<commit_before>
import requests
import json
from azure import constants
from azure import utils
import sys
from cloudify.exceptions import NonRecoverableError
from azure import WindowsAzureConflictError
from azure import WindowsAzureMissingResourceError
from cloudify import ctx
from cloudify.decorators import operation

@operation
def start(**_):
    #subscription_id = ctx.node.properties['subscription_id']
    location = ctx.node.properties['location']

@operation
def start_creation_validation(**_):
    for property_key in constants.COMMON_REQ_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

@operation
#resourcegroup:
def create_resource_group(**_):
    for property_key in constants.RESOURCE_GROUP_REQ_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

    resource_group_name = ctx.node.properties['resource_group_name']
    location = ctx.node.properties['location']
    resource_group_url = constants.resource_group_url
    ctx.logger.info("Checking availability of resource_group: " + resource_group_name)

    if resource_group_name not in [resource_group_name for rg in utils.list_all_rg()]:
        try:
            ctx.logger.info("Creating new Resource group: " + resource_group_name)
            rg_params=json.dumps({"name":resource_group_name,"location": location})
            response_rg = requests.put(url=resource_group_url, data=rg_params, headers=constants.headers)
            print response_rg.text
        except WindowsAzureConflictError:
            ctx.logger.info("Resource Group " + constants.resource_group_name + " could not be created")
            sys.exit(1)
    else:
        ctx.logger.info("Resource Group " + constants.resource_group_name + " has already been provisioned")

@operation
def resource_group_creation_validation(**_):
    resource_group_name = ctx.node.properties['resource_group_name']
    if resource_group_name in resource_group_name in [resource_group_name for rg in utils.list_all_rg()]:
        ctx.logger.info("Resource group: " + resource_group_name + " successfully created.")
    else:
        ctx.logger.info("Resource Group " + resource_group_name + " creation validation failed.")
        sys.exit(1)

@operation
def create_storage_account(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)
    storage_account_name = ctx.node.properties['storage_account_name']
    ctx.logger.info("Checking availability of storage account: " + storage_account_name)
    if storage_account_name not in [storage_account_name for sg in utils.list_all_sg()]:
        try:
            ctx.logger.info("Creating new storage account: " + storage_account_name)
            sg_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": constants.location})
            response_sg = requests.put(url=constants.storage_account_url, data=sg_params, headers=constants.headers)
            print response_sg.text
        except WindowsAzureConflictError:
            ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def storage_account_creation_validation(**_):
    storage_account_name = ctx.node.properties['storage_account_name']
    if storage_account_name in [storage_account_name for sg in utils.list_all_sg()]:
        ctx.logger.info("Storage account: " + storage_account_name + " successfully created.")
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " creation validation failed..")
        sys.exit(1)

@operation
#vnet:
def create_vnet(**_):
    for property_key in constants.VNET_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

vnet_name = ctx.node.properties['vnet_name']
location = ctx.node.properties['location']
vnet_url = constants.vnet_url
ctx.logger.info("Checking availability of virtual network: " + vnet_name)

if vnet_name not in [vnet_name for vnet in utils.list_all_vnet()]:
    try:
        ctx.logger.info("Creating new virtual network: " + vnet_name)

        vnet_params=json.dumps({"name":vnet_name, "location": location,"properties": {"addressSpace": {"addressPrefixes": constants.vnet_address_prefixes},"subnets": [{"name": constants.subnet_name, "properties": {"addressPrefix": constants.address_prefix}}]}})
        response_vnet = requests.put(url=vnet_url, data=vnet_params, headers=constants.headers)
        print response_vnet.text
    except WindowsAzureConflictError:
        ctx.logger.info("Virtual Network " + vnet_name + "could not be created.")
        sys.exit(1)
else:
    ctx.logger.info("Virtual Network" + vnet_name + "has already been provisioned by another user.")

def vnet_creation_validation(**_):
    vnet_name = ctx.node.properties['vnet_name']
    if vnet_name in [vnet_name for vnet in utils.list_all_vnet()]:
        ctx.logger.info("Virtual Network: " + vnet_name + " successfully created.")
    else:
        ctx.logger.info("Virtual Network " + vnet_name + " creation validation failed.")
        sys.exit(1)

@operation
#nic:
def create_nic():
    nic_name = ctx.node.properties['nic_name']
    nic_params=json.dumps({
                "location":constants.location,
                "properties":{
                    "ipConfigurations":[
                        {
                            "name":constants.ip_config_name,
                            "properties":{
                                "subnet":{
                                    "id":"/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Network/virtualNetworks/mdvnet/subnets/Subnet-1"
                                },
                                "privateIPAllocationMethod":"Dynamic",
                            }
                        }
                    ],
                }
            })
    response_nic = requests.put(url=constants.nic_url, data=nic_params, headers=constants.headers)
    print(response_nic.text)

#virtualmachine:

@operation
def create_vm_ubuntu_14_0_1(**_):
    for property_key in constants.VM_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

        vm_name = ctx.node.properties['vm_name']
        ctx.logger.info("Checking availability of virtual network: " + vm_name)
        if vm_name not in [vm_name for vm in utils.list_all_virtual_machines()]:
            try:
                ctx.logger.info("Creating new virtual machine: " + vm_name)

                vm_params_1=json.dumps(
                    {
                        "id":"/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Compute/virtualMachines/new",
                        "name":"new",
                        "type":constants.vm_type,
                        "location":constants.location,
                        "properties": {
                            "hardwareProfile": {
                                "vmSize": constants.vm_size
                            },
                            "osProfile": {
                                "computername": constants.computer_name,
                                "adminUsername": constants.admin_username,
                                "linuxConfiguration": {
                                    "disablePasswordAuthentication": "true",
                                    "ssh": {
                                        "publicKeys": [
                                            {
                                                "path": constants.key_path,
                                                "keyData": """---- BEGIN SSH2 PUBLIC KEY ----Comment: "rsa-key-20150804"AAAAB3NzaC1yc2EAAAABJQAAAQEA0Y5tAjA2C9xPLRMMfU37J3kGUYQzRAbPu2gN9HKKB+/bkzEE+W9zysYgL1vu3heqUewQlnMz2G6gfDca+6FmitMpZdz8E0ZYUy4MCG+fWs/6xT92OsVLAi2VRgQlyGqOD+KJEZdMnIbbWyPzaLC0yaUDEUNWe2hRNkr0daRY21UCCZG9+zZNR4ndJWxjJyF4Om1G4R5gruickOs5yECbgEMISpENWmXATc6UUsVhRznp4u6iBusZO3ilH7B3YbDyGhXs4X/TcwBj6zuWaJsHXzorTL621g4Ppp4Ig6QVQSrBpNBe2JCjou6tlGSBFm7vApUwAYaMStDzaIcLck/nUQ==---- END SSH2 PUBLIC KEY ----"""
                                            }
                                        ]
                                    }
                                }
                            },
                            "storageProfile": {
                                "imageReference": {
                                    "publisher": "Canonical",
                                    "offer": "UbuntuServer",
                                    "sku" : "14.04.2-LTS",
                                    "version":constants.vm_version
                                },
                                "osDisk" : {
                                    "name": constants.os_disk_name,
                                    "vhd": {
                                        "uri": "http://ruchikastorage.blob.core.windows.net/vhds/osdisk.vhd"
                                    },
                                    "caching": "ReadWrite",
                                    "createOption": "FromImage"
                                }
                            },
                            "networkProfile": {
                                "networkInterfaces": [
                                    {
                                        "id": "/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Network/networkInterfaces/nic"
                                    }
                                ]
                            }
                        }
                    })
                response_vm = requests.put(url=constants.vm_url, data=vm_params_1, headers=constants.headers)
                print(response_vm.text)
            except WindowsAzureConflictError:
              ctx.logger.info("Virtual Machine " + vm_name + "could not be created.")
              sys.exit(1)

    else:
     ctx.logger.info("Virtual Machine" + vm_name + "has already been provisioned by another user.")

def vm_creation_validation():
    vm_name = ctx.node.properties['vm_name']
    if vm_name in [vm_name for vms in utils.list_all_virtual_machines()]:
        ctx.logger.info("Virtual Machine: " + vm_name + " successfully created.")
    else:
        ctx.logger.info("Virtual Machine " + vm_name + " creation validation failed.")
        sys.exit(1)

<commit_msg>Update server.py<commit_after>
import requests
import json
from azure import constants
from azure import utils
import sys
from cloudify.exceptions import NonRecoverableError
from azure import WindowsAzureConflictError
from azure import WindowsAzureMissingResourceError
from cloudify import ctx
from cloudify.decorators import operation

@operation
def start(**_):
    #subscription_id = ctx.node.properties['subscription_id']
    location = ctx.node.properties['location']

@operation
def start_creation_validation(**_):
    for property_key in constants.COMMON_REQ_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

@operation
#resourcegroup:
def create_resource_group(**_):
    for property_key in constants.RESOURCE_GROUP_REQ_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

    resource_group_name = ctx.node.properties['resource_group_name']
    location = ctx.node.properties['location']
    resource_group_url = constants.resource_group_url
    ctx.logger.info("Checking availability of resource_group: " + resource_group_name)

    if resource_group_name not in [resource_group_name for rg in utils.list_all_rg()]:
        try:
            ctx.logger.info("Creating new Resource group: " + resource_group_name)
            rg_params=json.dumps({"name":resource_group_name,"location": location})
            response_rg = requests.put(url=resource_group_url, data=rg_params, headers=constants.headers)
            print response_rg.text
        except WindowsAzureConflictError:
            ctx.logger.info("Resource Group " + constants.resource_group_name + " could not be created")
            sys.exit(1)
    else:
        ctx.logger.info("Resource Group " + constants.resource_group_name + " has already been provisioned")

@operation
def resource_group_creation_validation(**_):
    resource_group_name = ctx.node.properties['resource_group_name']
    if resource_group_name in resource_group_name in [resource_group_name for rg in utils.list_all_rg()]:
        ctx.logger.info("Resource group: " + resource_group_name + " successfully created.")
    else:
        ctx.logger.info("Resource Group " + resource_group_name + " creation validation failed.")
        sys.exit(1)

