<commit_before> #!/usr/bin/env python
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from gcecloudstack import app
from gcecloudstack import authentication
from gcecloudstack.services import requester
from gcecloudstack.controllers import errors
from flask import jsonify, request, url_for
import json


def _cloudstack_securitygroup_to_gce(response_item):
    rules = response_item['ingressrule']
    allowed = []
    sourceranges = []
    for rule in rules:
        ports = []
        for i in range():
            ports.append(i)
        allowed.append({
                       "IPProtocol": rule['protocol'],
                       "ports": ports
                       })
        sourceranges.append(rule['cidr'])
    return ({
            "kind": "compute#firewall",
            "selfLink": '',
            "id": response_item['id'],
            "creationTimestamp": '',
            "name": response_item['name'],
            "description": response_item['description'],
            "network": '',
            "sourceRanges": sourceranges,
            "sourceTags": [
                ''
            ],
            "targetTags": response_item['tags'],
            "allowed": allowed
            })


@app.route('/' + app.config['PATH'] + '<projectid>/global/firewalls',
           methods=['GET'])
@authentication.required
def listsecuritygroups(projectid, authorization):
    command = 'listSecurityGroups'
    args = {}
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )

    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for aggregated list Firewalls\n'
        'Project: ' + projectid + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    firewalls = []
    if cloudstack_response['listsecuritygroupsresponse']:
        for response_item in cloudstack_response['listsecuritygroupsresponse']['securitygroup']:
            firewalls.append(response_item)

    items = []
    for fw in firewalls:
        items.append(_cloudstack_securitygroup_to_gce(fw))

    populated_response = {
        'kind': 'compute#firewallList',
        'id': 'projects/' + projectid + '/global/firewalls',
        'selfLink': request.base_url,
        'items': items
    }

    res = jsonify(populated_response)
    res.status_code = 200
    return res


@app.route('/' + app.config['PATH'] +
           '<projectid>/global/firewalls/<firewall>',
           methods=['GET'])
@authentication.required
def getsecuritygroup(projectid, authorization, firewall):
    command = 'listSecurityGroups'
    args = {
        'securitygroupname': firewall
    }
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )
    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for get Firewall\n'
        'Project: ' + projectid + '\n' +
        'Firewall: ' + firewall + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    if cloudstack_response['listsecuritygroupsresponse']:
        response_item = cloudstack_response[
            'listsecuritygroupsresponse']['securitygroup'][0]
        firewall = _cloudstack_securitygroup_to_gce(response_item)
        res = jsonify(firewall)
        res.status_code = 200

    else:
        func_route = url_for('getsecuritygroup', projectid=projectid,
                             firewall=firewall)
        res = errors.resource_not_found(func_route)

    return res


@app.route(
    '/' + app.config['PATH'] + '<projectid>/global/firewalls/<firewall>',
    methods=['DELETE'])
@authentication.required
def deletesecuritygroup(projectid, authorization, firewall):
    command = 'deleteSecurityGroup'
    args = {'name': firewall}
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )

    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for deleting a Firewall \n'
        'Project: ' + projectid + '\n' +
        'Firewall: ' + firewall + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    # return Global Operations
    populated_response = {}

    res = jsonify(populated_response)
    res.status_code = 200
    return res<commit_msg>Adding insert and fixed issues in firewalls<commit_after> #!/usr/bin/env python
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from gcecloudstack import app
from gcecloudstack import authentication
from gcecloudstack.services import requester
from gcecloudstack.controllers import errors
from flask import jsonify, request, url_for
import json


def _cloudstack_securitygroup_to_gce(response_item):
    rules = response_item['ingressrule']
    allowed = []
    sourceranges = []
    for rule in rules:
        ports = []
        for i in range(rule['startport'], rule['endport']+1):
            ports.append(str(i))
        allowed.append({
                       "IPProtocol": rule['protocol'],
                       "ports": ports
                       })
        sourceranges.append(rule['cidr'])
    return ({
            "kind": "compute#firewall",
            "selfLink": '',
            "id": response_item['id'],
            "creationTimestamp": '',
            "name": response_item['name'],
            "description": response_item['description'],
            "network": '',
            "sourceRanges": sourceranges,
            "sourceTags": [
                ''
            ],
            "targetTags": response_item['tags'],
            "allowed": allowed
            })


@app.route('/' + app.config['PATH'] + '<projectid>/global/firewalls',
           methods=['GET'])
