def leave(self):
        """
        Logout in the platform with session token

        @return ok, info
        """
        _ok = False
        _res = None
        try:
            if self.is_connected:
                response = self.raw_leave()
                if response.status_code == 200:
                    _res = response.text
                    _ok = True
            else:
                _ok = True

        except Exception as e:
            log.error(
                "Not possible to disconnect with iot-broker: {}".format(e))
            self.add_to_debug_trace(
                "Not possible to disconnect with iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 2
0
    def refresh(self, refresh_token=None):
        """
        Login in the platform with Iot-Client credentials

        @return ok, info
        """
        _ok = False
        _res = None

        try:
            response = self.raw_refresh(refresh_token=None)

            if response.status_code == 200 and len(response.content):
                _res = response.json()
                _ok = True

            else:
                _res = response.text

        except Exception as e:
            log.error(
                "Not possible to refresh with controlpanel-auth host:{}, path:{}, refresh_token:{}"
                .format(self.host, self.__control_panel_path,
                        self.token.refresh_token))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 3
0
    def from_json(json_object):
        """
        Creates a object from json-dict/ json-string

        @param json_object    json.dict/ json-string

        @return client        client object
        """
        client = None
        try:
            if type(json_object) == str:
                json_object = json.loads(json_object)

            json_object_keys = list(json_object.keys())
            client = FileManager(host=json_object['host'])
            if "user_token" in json_object_keys:
                client.user_token = json_object['user_token']
            if "protocol" in json_object_keys:
                client.protocol = json_object['protocol']
            if "proxies" in json_object_keys:
                client.proxies = json_object['proxies']
            if "timeout" in json_object_keys:
                client.timeout = json_object['timeout']
            if "avoid_ssl_certificate" in json_object_keys:
                client.avoid_ssl_certificate = json_object[
                    'avoid_ssl_certificate']
            if "raise_exceptions" in json_object_keys:
                client.raise_exceptions = json_object['raise_exceptions']

            log.info("Imported json {}".format(json_object))

        except Exception as e:
            log.error("Not possible to import object from json: {}".format(e))

        return client
Ejemplo n.º 4
0
    def login(self, username=None, password=None, vertical=None):
        """
        Login in the platform with Iot-Client credentials

        @return ok, info
        """
        _ok = False
        _res = None

        try:
            response = self.raw_login(username=username,
                                      password=password,
                                      vertical=vertical)

            if response.status_code == 200:
                _res = response.json()
                _ok = True

            else:
                _res = response.text

        except Exception as e:
            log.error(
                "Not possible to login with controlpanel-auth host:{}, path:{}, username:{}, vertical:{}"
                .format(self.host, self.__control_panel_path, self.username,
                        self.vertical))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
    def join(self, iot_client=None, iot_client_token=None):
        """
        Login in the platform with Iot-Client credentials

        @return ok, info
        """
        _ok = False
        _res = None

        try:
            response = self.raw_join(iot_client=iot_client,
                                     iot_client_token=iot_client_token)

            if response.status_code == 200:
                _res = response.json()
                _ok = True

            else:
                _res = response.text

        except Exception as e:
            self.is_connected = False
            log.error("Not possible to conect with iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 6
0
    def request(self, method, url=None, name=None, version=None, 
                path_params=None, query_params=None, body=None):
        """
        Make a request to an API rest

        @param method          method (hhtp method)
        @param url             url with path params and query params
        @param name            API rest name *
        @param version         API rest version *
        @param path_params     path_params *
        @param query_params    query_params *
        @param body            body

        * If url != None: api_path = generate_url_request(name, version, path_params, query_params)
        * else: api_path = url 

        @return ok, info  
        """
        _ok = False
        _res = None

        try:
            log.info("Making request: url:{}".format(url))
            self.raise_exception_if_not_token()

            if isinstance(version, int) or isinstance(version, float):
                version = str(int(version))
            
            if url is None:
                api_path = self.generate_url_request(name=name, version=version, 
                                                     path_params=path_params, query_params=query_params)
            else:
                api_path = url
            
            url = self.__request_template.substitute(protocol=self.protocol, host=self.hostport, 
                                                path=self.api_caller_path,
                                                api_path=api_path
                                                )
            headers = self.__headers
            response = self.call(method, url, headers=headers, body=body)
            log.info("Response: {} - {}".format(response.status_code, response.text))
            self.add_to_debug_trace("Response: {} - {}".format(response.status_code, response.text))

            if response.status_code == 200:
                _res = response.json()
                log.info("Query result: {}".format(response.text))
                self.add_to_debug_trace("Query result: {}".format(response.text))
                _ok = True

            else:
                raise Exception("Response: {} - {}".format(response.status_code, response.text))

        except Exception as e:
            log.error("Not possible to query api-manager: {}".format(e))
            self.add_to_debug_trace("Not possible to query api-manager: {}".format(e))
            _res = e

        return _ok, _res
Ejemplo n.º 7
0
    def download_file(self, id_file, filepath=""):
        """
        Download a file from binary-repository

        @param id_file            file id in onesait platform
        @param filepath           file path to be saved
        """
        def get_name_from_response(response):
            name_getted = None
            key_name = 'Content-Disposition'
            name_getted = response.headers[key_name].replace(
                " ", "").split("=")[1].strip()
            return name_getted

        _ok = False
        _res = None
        try:
            url = self.__download_template.substitute(protocol=self.protocol,
                                                      host=self.host,
                                                      path=self.__files_path,
                                                      id_file=id_file)
            headers = self.__headers_download

            response = requests.request(RestMethods.GET.value,
                                        url,
                                        headers=headers,
                                        data="",
                                        verify=not self.avoid_ssl_certificate,
                                        timeout=self.timeout,
                                        proxies=self.proxies)

            if response.status_code == 200:
                _ok = True
                name_file = get_name_from_response(response)
                if os.path.isdir(filepath):
                    name_file = os.path.join(filepath, name_file)
                _res = {
                    "id": id_file,
                    "msg": "Succesfully downloaded file",
                    "name": name_file
                }

                with open(name_file, 'wb') as f:
                    f.write(response.content)

            else:
                raise Exception("Response: {} - {}".format(
                    response.status_code, response.text))

        except Exception as e:
            log.error("Not possible to download file: {}".format(e))
            self.__raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 8
0
    def delete(self, identification, version):
        """
        Delete an API rest

        @param identification     API identification (name)
        @param version            API version

        @return ok, info  
        """
        _ok = False
        _res = None

        try:
            log.info("Making delete")
            if isinstance(version, str):
                version = version.replace("v", "")  # case vX -> X

            self.raise_exception_if_not_token()
            url = self.__delete_template.substitute(
                protocol=self.protocol,
                host=self.hostport,
                path=self.api_manager_path,
                identification=identification,
                version=version)
            headers = self.__headers
            response = self.call(RestMethods.DELETE.value,
                                 url,
                                 headers=headers)
            log.info("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))
            self.add_to_debug_trace("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))

            if response.status_code == 200:
                _res = response.json()
                log.info("Query result: {text}".format(text=response.text))
                self.add_to_debug_trace(
                    "Query result: {text}".format(text=response.text))
                _ok = True

            else:
                raise Exception("Response: {status_code} - {text}".format(
                    status_code=response.status_code, text=response.text))

        except Exception as e:
            log.error("Not possible to query api-manager: {exception}".format(
                exception=e))
            self.add_to_debug_trace(
                "Not possible to query api-manager: {exception}".format(
                    exception=e))
            _res = e

        return _ok, _res
    def download_file(self, id_file):
        """
        Download a file from binary-repository

        @param filename           file name
        @param filepath           file path
        """
        def get_name_from_response(response):
            name_getted = None
            key_name = 'Content-Disposition'
            name_getted = response.headers[key_name].replace(
                " ", "").split("=")[1].strip()
            return name_getted

        _ok = False
        _res = None
        try:
            url = self.download_template.substitute(protocol=self.protocol,
                                                    host=self.host,
                                                    path=self.files_path,
                                                    id_file=id_file)
            headers = {
                RestHeaders.AUTHORIZATION.value: self.user_token,
                RestHeaders.ACCEPT_STR.value: RestHeaders.ACCEPT_ALL.value
            }

            response = requests.request(RestMethods.GET.value,
                                        url,
                                        headers=headers,
                                        data="",
                                        verify=not self.avoid_ssl_certificate)

            if response.status_code == 200:
                _ok = True
                name_file = get_name_from_response(response)
                _res = {
                    "id": id_file,
                    "msg": "Succesfully downloaded file",
                    "name": name_file
                }

                with open(name_file, 'wb') as f:
                    f.write(response.content)

            else:
                raise Exception("Response: {} - {}".format(
                    response.status_code, response.text))

        except Exception as e:
            log.error("Not possible to download file: {}".format(e))
            _res = e

        return _ok, _res
Ejemplo n.º 10
0
    def update_file(self, id_file, filename, filepath, metadata=None):
        """
        Upload a file to binary-repository

        @param id_file            file id in onesait platform
        @param filename           file name
        @param filepath           file path
        @param metadata           file metadata or description
        """
        _ok = False
        _res = None
        try:
            if not os.path.exists(filepath):
                raise IOError("Source file not found: {}".format(filepath))

            url = self.__update_template.substitute(
                protocol=self.protocol,
                host=self.host,
                path=self.__binary_files_path,
                id_file=id_file)

            headers = self.__headers
            files_to_up = {
                'file': (filename, open(filepath, 'rb'), "multipart/form-data")
            }
            params = {"metadata": metadata}

            response = requests.request(RestMethods.PUT.value,
                                        url,
                                        params=params,
                                        headers=headers,
                                        files=files_to_up,
                                        verify=not self.avoid_ssl_certificate,
                                        timeout=self.timeout,
                                        proxies=self.proxies)

            if response.status_code == 202:
                _ok = True
                _res = {
                    "id": response.text,
                    "msg": "Succesfully uploaded file"
                }

            else:
                raise Exception("Response: {} - {}".format(
                    response.status_code, response.text))

        except Exception as e:
            log.error("Not possible to upload file: {}".format(e))
            self.__raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 11
0
    def find(self, identification, state, user):
        """
        Find API rest information

        @param identification     API identification (name)
        @param state              API state
        @param user               API creation user

        @return ok, info  
        """
        _ok = False
        _res = None

        try:
            log.info(
                "Making find: identification:{}, state:{}, user:{}".format(
                    identification, state, user))
            self.raise_exception_if_not_token()
            url = self.__find_template.substitute(
                protocol=self.protocol,
                host=self.hostport,
                path=self.api_manager_path,
                identification=identification,
                state=state,
                user=user)
            headers = self.__headers
            response = self.call(RestMethods.GET.value, url, headers=headers)
            log.info("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))
            self.add_to_debug_trace("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))

            if response.status_code == 200:
                _res = response.json()
                log.info("Query result: {text}".format(text=response.text))
                self.add_to_debug_trace(
                    "Query result: {text}".format(text=response.text))
                _ok = True

            else:
                raise Exception("Response: {status_code} - {text}".format(
                    status_code=response.status_code, text=response.text))

        except Exception as e:
            log.error("Not possible to query api-manager: {exception}".format(
                exception=e))
            self.add_to_debug_trace(
                "Not possible to query api-manager: {exception}".format(
                    exception=e))
            _res = e

        return _ok, _res
Ejemplo n.º 12
0
    def create(self, json_obj):
        """
        Create an API rest from json object

        @param json_obj     json object of the API

        @return ok, info  
        """
        _ok = False
        _res = None

        try:
            log.info("Making create")
            if isinstance(json_obj, str):
                json_obj = json.loads(json_obj)

            self.raise_exception_if_not_token()
            url = self.__create_template.substitute(protocol=self.protocol,
                                                    host=self.hostport,
                                                    path=self.api_manager_path)
            headers = self.__headers
            response = self.call(RestMethods.POST.value,
                                 url,
                                 headers=headers,
                                 body=json_obj)
            log.info("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))
            self.add_to_debug_trace("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))

            if response.status_code == 200:
                _res = response.json()
                log.info("Query result: {text}".format(text=response.text))
                self.add_to_debug_trace(
                    "Query result: {text}".format(text=response.text))
                _ok = True

            else:
                raise Exception("Response: {status_code} - {text}".format(
                    status_code=response.status_code, text=response.text))

        except Exception as e:
            log.error("Not possible to query api-manager: {exception}".format(
                exception=e))
            self.add_to_debug_trace(
                "Not possible to query api-manager: {exception}".format(
                    exception=e))
            _res = e

        return _ok, _res
    def update(self,
               ontology,
               query=None,
               query_type="NATIVE",
               data=None,
               where=None,
               return_ids=True):
        """
        Make a update to iot-broker service of the platform

        @param ontology     ontology name
        @param query        query expression
        @param query_type   quert type ['NATIVE']
        @param data         data to update
        @param where        selection criteria for the update
        @param return_ids   return ids in response (optional, default: True)

        @return ok, info
        """
        _ok = False
        _res = None
        try:
            response = self.raw_update(ontology, query, query_type, data,
                                       where, return_ids)

            if self.is_correct_status_code(response.status_code):
                _res = response.json()
                log.info("Query result: {}".format(response.text))
                self.add_to_debug_trace("Query result: {}".format(
                    response.text))
                _ok = True

            else:
                log.info("Bad response: {} - {}".format(
                    response.status_code, response.text))
                self.add_to_debug_trace("Bad response: {} - {}".format(
                    response.status_code, response.text))
                _res = response.text

        except Exception as e:
            log.error("Not possible to update with iot-broker: {}".format(e))
            self.add_to_debug_trace(
                "Not possible to update with iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
Ejemplo n.º 14
0
    def from_json(json_object):
        """
        Creates a object from json-dict/ json-string

        @param json_object    json.dict/ json-string

        @return client        client object
        """
        client = None
        try:
            if type(json_object) == str:
                json_object = json.loads(json_object)

            json_object_keys = list(json_object.keys())

            client = Client(host=json_object['host'])
            if "port" in json_object_keys:
                client.port = json_object['port']
            if "protocol" in json_object_keys:
                client.protocol = json_object['protocol']
            if "is_connected" in json_object_keys:
                client.is_connected = json_object['is_connected']
            if "proxies" in json_object_keys:
                client.proxies = json_object['proxies']
            if "timeout" in json_object_keys:
                client.timeout = json_object['timeout']
            if "avoid_ssl_certificate" in json_object_keys:
                client.avoid_ssl_certificate = json_object[
                    'avoid_ssl_certificate']
            if "raise_exceptions" in json_object_keys:
                client.raise_exceptions = json_object['raise_exceptions']
            if "model_endpoint" in json_object_keys:
                client.model_endpoint = json_object['model_endpoint']
            if "model_version" in json_object_keys:
                client.model_version = json_object['model_version']
            if "token" in json_object_keys:
                client.token = json_object['token']

            log.info("Imported json {}".format(json_object))
            client.add_to_debug_trace("Imported json {}".format(json_object))

        except Exception as e:
            log.error("Not possible to import object from json: {}".format(e))

        return client
Ejemplo n.º 15
0
    def list(self, user):
        """
        List APIs rest from user

        @param user     user

        @return ok, info  
        """
        _ok = False
        _res = None

        try:
            log.info("Making list: user: {}".format(user))
            self.raise_exception_if_not_token()
            url = self.__list_template.substitute(protocol=self.protocol,
                                                  host=self.hostport,
                                                  path=self.api_manager_path,
                                                  user=user)
            headers = self.__headers
            response = self.call(RestMethods.GET.value, url, headers=headers)
            log.info("Response: {status_code} - {text}".format(
                status_code=response.status_code, text=response.text))
            self.add_to_debug_trace("Response: {} - {}".format(
                response.status_code, response.text))

            if response.status_code == 200:
                _res = response.json()
                log.info("Query result: {}".format(response.text))
                self.add_to_debug_trace("Query result: {}".format(
                    response.text))
                _ok = True

            else:
                raise Exception("Response: {status_code} - {text}".format(
                    status_code=response.status_code, text=response.text))

        except Exception as e:
            log.error("Not possible to query api-manager: {exception}".format(
                exception=e))
            self.add_to_debug_trace(
                "Not possible to query api-manager: {exception}".format(
                    exception=e))
            _res = e

        return _ok, _res
Ejemplo n.º 16
0
    def upload_file(self, filename, filepath):
        """
        Upload a file to binary-repository

        @param filename           file name
        @param filepath           file path
        """
        _ok = False
        _res = None
        try:
            if not os.path.exists(filepath):
                raise IOError("Source file not found: {}".format(filepath))

            url = self.__upload_template.substitute(
                protocol=self.protocol,
                host=self.host,
                path=self.__binary_files_path)
            headers = self.__headers
            files_to_up = {
                'file': (filename, open(filepath, 'rb'), "multipart/form-data")
            }

            response = requests.request(RestMethods.POST.value,
                                        url,
                                        headers=headers,
                                        files=files_to_up,
                                        verify=not self.avoid_ssl_certificate)

            if response.status_code == 201:
                _ok = True
                _res = {
                    "id": response.text,
                    "msg": "Succesfully uploaded file"
                }

            else:
                raise Exception("Response: {} - {}".format(
                    response.status_code, response.text))

        except Exception as e:
            log.error("Not possible to upload file: {}".format(e))
            _res = e

        return _ok, _res
Ejemplo n.º 17
0
    def from_json(json_object):
        """
        Creates a object from json-dict/ json-string

        @param json_object    json.dict/ json-string

        @return client        client object
        """
        client = None
        try:
            if type(json_object) == str:
                json_object = json.loads(json_object)

            json_object_keys = list(json_object.keys())
            client = AuthClient(host=json_object['host'])
            if "port" in json_object_keys:
                client.port = json_object['port']
            if "username" in json_object_keys:
                client.username = json_object['username']
            if "password" in json_object_keys:
                client.password = json_object['password']
            if "vertical" in json_object_keys:
                client.vertical = json_object['vertical']
            if "token" in json_object_keys:
                client.token = Token.from_json(json_object['token'])
            if "protocol" in json_object_keys:
                client.protocol = json_object['protocol']
            if "proxies" in json_object_keys:
                client.proxies = json_object['proxies']
            if "timeout" in json_object_keys:
                client.timeout = json_object['timeout']
            if "avoid_ssl_certificate" in json_object_keys:
                client.avoid_ssl_certificate = json_object[
                    'avoid_ssl_certificate']
            if "raise_exceptions" in json_object_keys:
                client.raise_exceptions = json_object['raise_exceptions']

            log.info("Imported json {}".format(json_object))
            client.add_to_debug_trace("Imported json {}".format(json_object))

        except Exception as e:
            log.error("Not possible to import object from json: {}".format(e))

        return client
    def from_json(json_object):
        """
        Creates a object from json-dict/ json-string

        @param json_object    json.dict/ json-string

        @return connection   connection object
        """
        connection = None
        try:
            if type(json_object) == str:
                json_object = json.loads(json_object)
            connection = ApiManagerClient(host=json_object['host'])
            connection.is_connected = json_object['is_connected']
            log.info("Imported json {}".format(json_object))
            connection.add_to_debug_trace(
                "Imported json {}".format(json_object))

        except Exception as e:
            log.error("Not possible to import object from json: {}".format(e))

        return connection
Ejemplo n.º 19
0
    def query(self, ontology, query, query_type):
        """
        Make a query to iot-broker service of the platform

        @param ontology     ontology name
        @param query        query expression
        @param query_type   quert type ['NATIVE', 'SQL']

        @return ok, info
        """
        _ok = False
        _res = None
        try:
            response = self.raw_query(ontology, query, query_type)

            if self.is_correct_status_code(response.status_code):
                _res = response.json()
                log.info("Response: {} - {}".format(
                    response.status_code, _res[0] if len(_res) > 0 else []))
                self.add_to_debug_trace("Response: {} - {}".format(
                    response.status_code, _res[0] if len(_res) > 0 else []))
                _ok = True

            else:
                log.info("Bad response: {status_code} - {text}".format(
                    status_code=response.status_code, text=response.text))
                self.add_to_debug_trace(
                    "Bad response: {status_code} - {text}".format(
                        status_code=response.status_code, text=response.text))
                _res = response.text

        except Exception as e:
            log.error("Not possible to query iot-broker: {}".format(e))
            self.add_to_debug_trace(
                "Not possible to query iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
    def delete(self, ontology, entity_id, return_ids=True):
        """
        Make a insert to iot-broker service of the platform

        @param ontology     ontology name
        @param entity_id    entity object id
        @param return_ids   return ids in response (optional, default: True)

        @return ok, info
        """
        _ok = False
        _res = None
        try:
            response = self.raw_delete(ontology, entity_id, return_ids)

            if self.is_correct_status_code(response.status_code):
                _res = response.json()
                log.info("Query result: {}".format(response.text))
                self.add_to_debug_trace("Query result: {}".format(
                    response.text))
                _ok = True

            else:
                log.info("Bad response: {} - {}".format(
                    response.status_code, response.text))
                self.add_to_debug_trace("Bad response: {} - {}".format(
                    response.status_code, response.text))
                _res = response.text

        except Exception as e:
            log.error("Not possible to delete with iot-broker: {}".format(e))
            self.add_to_debug_trace(
                "Not possible to delete with iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res
    def insert(self, ontology, list_data):
        """
        Make a insert to iot-broker service of the platform

        @param ontology     ontology name
        @param list_data     list with data to insert

        @return ok, info
        """
        _ok = False
        _res = None
        try:
            response = self.raw_insert(ontology, list_data)

            if self.is_correct_status_code(response.status_code):
                _res = response.json()
                log.info("Query result: {}".format(response.text))
                self.add_to_debug_trace("Query result: {}".format(
                    response.text))
                _ok = True

            else:
                log.info("Bad response: {} - {}".format(
                    response.status_code, response.text))
                self.add_to_debug_trace("Bad response: {} - {}".format(
                    response.status_code, response.text))
                _res = response.text

        except Exception as e:
            log.error("Not possible to insert with iot-broker: {}".format(e))
            self.add_to_debug_trace(
                "Not possible to insert with iot-broker: {}".format(e))
            self.raise_exception_if_enabled(e)
            _res = e

        return _ok, _res