@operation
def create_storage_account(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)
    storage_account_name = ctx.node.properties['storage_account_name']
    ctx.logger.info("Checking availability of storage account: " + storage_account_name)
    if storage_account_name not in [storage_account_name for sg in utils.list_all_sg()]:
        try:
            ctx.logger.info("Creating new storage account: " + storage_account_name)
            sg_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": constants.location})
            response_sg = requests.put(url=constants.storage_account_url, data=sg_params, headers=constants.headers)
            print response_sg.text
        except WindowsAzureConflictError:
            ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def storage_account_creation_validation(**_):
    storage_account_name = ctx.node.properties['storage_account_name']
    if storage_account_name in [storage_account_name for sg in utils.list_all_sg()]:
        ctx.logger.info("Storage account: " + storage_account_name + " successfully created.")
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " creation validation failed..")
        sys.exit(1)

@operation
#vnet:
def create_vnet(**_):
    for property_key in constants.VNET_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

vnet_name = ctx.node.properties['vnet_name']
location = ctx.node.properties['location']
vnet_url = constants.vnet_url
ctx.logger.info("Checking availability of virtual network: " + vnet_name)

if vnet_name not in [vnet_name for vnet in utils.list_all_vnet()]:
    try:
        ctx.logger.info("Creating new virtual network: " + vnet_name)

        vnet_params=json.dumps({"name":vnet_name, "location": location,"properties": {"addressSpace": {"addressPrefixes": constants.vnet_address_prefixes},"subnets": [{"name": constants.subnet_name, "properties": {"addressPrefix": constants.address_prefix}}]}})
        response_vnet = requests.put(url=vnet_url, data=vnet_params, headers=constants.headers)
        print response_vnet.text
    except WindowsAzureConflictError:
        ctx.logger.info("Virtual Network " + vnet_name + "could not be created.")
        sys.exit(1)
else:
    ctx.logger.info("Virtual Network" + vnet_name + "has already been provisioned by another user.")

def vnet_creation_validation(**_):
    vnet_name = ctx.node.properties['vnet_name']
    if vnet_name in [vnet_name for vnet in utils.list_all_vnet()]:
        ctx.logger.info("Virtual Network: " + vnet_name + " successfully created.")
    else:
        ctx.logger.info("Virtual Network " + vnet_name + " creation validation failed.")
        sys.exit(1)

@operation
#nic:
def create_nic():
    nic_name = ctx.node.properties['nic_name']
    nic_params=json.dumps({
                "location":constants.location,
                "properties":{
                    "ipConfigurations":[
                        {
                            "name":constants.ip_config_name,
                            "properties":{
                                "subnet":{
                                    "id":"/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Network/virtualNetworks/mdvnet/subnets/Subnet-1"
                                },
                                "privateIPAllocationMethod":"Dynamic",
                            }
                        }
                    ],
                }
            })
    response_nic = requests.put(url=constants.nic_url, data=nic_params, headers=constants.headers)
    print(response_nic.text)

#virtualmachine:

@operation
def create_vm(**_):
    for property_key in constants.VM_REQUIRED_PROPERTIES:
        utils.validate_node_property(property_key, ctx.node.properties)

        vm_name = ctx.node.properties['vm_name']
        ctx.logger.info("Checking availability of virtual network: " + vm_name)
        if vm_name not in [vm_name for vm in utils.list_all_virtual_machines()]:
            try:
                ctx.logger.info("Creating new virtual machine: " + vm_name)

                vm_params_1=json.dumps(
                    {
                        "id":"/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Compute/virtualMachines/new",
                        "name":"new",
                        "type":constants.vm_type,
                        "location":constants.location,
                        "properties": {
                            "hardwareProfile": {
                                "vmSize": constants.vm_size
                            },
                            "osProfile": {
                                "computername": constants.computer_name,
                                "adminUsername": constants.admin_username,
                                "linuxConfiguration": {
                                    "disablePasswordAuthentication": "true",
                                    "ssh": {
                                        "publicKeys": [
                                            {
                                                "path": constants.key_path,
                                                "keyData": <RSA Public key here>}
                                        ]
                                    }
                                }
                            },
                            "storageProfile": {
                                "imageReference": {
                                    "publisher": constants.image_reference_publisher,
                                    "offer": constants.image_reference_offer,
                                    "sku" : constants.image_reference_sku,
                                    "version":constants.vm_version
                                },
                                "osDisk" : {
                                    "name": constants.os_disk_name,
                                    "vhd": {
                                        "uri": "http://ruchikastorage.blob.core.windows.net/vhds/osdisk.vhd"
                                    },
                                    "caching": "ReadWrite",
                                    "createOption": "FromImage"
                                }
                            },
                            "networkProfile": {
                                "networkInterfaces": [
                                    {
                                        "id": "/subscriptions/"+constants.subscription_id+"/resourceGroups/maryland/providers/Microsoft.Network/networkInterfaces/nic"
                                    }
                                ]
                            }
                        }
                    })
                response_vm = requests.put(url=constants.vm_url, data=vm_params_1, headers=constants.headers)
                print(response_vm.text)
            except WindowsAzureConflictError:
              ctx.logger.info("Virtual Machine " + vm_name + "could not be created.")
              sys.exit(1)

    else:
     ctx.logger.info("Virtual Machine" + vm_name + "has already been provisioned by another user.")

def vm_creation_validation():
    vm_name = ctx.node.properties['vm_name']
    if vm_name in [vm_name for vms in utils.list_all_virtual_machines()]:
        ctx.logger.info("Virtual Machine: " + vm_name + " successfully created.")
    else:
        ctx.logger.info("Virtual Machine " + vm_name + " creation validation failed.")
        sys.exit(1)

<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import xmltodict
import dhtmlparser

# Variables ===================================================================
# Functions & classes =========================================================
def compose_mono_xml(mods_volume_xml):
    dom = dhtmlparser.parseString(mods_volume_xml)
    xdom = xmltodict.parse(mods_volume_xml)

    # parse title
    title = xdom["mods:mods"]["mods:titleInfo"]["mods:title"]

    # parse author
    author = dom.find("mods:name", {"type": "personal", "usage": "primary"})
    if not author:
        raise ValueError("Can't find 'author' in given MODS!")

    # filter proper <mods:namePart> tag (one which doesn't contain type="date"
    # attribute)
    author = filter(
        lambda x: x.params.get("type", False) != "date",
        author[0].find("mods:namePart")
    )
    if not author:
        raise ValueError("Can't find namePart for author!")
    author = author[0].getContent().decode("utf-8")

    # compose output template
    output = {
        "r:import": {
            "@xmlns:r": "http://resolver.nkp.cz/v3/",
            "r:monograph": {
                "r:titleInfo": {
                    "title": title,
                },
                "r:primaryOriginator": {
                    "@type": "AUTHOR",
                    "#text": author
                },
            },
        }
    }
    mono_root = output["r:import"]["r:monograph"]

    # get part title
    part_title = xdom["mods:mods"]["mods:titleInfo"].get("mods:partName", None)
    if part_title:
        mono_root["r:titleInfo"]["r:subTitle"] = part_title

    # parse form
    forms = dom.match("mods:mods", "mods:physicalDescription", "mods:form")
    if forms:
        forms = filter(lambda x: x.params.get("authority", "") == "gmd", forms)

        if forms:
            mono_root["r:documentType"] = forms[0].getContent().decode("utf-8")

    # parse publication info
    description = xdom["mods:mods"].get("mods:originInfo", None)
    if description:
        place = description.get("mods:place", None)
        if place:
            place = description["mods:place"].get("mods:placeTerm", None)
        publisher = description.get("mods:publisher", None)
        year = description.get("mods:dateIssued", None)

        if any([place, publisher, year]):
            mono_root["r:publication"] = {}

        if year:
            mono_root["r:publication"]["r:year"] = year
        if place:
            mono_root["r:publication"]["r:place"] = place["#text"]
        if publisher:
            mono_root["r:publication"]["r:publisher"] = publisher

    # parse identifiers
    identifiers = xdom["mods:mods"].get("mods:identifier", [])

    # handle ccnb
    ccnb = filter(lambda x: x.get("@type", False) == "ccnb", identifiers)
    if ccnb:
        mono_root["r:ccnb"] = ccnb

    # handle isbn
    isbn = filter(lambda x: x.get("@type", False) == "isbn", identifiers)
    if isbn:
        mono_root["r:isbn"] = isbn

    # handle uuid
    uuid = filter(lambda x: x.get("@type", False) == "uuid", identifiers)
    if uuid:
        mono_root["r:otherId"] = uuid

    return xmltodict.unparse(output, pretty=True)
<commit_msg>comose_mono_xml(); Added docstring.<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import xmltodict
import dhtmlparser