@authentication.required
def listsecuritygroups(projectid, authorization):
    command = 'listSecurityGroups'
    args = {}
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )

    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for aggregated list Firewalls\n'
        'Project: ' + projectid + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    firewalls = []
    if cloudstack_response['listsecuritygroupsresponse']:
        res = cloudstack_response['listsecuritygroupsresponse']
        for response_item in res['securitygroup']:
            firewalls.append(response_item)

    items = []
    for fw in firewalls:
        items.append(_cloudstack_securitygroup_to_gce(fw))

    populated_response = {
        'kind': 'compute#firewallList',
        'id': 'projects/' + projectid + '/global/firewalls',
        'selfLink': request.base_url,
        'items': items
    }

    res = jsonify(populated_response)
    res.status_code = 200
    return res


@app.route('/' + app.config['PATH'] +
           '<projectid>/global/firewalls/<firewall>',
           methods=['GET'])
@authentication.required
def getsecuritygroup(projectid, authorization, firewall):
    command = 'listSecurityGroups'
    args = {
        'securitygroupname': firewall
    }
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )
    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for get Firewall\n'
        'Project: ' + projectid + '\n' +
        'Firewall: ' + firewall + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    if cloudstack_response['listsecuritygroupsresponse']:
        response_item = cloudstack_response[
            'listsecuritygroupsresponse']['securitygroup'][0]
        firewall = _cloudstack_securitygroup_to_gce(response_item)
        res = jsonify(firewall)
        res.status_code = 200

    else:
        func_route = url_for('getsecuritygroup', projectid=projectid,
                             firewall=firewall)
        res = errors.resource_not_found(func_route)

    return res


@app.route(
    '/' + app.config['PATH'] + '<projectid>/global/firewalls/<firewall>',
    methods=['DELETE'])
@authentication.required
def deletesecuritygroup(projectid, authorization, firewall):
    command = 'deleteSecurityGroup'
    args = {'name': firewall}
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )

    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for deleting a Firewall \n'
        'Project: ' + projectid + '\n' +
        'Firewall: ' + firewall + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    # return Global Operations
    populated_response = {}

    res = jsonify(populated_response)
    res.status_code = 200
    return res


@app.route(
    '/' + app.config['PATH'] + '<projectid>/global/firewalls',
    methods=['POST'])
@authentication.required
def createsecuritygroup(projectid, authorization):
    command = 'createSecurityGroup'
    res = json.loads(request.data)
    args = {'name': res['name'],
            'description': res['description']}
    cloudstack_response = requester.make_request(
        command,
        args,
        authorization.jsessionid,
        authorization.sessionkey
    )

    cloudstack_response = json.loads(cloudstack_response)

    app.logger.debug(
        'Processing request for creating a Firewall \n'
        'Project: ' + projectid + '\n' +
        'Firewall: ' + res['name'] + '\n' +
        json.dumps(cloudstack_response, indent=4, separators=(',', ': '))
    )

    net_protocol_codes = {'1': 'icmp', '6': 'tcp', '17': 'udp'}

    rules = res['allowed']
    if rules is not []:
        for rule in rules:
            command = 'authorizeSecurityGroupIngress'
            args = {'securitygroupname': res['name'],
                    'protocol': net_protocol_codes[str(rule['IPProtocol'])],
                    'startport': rule['ports'][0],
                    'endport': rule['ports'][0],
                    'cidrlist': ','.join([cidr for cidr in
                                          res['sourceRanges']])}
            cloudstack_response = requester.make_request(
                command,
                args,
                authorization.jsessionid,
                authorization.sessionkey
            )

            cloudstack_response = json.loads(cloudstack_response)

            app.logger.debug(
                'Processing request for adding a rule to a Firewall \n'
                'Project: ' + projectid + '\n' +
                'Firewall: ' + res['name'] + '\n' +
                json.dumps(cloudstack_response,
                           indent=4, separators=(',', ': '))
            )

    # return Global Operations
    populated_response = {}
    res = jsonify(populated_response)
    res.status_code = 200
    return res
{'fraction_non_alphanumeric': 0.11253918495297806, 'fraction_numerical': 0.003761755485893417, 'mean_word_length': 2.585557740938466, 'pattern_counts': {'":': 26, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2218292', 'n_tokens_mistral': 3582, 'n_tokens_neox': 3472, 'n_words': 824}