Exemplo n.º 1
0
 def __init__(self, username, password, hierarchy, gateway_id,
              environment_prefix):
     '''Configuration path'''
     dict_configuration_path = utility.getConfigurationPath()
     self.json_templates_path = dict_configuration_path[
         "json_templates_path"]
     self.excel_templates_path = dict_configuration_path[
         "excel_templates_path"]
     self.json_files_path = dict_configuration_path["json_files_path"]
     self.excel_files_path = dict_configuration_path["excel_files_path"]
     self.hierarchy_file_path = dict_configuration_path["hierarchy_path"]
     '''Data'''
     self.dict_configuration_path = utility.getConfigurationPath
     self.username = username
     self.password = password
     self.name_hierarchy = utility.getSubstring(os.path.basename(hierarchy),
                                                stop=".")
     self.hierarchy_path = os.path.join(self.hierarchy_file_path,
                                        self.name_hierarchy + ".xml")
     self.serial_number, self.match_group_value, self.dict_meters = self.getDataFromHierarchy(
     )
     self.gateway_id = gateway_id
     self.environment_prefix = environment_prefix
     self.match_group_value = self.name_hierarchy.split(
         "_")[1] + "_" + self.match_group_value
     self.dict_meter_template = self.createDictMeterTemplate()
Exemplo n.º 2
0
def createListModel(model):
    file_model = utility.readFileJSON(os.path.join(templatesPath, model))
    list_measures = []
    for model in file_model["parameters"]["filter_tag"]:
        if (model["tag"] != "CommunicationCode"):
            list_measures.append(utility.getSubstring(model["tag"], start="."))
    return (list_measures)
Exemplo n.º 3
0
 def createExcelSheet(self):
     excel_document = openpyxl.load_workbook(
         os.path.join(self.excel_templates_path,
                      "Meter Upload Template LEONARDO.xlsx"))
     sheet = excel_document.active
     number_cell = 7
     for meter_name, list_measures in self.dict_meters.items():
         for dict_measure in list_measures:
             try:
                 if (dict_measure["active"] == "True"
                         or dict_measure["active"] == "true"):
                     sheet['A' + str(number_cell)] = self.site_name
                     sheet['B' + str(number_cell)] = utility.getSubstring(
                         dict_measure["name"], stop=".")
                     sheet['C' + str(
                         number_cell
                     )] = self.environment_prefix + "_veig1_thing§_" + str(
                         dict_measure["trend_id"])
                     sheet['E' +
                           str(number_cell)] = dict_measure["period"] / 60
                     sheet['G' + str(number_cell)] = "True"
                     sheet['D' + str(number_cell)] = dict_measure["channel"]
                     sheet['F' +
                           str(number_cell)] = dict_measure["multipler"]
                     number_cell += 1
             except:
                 pass
     excel_document.save(
         os.path.join(self.excel_files_path, self.hierarchy_name + ".xlsx"))
Exemplo n.º 4
0
 def createTemplateList(self, template):
     file_template = utility.readJsonFile(os.path.join(self.json_templates_path, template))
     list_measures = []
     for model in file_template["parameters"]["filter_tag"]:
         if(model["tag"] != "CommunicationCode"):
             list_measures.append(utility.getSubstring(model["tag"], start="."))           
     return(list_measures)
Exemplo n.º 5
0
def add_file_hierarchy(path):
    if (os.path.isfile(path)
            and utility.getSubstring(path, start=".") == "xml"):
        shutil.copy(path, hierarchyPath)
        return True
    elif (os.path.isdir(path)):
        list_files = utility.createListFile(path, ".xml")
        for file in list_files:
            shutil.copy(os.path.join(path, file), hierarchyPath)
        return True
    else:
        return False
Exemplo n.º 6
0
def setConstantData(user, psw, nameFileHierarchy, gatewayId,
                    environmentPrefix):
    global user_name, password, name_file_hierarchy, dizMeters, serial_number, match_group_value, gateway_id, environment_prefix
    user_name = user
    password = psw
    gateway_id = gatewayId
    environment_prefix = environmentPrefix
    name_file_hierarchy = utility.getSubstring(nameFileHierarchy, stop=".")
    dizMeters = utility.createDictMeterMeasures(
        os.path.join(hierarchyPath, name_file_hierarchy + ".xml"))
    serial_number, match_group_value = utility.getSerialNumberMgValueHierarchy(
        os.path.join(hierarchyPath, name_file_hierarchy + ".xml"))
    if (len(match_group_value) > 15):
        match_group_value = match_group_value[0:15]
Exemplo n.º 7
0
def add_json_template(path):
    file_path = os.path.basename(path)
    if (os.path.isfile(path)
            and utility.getSubstring(path, start=".") == "json"):
        path_name, file_name = os.path.splitext(file_path)
        shutil.copy(path, templatesPath)
        utility.add_measures_template(file_path)
        return True
    elif (os.path.isdir(path)):
        list_files = utility.createListFile(path, ".json")
        for file in list_files:
            shutil.copy(os.path.join(path, file), templatesPath)
        utility.add_measures_template(list_files)
        return True
    else:
        return False
Exemplo n.º 8
0
def addJsonTemplate(path):
    file_path = os.path.basename(path)
    if (os.path.isfile(path)
            and utility.getSubstring(file_path, start=".") == "json"):
        path_name, file_name = os.path.splitext(file_path)
        shutil.copy(path, os.path.join(json_templates_path))
        utility.refreshTemplateConfiguration()
        return True
    elif (os.path.isdir(path)):
        list_files = utility.createFileList(path, ".json")
        for file in list_files:
            shutil.copy(os.path.join(path, file),
                        os.path.join(json_templates_path))
        utility.add_measures_template(list_files)
        return True
    else:
        return False