# Variables ===================================================================
# Functions & classes =========================================================
def compose_mono_xml(mods_volume_xml):
    """
    Convert MODS to XML, which is required by URN:NBN resolver.

    See:
        - http://resolver.nkp.cz/api/v3/digDocRegistration.xsd
        - https://code.google.com/p/czidlo/wiki/ApiV3

    Args:
        mods_volume_xml (str): MODS volume XML.

    Returns:
        str: XML for URN:NBN resolver.
    """
    dom = dhtmlparser.parseString(mods_volume_xml)
    xdom = xmltodict.parse(mods_volume_xml)

    # parse title
    title = xdom["mods:mods"]["mods:titleInfo"]["mods:title"]

    # parse author
    author = dom.find("mods:name", {"type": "personal", "usage": "primary"})
    if not author:
        raise ValueError("Can't find 'author' in given MODS!")

    # filter proper <mods:namePart> tag (one which doesn't contain type="date"
    # attribute)
    author = filter(
        lambda x: x.params.get("type", False) != "date",
        author[0].find("mods:namePart")
    )
    if not author:
        raise ValueError("Can't find namePart for author!")
    author = author[0].getContent().decode("utf-8")

    # compose output template
    output = {
        "r:import": {
            "@xmlns:r": "http://resolver.nkp.cz/v3/",
            "r:monograph": {
                "r:titleInfo": {
                    "title": title,
                },
                "r:primaryOriginator": {
                    "@type": "AUTHOR",
                    "#text": author
                },
            },
        }
    }
    mono_root = output["r:import"]["r:monograph"]

    # get part title
    part_title = xdom["mods:mods"]["mods:titleInfo"].get("mods:partName", None)
    if part_title:
        mono_root["r:titleInfo"]["r:subTitle"] = part_title

    # parse form
    forms = dom.match("mods:mods", "mods:physicalDescription", "mods:form")
    if forms:
        forms = filter(lambda x: x.params.get("authority", "") == "gmd", forms)

        if forms:
            mono_root["r:documentType"] = forms[0].getContent().decode("utf-8")

    # parse publication info
    description = xdom["mods:mods"].get("mods:originInfo", None)
    if description:
        place = description.get("mods:place", None)
        if place:
            place = description["mods:place"].get("mods:placeTerm", None)
        publisher = description.get("mods:publisher", None)
        year = description.get("mods:dateIssued", None)

        if any([place, publisher, year]):
            mono_root["r:publication"] = {}

        if year:
            mono_root["r:publication"]["r:year"] = year
        if place:
            mono_root["r:publication"]["r:place"] = place["#text"]
        if publisher:
            mono_root["r:publication"]["r:publisher"] = publisher

    # parse identifiers
    identifiers = xdom["mods:mods"].get("mods:identifier", [])

    # handle ccnb
    ccnb = filter(lambda x: x.get("@type", False) == "ccnb", identifiers)
    if ccnb:
        mono_root["r:ccnb"] = ccnb

    # handle isbn
    isbn = filter(lambda x: x.get("@type", False) == "isbn", identifiers)
    if isbn:
        mono_root["r:isbn"] = isbn

    # handle uuid
    uuid = filter(lambda x: x.get("@type", False) == "uuid", identifiers)
    if uuid:
        mono_root["r:otherId"] = uuid

    return xmltodict.unparse(output, pretty=True)
<|endoftext|>


<commit_before>#!/usr/bin/python3

import unittest
import pytest
import json
from io import StringIO
from gosa.common.components.jsonrpc_proxy import *

class JSONRPCProxyTestCase(unittest.TestCase):
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.urllib2")
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.dumps", wraps=json.dumps)
    def test_JSONRPCProxy(self, jsonDumpsMock, urllib2Mock):
        # ServiceURL is a optional argument and could be None through requests
        # (which of course would cause errors).

        def respError(*args, **kwargs):
            return StringIO("""{"error": "data", "result": null, "id": "jsonrpc"}""")
        def respSuccess(*args, **kwargs):
            return StringIO("""{"error": null, "result": "information", "id": "jsonrpc"}""")
        http_handler = unittest.mock.MagicMock()
        https_handler = unittest.mock.MagicMock()
        opener = unittest.mock.MagicMock()
        opener.open.side_effect = respSuccess

        urllib2Mock.HTTPHandler.return_value = http_handler
        urllib2Mock.HTTPSHandler.return_value = https_handler

        urllib2Mock.build_opener.return_value = opener

        sp = JSONServiceProxy()
        sp("test parameter", 1)
        jsonDumpsMock.assert_called_with({"method": None, "params": ("test parameter", 1), "id": "jsonrpc"})
        opener.open.side_effect = respError
        sp = sp.getProxy() # Recreates instance (with a few parameters gone)
        with pytest.raises(JSONRPCException):
            sp(test="TEST", digit=1)
        jsonDumpsMock.assert_called_with({"method": None, "params": {"test": "TEST", "digit": 1}, "id": "jsonrpc"})

        with pytest.raises(JSONRPCException):
            sp("positional arg", test="TEST", digit=1)

        opener.open.side_effect = respSuccess

        # Implementation checks if mode is "POST" and uses PostData to transmit the data.
        # Using any other mode will cause the data to be sent url-form-encoded.
        # Assuming "GET"
        sp = JSONServiceProxy(serviceURL="http://user:secret@localhost:8080/rpc", mode="GET")
        jsonDumpsMock.assert_called_with({"method": "login", "params": ("user", "secret"), "id": "jsonrpc"})
        # Username and password are omitted after initial login
        sp()
        opener.open.assert_called_with("http://localhost:8080/rpc?"+quote(dumps({"method": None, "params": (), "id": "jsonrpc"})))

        # Trigger line 173 - Expansion of __serviceName
        sp.name1.name2

        # What is line 186 doing?

    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.cookielib")
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.requests.utils")
    def test_XSRFCookieProcessor(self, requestsUtilsMock, cookielibMock):
        cookieJarMock = unittest.mock.MagicMock()
        cookielibMock.CookieJar.return_value = cookieJarMock

        request = unittest.mock.MagicMock()
        request.has_header.return_value = False

        response = unittest.mock.MagicMock()

        def extract_cookies(resp, req):
            assert resp == response
            assert req == request
        cookieJarMock.extract_cookies.side_effect = extract_cookies
        def dict_from_cookiejar(cookiejar):
            assert cookiejar == cookieJarMock
            return {"_xsrf": "TOKEN"}
        def dict_from_cookiejar_without_token(cookiejar):
            assert cookiejar == cookieJarMock
            return {}
        requestsUtilsMock.dict_from_cookiejar.side_effect = dict_from_cookiejar_without_token

        # Initial state
        cp = XSRFCookieProcessor()
        assert cp.has_token() == False
        assert cp.http_request(request) == request

        # first request
        request.has_header.assert_called_once_with("X-XSRFToken")
        cookieJarMock.add_cookie_header.assert_called_with(request)

        cp.http_response(request, response)
        cookieJarMock.extract_cookies.assert_called_with(response, request)
        requestsUtilsMock.dict_from_cookiejar.assert_called_with(cookieJarMock)

        # After the first request, there is still no token present
        assert cp.has_token() == False

        # first response
        requestsUtilsMock.dict_from_cookiejar.side_effect = dict_from_cookiejar
        cp.http_response(request, response)
        cookieJarMock.extract_cookies.assert_called_with(response, request)
        requestsUtilsMock.dict_from_cookiejar.assert_called_with(cookieJarMock)

        # after the arrival of a response with a token, there is a token present
        assert cp.has_token()

        # new request uses the token
        cp.http_request(request)
        request.has_header.assert_called_with("X-XSRFToken")
        request.add_unredirected_header.assert_called_with("X-XSRFToken", "TOKEN")
        cookieJarMock.add_cookie_header.assert_called_with(request)

        # if a token is already present in the given request, a it is not added
        # to the request, but to the cookiejar.
        countRequestAdded = request.add_unredirected_header.call_count
        request.has_header.return_value = True
        cp.http_request(request)
        assert countRequestAdded == request.add_unredirected_header.call_count

<commit_msg>Tests for JSONObjectFactory<commit_after>#!/usr/bin/python3

import unittest
import pytest
import json
from io import StringIO
from gosa.common.components.jsonrpc_proxy import *

class JSONRPCProxyTestCase(unittest.TestCase):
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.urllib2")
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.dumps", wraps=json.dumps)
    def test_JSONRPCProxy(self, jsonDumpsMock, urllib2Mock):
        # ServiceURL is a optional argument and could be None through requests
        # (which of course would cause errors).

        def respError(*args, **kwargs):
            return StringIO("""{"error": "data", "result": null, "id": "jsonrpc"}""")
        def respSuccess(*args, **kwargs):
            return StringIO("""{"error": null, "result": "information", "id": "jsonrpc"}""")
        http_handler = unittest.mock.MagicMock()
        https_handler = unittest.mock.MagicMock()
        opener = unittest.mock.MagicMock()
        opener.open.side_effect = respSuccess

        urllib2Mock.HTTPHandler.return_value = http_handler
        urllib2Mock.HTTPSHandler.return_value = https_handler

        urllib2Mock.build_opener.return_value = opener

        sp = JSONServiceProxy()
        sp("test parameter", 1)
        jsonDumpsMock.assert_called_with({"method": None, "params": ("test parameter", 1), "id": "jsonrpc"})
        opener.open.side_effect = respError
        sp = sp.getProxy() # Recreates instance (with a few parameters gone)
        with pytest.raises(JSONRPCException):
            sp(test="TEST", digit=1)
        jsonDumpsMock.assert_called_with({"method": None, "params": {"test": "TEST", "digit": 1}, "id": "jsonrpc"})

        with pytest.raises(JSONRPCException):
            sp("positional arg", test="TEST", digit=1)

        opener.open.side_effect = respSuccess

        # Implementation checks if mode is "POST" and uses PostData to transmit the data.
        # Using any other mode will cause the data to be sent url-form-encoded.
        # Assuming "GET"
        sp = JSONServiceProxy(serviceURL="http://user:secret@localhost:8080/rpc", mode="GET")
        jsonDumpsMock.assert_called_with({"method": "login", "params": ("user", "secret"), "id": "jsonrpc"})
        # Username and password are omitted after initial login
        sp()
        opener.open.assert_called_with("http://localhost:8080/rpc?"+quote(dumps({"method": None, "params": (), "id": "jsonrpc"})))

        # Trigger line 173 - Expansion of __serviceName
        sp.name1.name2

    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.cookielib")
    @unittest.mock.patch("gosa.common.components.jsonrpc_proxy.requests.utils")
    def test_XSRFCookieProcessor(self, requestsUtilsMock, cookielibMock):
        cookieJarMock = unittest.mock.MagicMock()
        cookielibMock.CookieJar.return_value = cookieJarMock

        request = unittest.mock.MagicMock()
        request.has_header.return_value = False

        response = unittest.mock.MagicMock()

        def extract_cookies(resp, req):
            assert resp == response
            assert req == request
        cookieJarMock.extract_cookies.side_effect = extract_cookies
        def dict_from_cookiejar(cookiejar):
            assert cookiejar == cookieJarMock
            return {"_xsrf": "TOKEN"}
        def dict_from_cookiejar_without_token(cookiejar):
            assert cookiejar == cookieJarMock
            return {}
        requestsUtilsMock.dict_from_cookiejar.side_effect = dict_from_cookiejar_without_token

        # Initial state
        cp = XSRFCookieProcessor()
        assert cp.has_token() == False
        assert cp.http_request(request) == request

        # first request
        request.has_header.assert_called_once_with("X-XSRFToken")
        cookieJarMock.add_cookie_header.assert_called_with(request)

        cp.http_response(request, response)
        cookieJarMock.extract_cookies.assert_called_with(response, request)
        requestsUtilsMock.dict_from_cookiejar.assert_called_with(cookieJarMock)

        # After the first request, there is still no token present
        assert cp.has_token() == False

        # first response
        requestsUtilsMock.dict_from_cookiejar.side_effect = dict_from_cookiejar
        cp.http_response(request, response)
        cookieJarMock.extract_cookies.assert_called_with(response, request)
        requestsUtilsMock.dict_from_cookiejar.assert_called_with(cookieJarMock)

        # after the arrival of a response with a token, there is a token present
        assert cp.has_token()

        # new request uses the token
        cp.http_request(request)
        request.has_header.assert_called_with("X-XSRFToken")
        request.add_unredirected_header.assert_called_with("X-XSRFToken", "TOKEN")
        cookieJarMock.add_cookie_header.assert_called_with(request)

        # if a token is already present in the given request, a it is not added
        # to the request, but to the cookiejar.
        countRequestAdded = request.add_unredirected_header.call_count
        request.has_header.return_value = True
        cp.http_request(request)
        assert countRequestAdded == request.add_unredirected_header.call_count

    def test_JSONObjectFactory(self):
        import uuid
        object_uuid = str(uuid.uuid4())

        def dispatchObjectMethod(ref, name, *args):
            # Note: No keyword arguments are forwarded.
            assert ref == object_uuid
            assert name == "testfunction"
            assert args == ("required parameter",)
            return "success"

        proxy = unittest.mock.MagicMock()
        proxy.dispatchObjectMethod.side_effect = dispatchObjectMethod

        of = JSONObjectFactory.get_instance(proxy,
                "TestType",
                object_uuid,
                "dc=test,dc=de",
                "tests.common.components.test_jsonrpc_proxy.TestType",
                ("testfunction"),
                ("attr1", "attr2"),
                {"attr1": "Data1", "attr2": "Data2"})
        assert of.uuid == object_uuid
        assert of.dn == "dc=test,dc=de"
        assert of.testfunction("required parameter") == "success"
        assert of.attr1 == "Data1"
        assert of.attr2 == "Data2"
        with pytest.raises(AttributeError):
            of.attr3

        of.attr2 = "Data"
        assert of.attr2 == "Data"
        with pytest.raises(AttributeError):
            of.attr3 = "TEST"

        assert repr(of) == object.__getattribute__(of, "ref") == object_uuid
<|endoftext|>


<commit_before>import os, binascii

def unique_hex(byte_length=4):
    return binascii.hexlify(os.urandom(byte_length)).decode()

if __name__ == '__main__':
    print(unique_hex())

<commit_msg>Adding natural_sort method<commit_after>import os, binascii
import re

def unique_hex(byte_length=4):
    return binascii.hexlify(os.urandom(byte_length)).decode()

def natural_sort(item):
    """
    Sort strings that contain numbers correctly.

    >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
    >>> l.sort(key=natural_sort)
    >>> print l
    "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
    """
    if item is None:
        return 0

    def try_int(s):
        try:
            return int(s)
        except ValueError:
            return s
    return map(try_int, re.findall(r'(\d+|\D+)', item))

if __name__ == '__main__':
    print(unique_hex())

<|endoftext|>


<commit_before>"""
Support for KNX/IP climate devices.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.knx/
"""
import asyncio
import voluptuous as vol

from custom_components.xknx import DATA_XKNX, ATTR_DISCOVER_DEVICES
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice
from homeassistant.const import CONF_NAME, TEMP_CELSIUS, ATTR_TEMPERATURE
from homeassistant.util.temperature import convert as convert_temperature
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv

CONF_SETPOINT_SHIFT_ADDRESS = 'setpoint_shift_address'
CONF_SETPOINT_SHIFT_STATE_ADDRESS = 'setpoint_shift_state_address'
CONF_SETPOINT_SHIFT_STEP = 'setpoint_shift_step'
CONF_SETPOINT_SHIFT_MAX = 'setpoint_shift_max'
CONF_SETPOINT_SHIFT_MIN = 'setpoint_shift_min'
CONF_TEMPERATURE_ADDRESS = 'temperature_address'
CONF_TARGET_TEMPERATURE_ADDRESS = 'target_temperature_address'
CONF_OPERATION_MODE_ADDRESS = 'operation_mode_address'
CONF_OPERATION_MODE_STATE_ADDRESS = 'operation_mode_state_address'
CONF_CONTROLLER_STATUS_ADDRESS = 'controller_status_address'
CONF_CONTROLLER_STATUS_STATE_ADDRESS = 'controller_status_state_address'
CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS = \
    'operation_mode_frost_protection_address'
CONF_OPERATION_MODE_NIGHT_ADDRESS = 'operation_mode_night_address'
CONF_OPERATION_MODE_COMFORT_ADDRESS = 'operation_mode_comfort_address'

DEFAULT_NAME = 'XKNX Climate'
DEFAULT_SETPOINT_SHIFT_STEP = 0.5
DEFAULT_SETPOINT_SHIFT_MAX = 6
DEFAULT_SETPOINT_SHIFT_MIN = -6
DEPENDENCIES = ['xknx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Required(CONF_TEMPERATURE_ADDRESS): cv.string,
    vol.Required(CONF_TARGET_TEMPERATURE_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_STEP, default=DEFAULT_SETPOINT_SHIFT_STEP):
        vol.All(float, vol.Range(min=0, max=2)),
    vol.Optional(CONF_SETPOINT_SHIFT_MAX, default=DEFAULT_SETPOINT_SHIFT_MAX):
        vol.All(int, vol.Range(min=-32, max=0)),
    vol.Optional(CONF_SETPOINT_SHIFT_MIN, default=DEFAULT_SETPOINT_SHIFT_MIN):
        vol.All(int, vol.Range(min=0, max=32)),
    vol.Optional(CONF_OPERATION_MODE_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_CONTROLLER_STATUS_ADDRESS): cv.string,
    vol.Optional(CONF_CONTROLLER_STATUS_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_NIGHT_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_COMFORT_ADDRESS): cv.string,
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices,
                         discovery_info=None):
    """Set up climate(s) for KNX platform."""
    if DATA_XKNX not in hass.data \
            or not hass.data[DATA_XKNX].initialized:
        return False

    if discovery_info is not None:
        async_add_devices_discovery(hass, discovery_info, async_add_devices)
    else:
        async_add_devices_config(hass, config, async_add_devices)

    return True