Exemplo n.º 9
0
def get(credentials, endpoint, commandId):

    # VARIABLES DECLARATION
    service = 'execute-api'
    method = 'GET'
    endpoint_g = endpoint + commandId
    host = getSubstring(endpoint, start="'https://", stop='/dev/')
    uri = getSubstring(endpoint, start=host, stop="") + commandId
    content_type = 'application/json'
    request_parameters = ''

    ## CREDENTIALS
    dict_credentials = credentials
    region = dict_credentials['region']
    securitytoken = dict_credentials['aws_security_token']

    ###ACCESS AND SECRET CONTROL
    secretkey = dict_credentials['aws_secret_access_key']
    accesskey = dict_credentials['aws_access_key_id']
    if accesskey is None or secretkey is None:
        print('No access key is available.')
        sys.exit()

    t = datetime.datetime.utcnow()
    amzdate = t.strftime('%Y%m%dT%H%M%SZ')
    datestamp = t.strftime('%Y%m%d')

    ### CREATE A CANONICAL REQUEST
    canonical_uri = uri
    canonical_querystring = request_parameters
    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
    signed_headers = 'content-type;host;x-amz-date'
    payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    ### CREATE THE STRING TO SIGN
    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'

    string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(
        canonical_request.encode('utf-8')).hexdigest()

    ### CALCULATE THE SIGNATURE
    signing_key = getSignatureKey(secretkey, datestamp, region, service)

    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
                         hashlib.sha256).hexdigest()

    ### ADD SIGNING INFORMATION TO THE REQUEST
    authorization_header = algorithm + ' ' + 'Credential=' + accesskey + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

    headers = {
        'Content-Type': content_type,
        'host': host,
        'x-amz-security-token': securitytoken,
        'x-amz-date': amzdate,
        'Authorization': authorization_header
    }

    request_url = endpoint_g + canonical_querystring

    # RESPONSE OF THE REQUEST
    response_g = requests.get(request_url, headers=headers)

    ## RESPONSE CONTROLS
    if (response_g.status_code == 404):
        return get(credentials, endpoint, commandId)
    elif (response_g.status_code == 200):
        commandstat = binary_to_dict(response_g._content)["command_status"]
        commandProcessDet = binary_to_dict(
            response_g._content)["command_process_details"]
        rejected = commandProcessDet['rejected']
        failed = commandProcessDet['failed']
        succeed = commandProcessDet['succeed']
        inprogress = commandProcessDet['in_progress']
        removed = commandProcessDet['removed']
        queued = commandProcessDet['queued']

        if (rejected == '1'):
            rejected_msg = "GET PROCESS DETAIL: REJECTED"
            response = (commandstat, rejected_msg)
            return response

        elif (failed == '1'):
            failed_msg = "GET PROCESS DETAIL: FAILED"
            response = (commandstat, failed_msg)
            return response

        elif (succeed == '1'):
            succeed_msg = "GET PROCESS DETAIL: SUCCEED"
            response = (commandstat, succeed_msg)
            return response

        elif (inprogress == '1'):
            inprogress_msg = "GET PROCESS DETAIL: IN PROGRESS"
            response = (commandstat, inprogress_msg)
            return response

        elif (removed == '1'):
            removed_msg = "GET PROCESS DETAIL: REMOVED"
            response = (commandstat, removed_msg)
            return response

        elif (queued == '1'):
            queued_msg = "GET PROCESS DETAIL: QUEUED"
            response = (commandstat, queued_msg)
            return response
        else:
            message = binary_to_dict(response_g._content)["command_status"]
            response = (response_g.status_code, message)
            return response
    else:
        message = binary_to_dict(response_g._content)["message"]
        response = (response_g.status_code, message)
        return response
Exemplo n.º 10
0
def post(credentials, endpoint, payload):

    #VARIABLE DECLARATION
    service = 'execute-api'
    method = 'POST'
    host = getSubstring(endpoint, start="'https://", stop='/dev/')
    uri = getSubstring(endpoint, start=host, stop='')
    content_type = 'application/json'

    ##CREDENTIALS
    dict_credentials = credentials
    region = dict_credentials['region']
    securitytoken = dict_credentials['aws_security_token']

    ###ACCESS AND SECRET CONTROL
    secretkey = dict_credentials['aws_secret_access_key']
    accesskey = dict_credentials['aws_access_key_id']
    if accesskey is None or secretkey is None:
        print('No access key is available.')
        sys.exit()

    t = datetime.datetime.utcnow()
    amz_date = t.strftime('%Y%m%dT%H%M%SZ')
    date_stamp = t.strftime('%Y%m%d')

    ### CREATE A CANONICAL REQUEST
    canonical_uri = uri
    canonical_querystring = ''
    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
    signed_headers = 'content-type;host;x-amz-date'
    payload_hash = hashlib.sha256(payload.encode('utf-8')).hexdigest()

    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    ### CREATE THE STRING TO SIGN
    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'

    string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(
        canonical_request.encode('utf-8')).hexdigest()

    ### CALCULATE THE SIGNATURE
    signing_key = getSignatureKey(secretkey, date_stamp, region, service)

    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
                         hashlib.sha256).hexdigest()

    ### ADD SIGNING INFORMATION TO THE REQUEST
    authorization_header = algorithm + ' ' + 'Credential=' + accesskey + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

    headers = {
        'Content-Type': content_type,
        'x-amz-date': amz_date,
        'x-amz-security-token': securitytoken,
        'Authorization': authorization_header
    }

    # RESPONSE OF THE REQUEST
    r = requests.post(endpoint, data=payload, headers=headers)
    post_response = (r.status_code, r._content)

    return post_response