@callback
def async_add_devices_discovery(hass, discovery_info, async_add_devices):
    """Set up climates for KNX platform configured within plattform."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_XKNX].xknx.devices[device_name]
        entities.append(KNXClimate(hass, device))
    async_add_devices(entities)

@callback
def async_add_devices_config(hass, config, async_add_devices):
    """Set up climate for KNX platform configured within plattform."""
    import xknx

    climate = xknx.devices.Climate(
        hass.data[DATA_XKNX].xknx,
        name=config.get(CONF_NAME),
        group_address_temperature=config.get(
            CONF_TEMPERATURE_ADDRESS),
        group_address_target_temperature=config.get(
            CONF_TARGET_TEMPERATURE_ADDRESS),
        group_address_setpoint_shift=config.get(
            CONF_SETPOINT_SHIFT_ADDRESS),
        group_address_setpoint_shift_state=config.get(
            CONF_SETPOINT_SHIFT_STATE_ADDRESS),
        setpoint_shift_step=config.get(
            CONF_SETPOINT_SHIFT_STEP),
        setpoint_shift_max=config.get(
            CONF_SETPOINT_SHIFT_MAX),
        setpoint_shift_min=config.get(
            CONF_SETPOINT_SHIFT_MIN),
        group_address_operation_mode=config.get(
            CONF_OPERATION_MODE_ADDRESS),
        group_address_operation_mode_state=config.get(
            CONF_OPERATION_MODE_STATE_ADDRESS),
        group_address_controller_status=config.get(
            CONF_CONTROLLER_STATUS_ADDRESS),
        group_address_controller_status_state=config.get(
            CONF_CONTROLLER_STATUS_STATE_ADDRESS),
        group_address_operation_mode_protection=config.get(
            CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS),
        group_address_operation_mode_night=config.get(
            CONF_OPERATION_MODE_NIGHT_ADDRESS),
        group_address_operation_mode_comfort=config.get(
            CONF_OPERATION_MODE_COMFORT_ADDRESS))
    hass.data[DATA_XKNX].xknx.devices.add(climate)
    async_add_devices([KNXClimate(hass, climate)])

class KNXClimate(ClimateDevice):
    """Representation of a KNX climate."""

    def __init__(self, hass, device):
        """Initialization of KNXClimate."""
        self.device = device
        self.hass = hass
        self.async_register_callbacks()

        self._unit_of_measurement = TEMP_CELSIUS
        self._away = False  # not yet supported
        self._is_fan_on = False  # not yet supported

    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        @asyncio.coroutine
        def after_update_callback(device):
            """Callback after device was updated."""
            # pylint: disable=unused-argument
            yield from self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def temperature_unit(self):
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @property
    def current_temperature(self):
        """Return the current temperature."""
        return self.device.temperature.value

    @property
    def target_temperature_step(self):
        """Return the supported step of target temperature."""
        return self.device.setpoint_shift_step

    @property
    def target_temperature(self):
        """Return the temperature we try to reach."""
        return self.device.target_temperature.value

    @property
    def min_temp(self):
        """Return the minimum temperature."""
        return convert_temperature(
            self.device.target_temperature_min,
            TEMP_CELSIUS,
            self.temperature_unit)

    @property
    def max_temp(self):
        """Return the maximum temperature."""
        return convert_temperature(
            self.device.target_temperature_max,
            TEMP_CELSIUS,
            self.temperature_unit)

    @asyncio.coroutine
    def async_set_temperature(self, **kwargs):
        """Set new target temperature."""
        temperature = kwargs.get(ATTR_TEMPERATURE)
        if temperature is None:
            return
        yield from self.device.set_target_temperature(temperature)
        yield from self.async_update_ha_state()

    @property
    def current_operation(self):
        """Return current operation ie. heat, cool, idle."""
        if self.device.supports_operation_mode:
            return self.device.operation_mode.value
        return None

    @property
    def operation_list(self):
        """Return the list of available operation modes."""
        return [operation_mode.value for
                operation_mode in
                self.device.get_supported_operation_modes()]

    @asyncio.coroutine
    def async_set_operation_mode(self, operation_mode):
        """Set operation mode."""
        if self.device.supports_operation_mode:
            from xknx.knx import HVACOperationMode
            knx_operation_mode = HVACOperationMode(operation_mode)
            yield from self.device.set_operation_mode(knx_operation_mode)
<commit_msg>HASS Plugin: updated climate plattform:<commit_after>"""
Support for KNX/IP climate devices.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.knx/
"""
import asyncio
import voluptuous as vol

from custom_components.xknx import DATA_XKNX, ATTR_DISCOVER_DEVICES
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice
from homeassistant.const import CONF_NAME, TEMP_CELSIUS, ATTR_TEMPERATURE
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv

CONF_SETPOINT_SHIFT_ADDRESS = 'setpoint_shift_address'
CONF_SETPOINT_SHIFT_STATE_ADDRESS = 'setpoint_shift_state_address'
CONF_SETPOINT_SHIFT_STEP = 'setpoint_shift_step'
CONF_SETPOINT_SHIFT_MAX = 'setpoint_shift_max'
CONF_SETPOINT_SHIFT_MIN = 'setpoint_shift_min'
CONF_TEMPERATURE_ADDRESS = 'temperature_address'
CONF_TARGET_TEMPERATURE_ADDRESS = 'target_temperature_address'
CONF_OPERATION_MODE_ADDRESS = 'operation_mode_address'
CONF_OPERATION_MODE_STATE_ADDRESS = 'operation_mode_state_address'
CONF_CONTROLLER_STATUS_ADDRESS = 'controller_status_address'
CONF_CONTROLLER_STATUS_STATE_ADDRESS = 'controller_status_state_address'
CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS = \
    'operation_mode_frost_protection_address'
CONF_OPERATION_MODE_NIGHT_ADDRESS = 'operation_mode_night_address'
CONF_OPERATION_MODE_COMFORT_ADDRESS = 'operation_mode_comfort_address'

DEFAULT_NAME = 'XKNX Climate'
DEFAULT_SETPOINT_SHIFT_STEP = 0.5
DEFAULT_SETPOINT_SHIFT_MAX = 6
DEFAULT_SETPOINT_SHIFT_MIN = -6
DEPENDENCIES = ['xknx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Required(CONF_TEMPERATURE_ADDRESS): cv.string,
    vol.Required(CONF_TARGET_TEMPERATURE_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_SETPOINT_SHIFT_STEP,
                 default=DEFAULT_SETPOINT_SHIFT_STEP): vol.All(
                     float, vol.Range(min=0, max=2)),
    vol.Optional(CONF_SETPOINT_SHIFT_MAX, default=DEFAULT_SETPOINT_SHIFT_MAX):
        vol.All(int, vol.Range(min=-32, max=0)),
    vol.Optional(CONF_SETPOINT_SHIFT_MIN, default=DEFAULT_SETPOINT_SHIFT_MIN):
        vol.All(int, vol.Range(min=0, max=32)),
    vol.Optional(CONF_OPERATION_MODE_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_CONTROLLER_STATUS_ADDRESS): cv.string,
    vol.Optional(CONF_CONTROLLER_STATUS_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_NIGHT_ADDRESS): cv.string,
    vol.Optional(CONF_OPERATION_MODE_COMFORT_ADDRESS): cv.string,
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices,
                         discovery_info=None):
    """Set up climate(s) for KNX platform."""
    if DATA_XKNX not in hass.data \
            or not hass.data[DATA_XKNX].initialized:
        return False

    if discovery_info is not None:
        async_add_devices_discovery(hass, discovery_info, async_add_devices)
    else:
        async_add_devices_config(hass, config, async_add_devices)

    return True

@callback
def async_add_devices_discovery(hass, discovery_info, async_add_devices):
    """Set up climates for KNX platform configured within plattform."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_XKNX].xknx.devices[device_name]
        entities.append(KNXClimate(hass, device))
    async_add_devices(entities)

@callback
def async_add_devices_config(hass, config, async_add_devices):
    """Set up climate for KNX platform configured within plattform."""
    import xknx

    climate = xknx.devices.Climate(
        hass.data[DATA_XKNX].xknx,
        name=config.get(CONF_NAME),
        group_address_temperature=config.get(
            CONF_TEMPERATURE_ADDRESS),
        group_address_target_temperature=config.get(
            CONF_TARGET_TEMPERATURE_ADDRESS),
        group_address_setpoint_shift=config.get(
            CONF_SETPOINT_SHIFT_ADDRESS),
        group_address_setpoint_shift_state=config.get(
            CONF_SETPOINT_SHIFT_STATE_ADDRESS),
        setpoint_shift_step=config.get(
            CONF_SETPOINT_SHIFT_STEP),
        setpoint_shift_max=config.get(
            CONF_SETPOINT_SHIFT_MAX),
        setpoint_shift_min=config.get(
            CONF_SETPOINT_SHIFT_MIN),
        group_address_operation_mode=config.get(
            CONF_OPERATION_MODE_ADDRESS),
        group_address_operation_mode_state=config.get(
            CONF_OPERATION_MODE_STATE_ADDRESS),
        group_address_controller_status=config.get(
            CONF_CONTROLLER_STATUS_ADDRESS),
        group_address_controller_status_state=config.get(
            CONF_CONTROLLER_STATUS_STATE_ADDRESS),
        group_address_operation_mode_protection=config.get(
            CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS),
        group_address_operation_mode_night=config.get(
            CONF_OPERATION_MODE_NIGHT_ADDRESS),
        group_address_operation_mode_comfort=config.get(
            CONF_OPERATION_MODE_COMFORT_ADDRESS))
    hass.data[DATA_XKNX].xknx.devices.add(climate)
    async_add_devices([KNXClimate(hass, climate)])

class KNXClimate(ClimateDevice):
    """Representation of a KNX climate."""

    def __init__(self, hass, device):
        """Initialization of KNXClimate."""
        self.device = device
        self.hass = hass
        self.async_register_callbacks()

        self._unit_of_measurement = TEMP_CELSIUS

    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        @asyncio.coroutine
        def after_update_callback(device):
            """Callback after device was updated."""
            # pylint: disable=unused-argument
            yield from self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def temperature_unit(self):
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @property
    def current_temperature(self):
        """Return the current temperature."""
        return self.device.temperature.value

    @property
    def target_temperature_step(self):
        """Return the supported step of target temperature."""
        return self.device.setpoint_shift_step

    @property
    def target_temperature(self):
        """Return the temperature we try to reach."""
        return self.device.target_temperature.value

    @property
    def min_temp(self):
        """Return the minimum temperature."""
        return self.device.target_temperature_min

    @property
    def max_temp(self):
        """Return the maximum temperature."""
        return self.device.target_temperature_max

    @asyncio.coroutine
    def async_set_temperature(self, **kwargs):
        """Set new target temperature."""
        temperature = kwargs.get(ATTR_TEMPERATURE)
        if temperature is None:
            return
        yield from self.device.set_target_temperature(temperature)
        yield from self.async_update_ha_state()

    @property
    def current_operation(self):
        """Return current operation ie. heat, cool, idle."""
        if self.device.supports_operation_mode:
            return self.device.operation_mode.value
        return None

    @property
    def operation_list(self):
        """Return the list of available operation modes."""
        return [operation_mode.value for
                operation_mode in
                self.device.get_supported_operation_modes()]

    @asyncio.coroutine
    def async_set_operation_mode(self, operation_mode):
        """Set operation mode."""
        if self.device.supports_operation_mode:
            from xknx.knx import HVACOperationMode
            knx_operation_mode = HVACOperationMode(operation_mode)
            yield from self.device.set_operation_mode(knx_operation_mode)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright (c) 2013, Camptocamp SA
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.

from unittest import TestCase
from nose.plugins.attrib import attr

import transaction
import os
from pyramid import testing

from c2cgeoportal.tests.functional import (  # NOQA
        tearDownCommon as tearDownModule,
        setUpCommon as setUpModule,
        mapserv_url, host)

@attr(functional=True)
class TestMobileDesktop(TestCase):

    def setUp(self):
        self.config = testing.setUp()

        from c2cgeoportal.models import DBSession, Layer, Theme

        layer = Layer(name=u'__test_layer')

        mobile_only_layer = Layer(name=u'__test_mobile_only_layer')
        mobile_only_layer.inDesktopViewer = False

        desktop_only_layer = Layer(name=u'__test_desktop_only_layer')
        desktop_only_layer.inMobileViewer = False

        theme = Theme(name=u'__test_theme')
        theme.children = [layer, mobile_only_layer, desktop_only_layer]

        mobile_only_theme = Theme(name=u'__test_mobile_only_theme')
        mobile_only_theme.children = [layer]
        mobile_only_theme.inDesktopViewer = False

        desktop_only_theme = Theme(name=u'__test_desktop_only_theme')
        desktop_only_theme.children = [layer]
        desktop_only_theme.inMobileViewer = False

        # the following theme should not appear in the list of themes on desktop
        # nor on mobile
        # It should be accessible by explicitely loading it in mobile though
        mobile_private_theme = Theme(name=u'__test_mobile_private_theme')
        mobile_private_theme.children = [layer]
        mobile_private_theme.inDesktopViewer = False
        mobile_private_theme.inMobileViewer = False

        DBSession.add_all([layer, mobile_only_layer, desktop_only_layer, theme,
            mobile_only_theme, desktop_only_theme, mobile_private_theme])
        transaction.commit()

    def tearDown(self):
        testing.tearDown()

        from c2cgeoportal.models import DBSession, Layer, \
                Theme, LayerGroup, Role

        for t in DBSession.query(Theme).all():
            DBSession.delete(t)
        for layergroup in DBSession.query(LayerGroup).all():
            DBSession.delete(layergroup)  # pragma: nocover
        for layer in DBSession.query(Layer).all():
            DBSession.delete(layer)  # pragma: nocover

        transaction.commit()

    def _create_entry_obj(self, username=None, params={}):
        from c2cgeoportal.models import DBSession, User
        from c2cgeoportal.views.entry import Entry

        mapfile = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'c2cgeoportal_test.map'
        )
        mapserv = "%s?map=%s&" % (mapserv_url, mapfile)
        request = testing.DummyRequest()
        request.headers['Host'] = host
        request.registry.settings = {
            'mapserv_url': mapserv,
        }
        mapserv = "%s?map=%s&" % (mapserv_url, mapfile)
        request.static_url = lambda url: '/dummy/static/url'
        request.route_url = lambda url: mapserv
        request.params = params

        request.user = None

        return Entry(request)

    def test_mobile_themes(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()

        self.assertEqual(len(response['themes']), 2)

    def test_mobile_private_theme(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()
        entry.request.registry.settings['functionalities'] = {
            'anonymous': {
                'mobile_default_theme': u'__test_mobile_private_theme'
            }
        }
        response = entry.mobileconfig()

        layers = response['layers'].split(',')
        self.assertEqual(len(layers), 1)

    def test_desktop_themes(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()

        self.assertEqual(len(response['themes']), 2)

    def test_mobile_layers(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        entry.request.registry.settings['functionalities'] = {
            'anonymous': {
                'mobile_default_theme': u'__test_theme'
            }
        }
        response = entry.mobileconfig()

        layers = response['layers'].split(',')
        self.assertEqual(len(layers), 2)

    def test_desktop_layers(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.viewer()

        import json
        themes = json.loads(response['themes'])
        theme = themes[0]

        layers = theme['children']
        self.assertEqual(len(layers), 2)
<commit_msg>Fix mobile theme test<commit_after># -*- coding: utf-8 -*-

# Copyright (c) 2013, Camptocamp SA
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.

from unittest import TestCase
from nose.plugins.attrib import attr

import transaction
import os
from pyramid import testing

from c2cgeoportal.tests.functional import (  # NOQA
        tearDownCommon as tearDownModule,
        setUpCommon as setUpModule,
        mapserv_url, host)

@attr(functional=True)
class TestMobileDesktop(TestCase):

    def setUp(self):
        self.config = testing.setUp()

        from c2cgeoportal.models import DBSession, Layer, Theme

        layer = Layer(name=u'__test_layer')

        mobile_only_layer = Layer(name=u'__test_mobile_only_layer')
        mobile_only_layer.inDesktopViewer = False

        desktop_only_layer = Layer(name=u'__test_desktop_only_layer')
        desktop_only_layer.inMobileViewer = False

        theme = Theme(name=u'__test_theme')
        theme.children = [layer, mobile_only_layer, desktop_only_layer]
        theme.inMobileViewer = True

        mobile_only_theme = Theme(name=u'__test_mobile_only_theme')
        mobile_only_theme.children = [layer]
        mobile_only_theme.inDesktopViewer = False
        mobile_only_theme.inMobileViewer = True

        desktop_only_theme = Theme(name=u'__test_desktop_only_theme')
        desktop_only_theme.children = [layer]
        desktop_only_theme.inMobileViewer = False

        # the following theme should not appear in the list of themes on desktop
        # nor on mobile
        # It should be accessible by explicitely loading it in mobile though
        mobile_private_theme = Theme(name=u'__test_mobile_private_theme')
        mobile_private_theme.children = [layer]
        mobile_private_theme.inDesktopViewer = False
        mobile_private_theme.inMobileViewer = False

        DBSession.add_all([layer, mobile_only_layer, desktop_only_layer, theme,
            mobile_only_theme, desktop_only_theme, mobile_private_theme])
        transaction.commit()

    def tearDown(self):
        testing.tearDown()

        from c2cgeoportal.models import DBSession, Layer, \
                Theme, LayerGroup, Role

        for t in DBSession.query(Theme).all():
            DBSession.delete(t)
        for layergroup in DBSession.query(LayerGroup).all():
            DBSession.delete(layergroup)  # pragma: nocover
        for layer in DBSession.query(Layer).all():
            DBSession.delete(layer)  # pragma: nocover

        transaction.commit()

    def _create_entry_obj(self, username=None, params={}):
        from c2cgeoportal.models import DBSession, User
        from c2cgeoportal.views.entry import Entry

        mapfile = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'c2cgeoportal_test.map'
        )
        mapserv = "%s?map=%s&" % (mapserv_url, mapfile)
        request = testing.DummyRequest()
        request.headers['Host'] = host
        request.registry.settings = {
            'mapserv_url': mapserv,
        }
        mapserv = "%s?map=%s&" % (mapserv_url, mapfile)
        request.static_url = lambda url: '/dummy/static/url'
        request.route_url = lambda url: mapserv
        request.params = params

        request.user = None

        return Entry(request)

    def test_mobile_themes(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()

        import json
        themes = json.loads(response['themes'])
        self.assertEqual(len(themes), 2)
        self.assertEqual(
            themes,
            [{
                "name": "__test_theme",
                "icon": "/dummy/static/url"
            }, {
                "name": "__test_mobile_only_theme",
                "icon": "/dummy/static/url"
            }]
        )

    def test_mobile_private_theme(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()
        entry.request.registry.settings['functionalities'] = {
            'anonymous': {
                'mobile_default_theme': u'__test_mobile_private_theme'
            }
        }
        response = entry.mobileconfig()

        layers = response['layers'].split(',')
        self.assertEqual(len(layers), 1)
        self.assertEqual(layers[0], '__test_layer')

    def test_desktop_themes(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.mobileconfig()

        import json
        themes = json.loads(response['themes'])
        self.assertEqual(len(themes), 2)
        self.assertEqual(
            themes,
            [{
                "name": "__test_theme",
                "icon": "/dummy/static/url"
            }, {
                "name": "__test_mobile_only_theme",
                "icon": "/dummy/static/url"
            }]
        )

    def test_mobile_layers(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        entry.request.registry.settings['functionalities'] = {
            'anonymous': {
                'mobile_default_theme': u'__test_theme'
            }
        }
        response = entry.mobileconfig()

        layers = response['layers'].split(',')
        self.assertEqual(len(layers), 2)

    def test_desktop_layers(self):
        from c2cgeoportal.models import DBSession, Layer, Theme

        entry = self._create_entry_obj()
        response = entry.viewer()

        import json
        themes = json.loads(response['themes'])
        theme = themes[0]

        layers = theme['children']
        self.assertEqual(len(layers), 2)
        self.assertEqual(
            layers,
            [{
                u'name': u'__test_layer',
                u'isLegendExpanded': False,
                u'legend': True,
                u'public': True,
                u'isChecked': True,
                u'type': u'internal WMS',
                u'id': 1,
                u'imageType': None
            }, {
                u'name': u'__test_desktop_only_layer',
                u'isLegendExpanded': False,
                u'legend': True,
                u'public': True,
                u'isChecked': True,
                u'type': u'internal WMS',
                u'id': 4,
                u'imageType': None
            }]
        )
<|endoftext|>


<commit_before># Licensed 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.

import logging
import json

from django import http
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from horizon import forms

from openstack_dashboard import api
from openstack_dashboard import fiware_api
from openstack_dashboard.dashboards.idm_admin.user_accounts \
    import forms as user_accounts_forms
from openstack_dashboard.dashboards.idm_admin \
    import utils as idm_admin_utils

LOG = logging.getLogger('idm_logger')

class FindUserView(forms.ModalFormView):
    form_class = user_accounts_forms.FindUserByEmailForm
    template_name = 'idm_admin/user_accounts/index.html'

    def dispatch(self, request, *args, **kwargs):
        if idm_admin_utils.is_current_user_administrator(request):
            return super(FindUserView, self).dispatch(request, *args, **kwargs)
        else:
            return redirect('horizon:user_home')

class UpdateAccountView(forms.ModalFormView):
    form_class = user_accounts_forms.UpdateAccountForm
    template_name = 'idm_admin/user_accounts/update.html'
    success_url = 'horizon:idm_admin:user_accounts:update'

    def dispatch(self, request, *args, **kwargs):
        if idm_admin_utils.is_current_user_administrator(request):
            return super(UpdateAccountView, self).dispatch(request, *args, **kwargs)
        else:
            return redirect('horizon:user_home')

    def get_context_data(self, **kwargs):
        context = super(UpdateAccountView, self).get_context_data(**kwargs)
        context['user'] = api.keystone.user_get(self.request,
            self.kwargs['user_id'])
        return context

    def get_initial(self):
        initial = super(UpdateAccountView, self).get_initial()
        user_id = self.kwargs['user_id']
        user_roles = api.keystone.role_assignments_list(self.request,
            user=user_id, domain='default')
        # TODO(garcianavalon) find a better solution to this
        account_roles = [
            fiware_api.keystone.get_basic_role(None,
                use_idm_account=True).id,
            fiware_api.keystone.get_trial_role(None,
                use_idm_account=True).id,
            fiware_api.keystone.get_community_role(None,
                use_idm_account=True).id,
        ]
        current_account = next((a.role['id'] for a in user_roles
            if a.role['id'] in account_roles), None)

        initial.update({
            'user_id': user_id,
            #'region': '',
            'account_type': current_account,
        })
        return initial

class UpdateAccountEndpointView(View, user_accounts_forms.UserAccountsLogicMixin):
    """ Upgrade account logic with out the form"""
    http_method_names = ['post', 'get']
    use_idm_account = True

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super(UpdateAccountEndpointView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        try:
            import pdb; pdb.set_trace()
            import os
            __location__ = os.path.realpath(
                os.path.join(os.getcwd(), os.path.dirname(__file__)))
            categories = json.load(open(os.path.join(__location__, 'categories.json')))
            for data in categories:
                user_id = data['user_id']
                role_id = data['role_id']
                region_id = data.get('region_id', None)
                errors = []
                if (role_id == fiware_api.keystone.get_trial_role(
                        request, use_idm_account=True).id
                    and not region_id):

                    region_id = 'Spain2'

                if (role_id == fiware_api.keystone.get_community_role(
                        request, use_idm_account=True).id
                    and not region_id):

                    errors.append('ERROR: ' + user_id + ' community with no region')

                self.update_account(request, user_id, role_id, region_id)

            return http.HttpResponse(errors)

        except Exception:
            return http.HttpResponseServerError()
    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)
            user_id = data['user_id']
            role_id = data['role_id']

            if (role_id == fiware_api.keystone.get_trial_role(
                request).id):

                trial_left = self._max_trial_users_reached(request)
                if not trial_left:
                    return http.HttpResponseNotAllowed()

            region_id = data.get('region_id', None)

            if (role_id != fiware_api.keystone.get_basic_role(
                    request).id
                and not region_id):

                return http.HttpResponseBadRequest()

            self.update_account(request, user_id, role_id, region_id)

            return http.HttpResponse()

        except Exception:
            return http.HttpResponseServerError()
<commit_msg>removed pdb<commit_after># Licensed 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.

import logging
import json

from django import http
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from horizon import forms

from openstack_dashboard import api
from openstack_dashboard import fiware_api
from openstack_dashboard.dashboards.idm_admin.user_accounts \
    import forms as user_accounts_forms
from openstack_dashboard.dashboards.idm_admin \
    import utils as idm_admin_utils

LOG = logging.getLogger('idm_logger')

class FindUserView(forms.ModalFormView):
    form_class = user_accounts_forms.FindUserByEmailForm
    template_name = 'idm_admin/user_accounts/index.html'

    def dispatch(self, request, *args, **kwargs):
        if idm_admin_utils.is_current_user_administrator(request):
            return super(FindUserView, self).dispatch(request, *args, **kwargs)
        else:
            return redirect('horizon:user_home')

class UpdateAccountView(forms.ModalFormView):
    form_class = user_accounts_forms.UpdateAccountForm
    template_name = 'idm_admin/user_accounts/update.html'
    success_url = 'horizon:idm_admin:user_accounts:update'

    def dispatch(self, request, *args, **kwargs):
        if idm_admin_utils.is_current_user_administrator(request):
            return super(UpdateAccountView, self).dispatch(request, *args, **kwargs)
        else:
            return redirect('horizon:user_home')

    def get_context_data(self, **kwargs):
        context = super(UpdateAccountView, self).get_context_data(**kwargs)
        context['user'] = api.keystone.user_get(self.request,
            self.kwargs['user_id'])
        return context

    def get_initial(self):
        initial = super(UpdateAccountView, self).get_initial()
        user_id = self.kwargs['user_id']
        user_roles = api.keystone.role_assignments_list(self.request,
            user=user_id, domain='default')
        # TODO(garcianavalon) find a better solution to this
        account_roles = [
            fiware_api.keystone.get_basic_role(None,
                use_idm_account=True).id,
            fiware_api.keystone.get_trial_role(None,
                use_idm_account=True).id,
            fiware_api.keystone.get_community_role(None,
                use_idm_account=True).id,
        ]
        current_account = next((a.role['id'] for a in user_roles
            if a.role['id'] in account_roles), None)

        initial.update({
            'user_id': user_id,
            #'region': '',
            'account_type': current_account,
        })
        return initial

class UpdateAccountEndpointView(View, user_accounts_forms.UserAccountsLogicMixin):
    """ Upgrade account logic with out the form"""
    http_method_names = ['post', 'get']
    use_idm_account = True

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super(UpdateAccountEndpointView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        try:
            import os
            __location__ = os.path.realpath(
                os.path.join(os.getcwd(), os.path.dirname(__file__)))
            categories = json.load(open(os.path.join(__location__, 'categories.json')))
            for data in categories:
                user_id = data['user_id']
                role_id = data['role_id']
                region_id = data.get('region_id', None)
                errors = []
                if (role_id == fiware_api.keystone.get_trial_role(
                        request, use_idm_account=True).id
                    and not region_id):

                    region_id = 'Spain2'

                if (role_id == fiware_api.keystone.get_community_role(
                        request, use_idm_account=True).id
                    and not region_id):

                    errors.append('ERROR: ' + user_id + ' community with no region')

                self.update_account(request, user_id, role_id, region_id)

            return http.HttpResponse(errors)

        except Exception:
            return http.HttpResponseServerError()
    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)
            user_id = data['user_id']
            role_id = data['role_id']

            if (role_id == fiware_api.keystone.get_trial_role(
                request).id):

                trial_left = self._max_trial_users_reached(request)
                if not trial_left:
                    return http.HttpResponseNotAllowed()

            region_id = data.get('region_id', None)

            if (role_id != fiware_api.keystone.get_basic_role(
                    request).id
                and not region_id):

                return http.HttpResponseBadRequest()

            self.update_account(request, user_id, role_id, region_id)

            return http.HttpResponse()

        except Exception:
            return http.HttpResponseServerError()
<|endoftext|>


<commit_before># vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003  Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

from __future__ import generators

import time, urlparse, types

def headerKey(n):
    return n.lower()

http_header_classes = {
    headerKey('Date'):              ((1,0), 'general'),
    headerKey('Pragma'):            ((1,0), 'general'),

    headerKey('Authorization'):     ((1,0), 'request'),
    headerKey('From'):              ((1,0), 'request'),
    headerKey('If-Modified-Since'): ((1,0), 'request'),
    headerKey('Referer'):           ((1,0), 'request'),
    headerKey('User-Agent'):        ((1,0), 'request'),

    headerKey('Location'):          ((1,0), 'response'),
    headerKey('Server'):            ((1,0), 'response'),
    headerKey('WWW-Authenticate'):  ((1,0), 'response'),

    headerKey('Allow'):             ((1,0), 'entity'),
    headerKey('Content-Encoding'):  ((1,0), 'entity'),
    headerKey('Content-Length'):    ((1,0), 'entity'),
    headerKey('Content-Type'):      ((1,0), 'entity'),
    headerKey('Expires'):           ((1,0), 'entity'),
    headerKey('Last-Modified'):     ((1,0), 'entity'),
}
def headerVersion(name):
    return http_header_classes[headerKey(name)][0]
def headerClass(name):
    return http_header_classes[headerKey(name)][1]

HTTP_OK = 200
HTTP_CREATED = 201
HTTP_ACCEPTED = 202
HTTP_NO_CONTENT = 204
HTTP_MOVED_PERMANENTLY = 301
HTTP_MOVED_TEMPORARILY = 302
HTTP_NOT_MODIFIED = 304
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUND = 404
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_NOT_IMPLEMENTED = 501
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503

http_reason = {
    200: "OK",
    201: "Created",
    202: "Accepted",
    204: "No Content",
    301: "Moved Permanently",
    302: "Moved Temporarily",
    304: "Not Modified",
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    500: "Internal Server Error",
    501: "Not Implemented",
    502: "Bad Gateway",
    503: "Service Unavailable",
}

#
# FIXME -- The following (from RFC 1945 appendix B) describes behaivour which
# cannot be said to apply to this implementation, this should probably be made
# so.
#
# B.  Tolerant Applications
#
#    Although this document specifies the requirements for the generation
#    of HTTP/1.0 messages, not all applications will be correct in their
#    implementation. We therefore recommend that operational applications
#    be tolerant of deviations whenever those deviations can be
#    interpreted unambiguously.
#
#    Clients should be tolerant in parsing the Status-Line and servers
#    tolerant when parsing the Request-Line. In particular, they should
#    accept any amount of SP or HT characters between fields, even though
#    only a single SP is required.
#
#    The line terminator for HTTP-header fields is the sequence CRLF.
#    However, we recommend that applications, when parsing such headers,
#    recognize a single LF as a line terminator and ignore the leading CR.
#

class HTTPDateTime:
    def __init__(self, s=None):
        if isinstance(s, types.IntType):
            self.unixtime = time.gmtime(s)
        elif s:
            self.unixtime = self.parseString(s)
        else:
            self.unixtime = time.gmtime(time.time())

    def parseString(self, s):
        # RFC 822 format (Sun, 06 Nov 1994 08:49:37 GMT)
        try:
            return time.strptime(s, "%a, %d %b %Y %H:%M:%S GMT")
        except ValueError:
            pass
        # RFC 850 format (Sunday, 06-Nov-94 08:49:37 GMT)
        try:
            return time.strptime(s, "%A, %d-%b-%y %H:%M:%S GMT")
        except ValueError:
            pass
        # ANSI C's asctime format (Sun Nov  6 08:49:37 1994)
        try:
            return time.strptime(s, "%a %b %d %H:%M:%S %Y")
        except ValueError:
            pass
        raise ValueError('string matches no known date/time format')

    def __str__(self):
        return time.strftime("%a, %d %b %Y %H:%M:%S GMT", self.unixtime)

def parseHeaderLines(s):
    lines = []
    physical = s.split('\r\n')
    for line in physical:
        if line == '':
            continue
        if line[0] in '\t ':
            if not lines:
                raise ValueError('first line cannot be a continued line')
            lines[-1] = lines[-1] + line
        else:
            lines.append(line)

    for line in lines:
        yield parseHeaderLine(line)

def parseHeaderLine(s):
    try:
        name, value = s.split(':', 1)
        if not name:
            raise ValueError
        name = name.strip()
        value = value.strip()
    except ValueError:
        raise ValueError('"%s" is not a proper HTTP header' % s)
    return name, value

def splitHeaderList(s):
    l = []
    for e in s.split(','):
        e = e.strip()
        if e:
            l.append(e)
    return l

class HTTPHeaders:
    def __init__(self, s=None):
        self.order = []
        self.headers = {}
        if not s is None:
            for name, value in parseHeaderLines(s):
                self.addHeader(name, value)

    def addHeader(self, name, value):
        key = headerKey(name)
        if not self.headers.has_key(key):
            self.order.append(name)
            self.headers[key] = (name, value)
        else:
            self.headers[key] = (self.headers[key][0], self.headers[key][1] + ', ' + value)

    def setHeader(self, name, value):
        key = headerKey(name)
        if not self.headers.has_key(key):
            self.order.append(name)
        self.headers[key] = (name, value)

    def get(self, name):
        return self.headers[headerKey(name)][1]
    def __getitem__(self, name):
        return self.get(name)
    def has_key(self, name):
        return self.headers.has_key(headerKey(name))
    def item(self, name):
        return name, self.get(name)
    def items(self):
        return map(self.item, self.order)

class HTTPRequestLine:
    def __init__(self, s):
        self.raw = s

        pieces = s.split(' ')
        if len(pieces) == 2 and pieces[0] == 'GET':
            # simple HTTP request-line
            self.method = 'GET'
            self.wire_uri = pieces[1]
            self.uri = urlparse.urlsplit(pieces[1])
            self.version = 0, 9

        elif len(pieces) == 3 and pieces[2].startswith('HTTP/'):
            # full HTTP request-line
            self.method = pieces[0]
            self.wire_uri = pieces[1]
            self.uri = urlparse.urlsplit(pieces[1])
            self.version = tuple(map(int, pieces[2][5:].split('.')))
            if not len(self.version) == 2:
                ValueError('"%s" is not a known form of HTTP request-line' % s)

        else:
            raise ValueError('"%s" is not a known form of HTTP request-line' % s)

class HTTPStatusLine:
    def __init__(self, s):
        http, status, self.reason = s.split(' ', 2)
        if not http.startswith('HTTP/'):
            raise ValueError('"%s" is not a valie HTTP status-line' % s)

        self.version = tuple(map(int, http[5:].split('.')))
        if not len(self.version) == 2:
            raise ValueError('"%s" is not a valie HTTP status-line' % s)
        self.code = int(status)

#__all__ = ['HTTPDateTime', 'HTTPHeaders', 'HTTPRequestLine', 'HTTPStatusLine', 'splitHeaderList']
<commit_msg>HTTPHeaders.get now takes an optional default value.<commit_after># vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003  Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

from __future__ import generators

import time, urlparse, types

def headerKey(n):
    return n.lower()

http_header_classes = {
    headerKey('Date'):              ((1,0), 'general'),
    headerKey('Pragma'):            ((1,0), 'general'),

    headerKey('Authorization'):     ((1,0), 'request'),
    headerKey('From'):              ((1,0), 'request'),
    headerKey('If-Modified-Since'): ((1,0), 'request'),
    headerKey('Referer'):           ((1,0), 'request'),
    headerKey('User-Agent'):        ((1,0), 'request'),

    headerKey('Location'):          ((1,0), 'response'),
    headerKey('Server'):            ((1,0), 'response'),
    headerKey('WWW-Authenticate'):  ((1,0), 'response'),

    headerKey('Allow'):             ((1,0), 'entity'),
    headerKey('Content-Encoding'):  ((1,0), 'entity'),
    headerKey('Content-Length'):    ((1,0), 'entity'),
    headerKey('Content-Type'):      ((1,0), 'entity'),
    headerKey('Expires'):           ((1,0), 'entity'),
    headerKey('Last-Modified'):     ((1,0), 'entity'),
}
def headerVersion(name):
    return http_header_classes[headerKey(name)][0]
def headerClass(name):
    return http_header_classes[headerKey(name)][1]

HTTP_OK = 200
HTTP_CREATED = 201
HTTP_ACCEPTED = 202
HTTP_NO_CONTENT = 204
HTTP_MOVED_PERMANENTLY = 301
HTTP_MOVED_TEMPORARILY = 302
HTTP_NOT_MODIFIED = 304
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUND = 404
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_NOT_IMPLEMENTED = 501
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503

http_reason = {
    200: "OK",
    201: "Created",
    202: "Accepted",
    204: "No Content",
    301: "Moved Permanently",
    302: "Moved Temporarily",
    304: "Not Modified",
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    500: "Internal Server Error",
    501: "Not Implemented",
    502: "Bad Gateway",
    503: "Service Unavailable",
}

#
# FIXME -- The following (from RFC 1945 appendix B) describes behaivour which
# cannot be said to apply to this implementation, this should probably be made
# so.
#
# B.  Tolerant Applications
#
#    Although this document specifies the requirements for the generation
#    of HTTP/1.0 messages, not all applications will be correct in their
#    implementation. We therefore recommend that operational applications
#    be tolerant of deviations whenever those deviations can be
#    interpreted unambiguously.
#
#    Clients should be tolerant in parsing the Status-Line and servers
#    tolerant when parsing the Request-Line. In particular, they should
#    accept any amount of SP or HT characters between fields, even though
#    only a single SP is required.
#
#    The line terminator for HTTP-header fields is the sequence CRLF.
#    However, we recommend that applications, when parsing such headers,
#    recognize a single LF as a line terminator and ignore the leading CR.
#

class HTTPDateTime:
    def __init__(self, s=None):
        if isinstance(s, types.IntType):
            self.unixtime = time.gmtime(s)
        elif s:
            self.unixtime = self.parseString(s)
        else:
            self.unixtime = time.gmtime(time.time())

    def parseString(self, s):
        # RFC 822 format (Sun, 06 Nov 1994 08:49:37 GMT)
        try:
            return time.strptime(s, "%a, %d %b %Y %H:%M:%S GMT")
        except ValueError:
            pass
        # RFC 850 format (Sunday, 06-Nov-94 08:49:37 GMT)
        try:
            return time.strptime(s, "%A, %d-%b-%y %H:%M:%S GMT")
        except ValueError:
            pass
        # ANSI C's asctime format (Sun Nov  6 08:49:37 1994)
        try:
            return time.strptime(s, "%a %b %d %H:%M:%S %Y")
        except ValueError:
            pass
        raise ValueError('string matches no known date/time format')

    def __str__(self):
        return time.strftime("%a, %d %b %Y %H:%M:%S GMT", self.unixtime)

def parseHeaderLines(s):
    lines = []
    physical = s.split('\r\n')
    for line in physical:
        if line == '':
            continue
        if line[0] in '\t ':
            if not lines:
                raise ValueError('first line cannot be a continued line')
            lines[-1] = lines[-1] + line
        else:
            lines.append(line)

    for line in lines:
        yield parseHeaderLine(line)

def parseHeaderLine(s):
    try:
        name, value = s.split(':', 1)
        if not name:
            raise ValueError
        name = name.strip()
        value = value.strip()
    except ValueError:
        raise ValueError('"%s" is not a proper HTTP header' % s)
    return name, value

def splitHeaderList(s):
    l = []
    for e in s.split(','):
        e = e.strip()
        if e:
            l.append(e)
    return l

class HTTPHeaders:
    def __init__(self, s=None):
        self.order = []
        self.headers = {}
        if not s is None:
            for name, value in parseHeaderLines(s):
                self.addHeader(name, value)

    def addHeader(self, name, value):
        key = headerKey(name)
        if not self.headers.has_key(key):
            self.order.append(name)
            self.headers[key] = (name, value)
        else:
            self.headers[key] = (self.headers[key][0], self.headers[key][1] + ', ' + value)

    def setHeader(self, name, value):
        key = headerKey(name)
        if not self.headers.has_key(key):
            self.order.append(name)
        self.headers[key] = (name, value)

    def get(self, name, *argv):
        assert len(argv) < 2, 'get takes one or two arguments'

        if self.headers.has_key(headerKey(name)):
            return self.headers[headerKey(name)][1]
        elif len(argv):
            return argv[0]
        else:
            raise KeyError, name
    def __getitem__(self, name):
        return self.get(name)
    def has_key(self, name):
        return self.headers.has_key(headerKey(name))
    def item(self, name):
        return name, self.get(name)
    def items(self):
        return map(self.item, self.order)

class HTTPRequestLine:
    def __init__(self, s):
        self.raw = s

        pieces = s.split(' ')
        if len(pieces) == 2 and pieces[0] == 'GET':
            # simple HTTP request-line
            self.method = 'GET'
            self.wire_uri = pieces[1]
            self.uri = urlparse.urlsplit(pieces[1])
            self.version = 0, 9

        elif len(pieces) == 3 and pieces[2].startswith('HTTP/'):
            # full HTTP request-line
            self.method = pieces[0]
            self.wire_uri = pieces[1]
            self.uri = urlparse.urlsplit(pieces[1])
            self.version = tuple(map(int, pieces[2][5:].split('.')))
            if not len(self.version) == 2:
                ValueError('"%s" is not a known form of HTTP request-line' % s)

        else:
            raise ValueError('"%s" is not a known form of HTTP request-line' % s)

class HTTPStatusLine:
    def __init__(self, s):
        http, status, self.reason = s.split(' ', 2)
        if not http.startswith('HTTP/'):
            raise ValueError('"%s" is not a valie HTTP status-line' % s)

        self.version = tuple(map(int, http[5:].split('.')))
        if not len(self.version) == 2:
            raise ValueError('"%s" is not a valie HTTP status-line' % s)
        self.code = int(status)

#__all__ = ['HTTPDateTime', 'HTTPHeaders', 'HTTPRequestLine', 'HTTPStatusLine', 'splitHeaderList']
<|endoftext|>