Esempio n. 1
0
    def objectsList(self, filter, params):

        # ====================================================================#
        # Prepare Search Settings
        try:
            limit = params["max"]
        except:
            limit = 25
        try:
            offset = params["offset"]
        except:
            offset = 0
        # ====================================================================#
        # Execute Search Query
        query = self.getObjectClass().select().limit(limit).offset(offset)
        # ====================================================================#
        # Init Results
        objects = {}
        # ====================================================================#
        # Walk on Results
        try:
            for faker_object in query:
                objects["short-" +
                        str(faker_object.id)] = self.toListData(faker_object)
        except Exception as exception:
            Framework.log().error(exception.message)
        # ====================================================================#
        # Add Metadata
        objects['meta'] = {
            'current': query.count(),
            'total': self.getObjectClass().select().count()
        }

        return objects
Esempio n. 2
0
    def execute(self, task):
        """Execute Objects Actions"""
        response = self.empty_response(task)

        # READING OF SERVER OBJECT LIST
        if task['name'] == const.__SPL_F_OBJECTS__:
            response['data'] = Framework.getObjects()
            response['result'] = True
            return response

        # Validate Received Task
        if not self.isValidTask(task):
            return response

        # Execute Admin Actions
        if task['name'] in [
                const.__SPL_F_DESC__, const.__SPL_F_FIELDS__,
                const.__SPL_F_LIST__
        ]:
            return self.doAdminActions(task)

        # Execute Sync Actions
        if task['name'] in [
                const.__SPL_F_GET__, const.__SPL_F_SET__, const.__SPL_F_DEL__
        ]:
            return self.doSyncActions(task)

        # Wrong Request Task
        Framework.log().error("Object Router - Requested task not found => " +
                              task['name'])

        return response
Esempio n. 3
0
    def execute(self, task):

        response = self.empty_response(task)

        # READING OF SERVER OBJECT LIST
        if task['name'] == const.__SPL_F_GET_OBJECTS__:
            response['data'] = Framework.getObjects()
            response['result'] = True

        # READING OF SERVER WIDGETS LIST
        if task['name'] == const.__SPL_F_GET_WIDGETS__:
            response['data'] = {}
            response['result'] = True

        # READING OF SERVER SELFTEST RESULTS
        if task['name'] == const.__SPL_F_GET_SELFTEST__:
            response['data'] = True
            response['result'] = True

        # READING OF SERVER INFORMATIONS
        if task['name'] == const.__SPL_F_GET_INFOS__:
            response['data'] = Framework.getClientInfo().get()
            response['result'] = True

        return response
Esempio n. 4
0
 def get(self, object_id, fields):
     # ====================================================================#
     # Init Reading
     self._in = fields
     # ====================================================================#
     # Load Object
     self.object = False
     self.object = self.load(object_id)
     if self.object is False:
         return False
     # ====================================================================#
     # Init Response
     self._out = {'id': object_id}
     # ====================================================================#
     # Run Through All Requested Fields
     for index, field in copy.copy(fields).items():
         # Read Requested Fields
         for method in self.identify_get_methods():
             method(index, field)
     # ====================================================================#
     # Verify Requested Fields List is now Empty => All Fields Read Successfully
     if self._in.__len__():
         from splashpy.core.framework import Framework
         for field in self._in.values():
             Framework.log().error(
                 "Get Object - Requested field not found => " + field)
         return False
     # ====================================================================#
     # Return Object Data
     return self._out
Esempio n. 5
0
    def isValidObjectFieldsList(fields):
        from splashpy.core.framework import Framework
        # Checks List Type
        if not hasattr(fields, '__iter__'):
            return Framework.log().error("Wrong Field List Type")
        # Checks List Not Empty
        if not fields.__len__():
            return Framework.log().error("Field List is Empty")

        return True
Esempio n. 6
0
 def loadOsInformation(self):
     """Load Server Platform Information"""
     import sys
     import socket
     self.server_version = sys.version
     try:
         self.server_host = socket.gethostname()
         self.server_ip = self.server_address = socket.gethostbyname(
             self.server_host)
     except Exception:
         from splashpy.core.framework import Framework
         Framework.log().error("Unable to get Hostname and IP")
Esempio n. 7
0
    def doAdminActions(self, task):
        """Execute Admin Objects Actions"""
        response = self.empty_response(task)
        # Load Object Class
        ws_object = Framework.getObject(task["params"]['type'])

        # READING OF OBJECT DESCRIPTION
        if task['name'] == const.__SPL_F_DESC__:
            if ws_object:
                response['data'] = ws_object.description()
                response['result'] = bool(response['data'].__len__())

        # READING OF OBJECT FIELDS
        if task['name'] == const.__SPL_F_FIELDS__:
            if ws_object:
                response['data'] = ws_object.fields()
                response['result'] = bool(response['data'].__len__())

        # READING OF OBJECTS LIST
        if task['name'] == const.__SPL_F_LIST__:
            try:
                filters = task["params"]["filters"]
            except:
                filters = None
            try:
                parameters = task["params"]["params"]
            except:
                parameters = None
            if ws_object:
                response['data'] = ws_object.objectsList(filters, parameters)
                response['result'] = bool(response['data'].__len__())

        return response
Esempio n. 8
0
 def update(self, needed):
     """Update Current Faker Object"""
     try:
         self.object.save()
         return self.object.id
     except Exception as exception:
         return Framework.log().error(exception)
Esempio n. 9
0
    def isValidTask(task):
        """Verify Received Task"""
        # Verify Requested Object Type is Available
        if not hasattr(task["params"], '__iter__'):
            return Framework.log().error(
                "Object Router - Missing Task Parameters... ")
        # Verify Requested Object Type is Available
        if 'type' not in task["params"]:
            return Framework.log().error(
                "Object Router - Missing Object Type... ")
        # Verify Requested Object Type is Valid
        if not task["params"]['type'] in Framework.getObjects():
            return Framework.log().error(
                "Object Router - Object Type is Invalid... ")

        return True
Esempio n. 10
0
    def get_file(self, path, md5):
        # Walk for File on All Registered Objects
        for object_type in Framework.getObjects():
            object_class = Framework.getObject(object_type)
            file = object_class.getFile(path, md5)
            # Verify File was Found
            if file is None or not isinstance(file, dict):
                continue
            # Verify File Md5
            if file['md5'] != md5:
                continue

            return file

        Framework.log().error("File Not Found")

        return None
Esempio n. 11
0
 def load(self, object_id):
     """Load Faker Object with Id"""
     try:
         return self.getObjectClass().get_by_id(object_id)
     except DoesNotExist:
         return False
     except Exception as exception:
         return Framework.log().error(exception.message)
Esempio n. 12
0
    def setObjectData(self):
        """Execute Fields Update"""
        # ====================================================================#
        # Walk on All Requested Fields
        for field_id, field_data in copy.copy(self._in).items():
            # Write Requested Fields
            for method in self.identify_set_methods():
                method(field_id, field_data)
        # ====================================================================#
        # Verify Requested Fields List is now Empty => All Fields Read Successfully
        if self._in.__len__():
            from splashpy.core.framework import Framework
            for field in self._in.keys():
                Framework.log().error(
                    "Set Object - Requested field not found => " + field)
            return False

        return True
Esempio n. 13
0
 def delete(self, object_id):
     """Delete Faker Object with Id"""
     try:
         fake_object = self.getObjectClass().get_by_id(object_id)
         fake_object.delete_instance()
         return True
     except DoesNotExist:
         return True
     except Exception as exception:
         return Framework.log().error(exception)
Esempio n. 14
0
    def validate(inputs, outputs):

        # Verify Buffers
        if not hasattr(inputs, '__iter__') or not hasattr(outputs, '__iter__'):
            return Framework.log().error(
                'Unable to perform requested action. I/O Buffer not Iterable Type.'
            )

        # Verify Tasks are Defines
        if not 'tasks' in inputs or not hasattr(inputs['tasks'], '__iter__'):
            return Framework.log().warn(
                'Unable to perform requested action, task list is empty.')

        # Verify Tasks are Iterable
        for key in inputs['tasks']:
            if not hasattr(inputs['tasks'][key], '__iter__'):
                return Framework.log().error(
                    'Unable to perform requested action. Task is Iterable Type.'
                )

        return True
Esempio n. 15
0
    def execute(self, task):

        response = self.empty_response(task)
        try:
            path = task["params"]["path"]
            md5 = task["params"]["md5"]
        except:
            Framework.log().error("Files Router - Missing Task Parameters... ")

            return response

        # READING A FILE INFORMATIONS
        if task['name'] == const.__SPL_F_ISFILE__:
            response['data'] = False
            response['result'] = True

        # READING A FILE CONTENTS
        if task['name'] == const.__SPL_F_GETFILE__:
            response['data'] = self.get_file(path, md5)
            response['result'] = True

        return response
Esempio n. 16
0
    def objectsList(self, filter, params):
        """
        Get Objects List

        :param filter: Search filters to apply (TODO)
        :param params: List pagination
        :return: object
        """
        # ====================================================================#
        # Prepare Search Settings
        try:
            limit = int(params["max"])
        except:
            limit = 25
        try:
            offset = int(params["offset"])
        except:
            offset = 0
        # ====================================================================#
        # Execute Search Query
        results = self.getModel().search(self.objectsListFiltered(), limit=limit, offset=offset, order='id')
        # Init Results
        objects = {}
        # Walk on Results
        try:
            for result in results.read(self.get_listed_fields()):
                objects["object-" + str(result['id'])] = result
        except Exception as exception:
            Framework.log().fromException(exception)
        # ====================================================================#
        # Add Metadata
        objects['meta'] = {
            'current': results.__len__(),
            'total': self.getModel().search_count(self.objectsListFiltered())
        }

        return objects
Esempio n. 17
0
    def execute(self, task):

        response = self.empty_response(task)

        # READING OF SERVER WIDGETS LIST
        if task['name'] == const.__SPL_F_WIDGET_LIST__:
            response['data'] = Framework.getWidgets()
            response['result'] = True

        # READING OF SERVER WIDGETS DEFINITION
        if task['name'] == const.__SPL_F_WIDGET_DEFINITION__:
            # Load Widget Class
            ws_widget = Framework.getWidget(task["params"]['type'])
            response['data'] = ws_widget.description()
            response['result'] = True

        # READING OF SERVER WIDGETS CONTENTS
        if task['name'] == const.__SPL_F_WIDGET_GET__:
            # Load Widget Class
            ws_widget = Framework.getWidget(task["params"]['type'])
            response['data'] = ws_widget.get(task["params"]['params'])
            response['result'] = True

        return response
Esempio n. 18
0
    def doSyncActions(self, task):
        """Execute Admin Objects Actions"""
        from splashpy.componants.validator import Validator
        response = self.empty_response(task)
        # Load Object Class
        ws_object = Framework.getObject(task["params"]['type'])
        ws_object_id = task["params"]['id']

        # Verify Object Id
        if not Validator.isValidObjectId(ws_object_id):
            return response

        # READING OF OBJECT DATA
        if task['name'] == const.__SPL_F_GET__:
            ws_fields = task["params"]['fields']
            if ws_object and Validator.isValidObjectFieldsList(ws_fields):
                response['data'] = ws_object.get(ws_object_id, ws_fields)
                response['result'] = (response['data'] != False)

        # WRITING OF OBJECT DATA
        if task['name'] == const.__SPL_F_SET__:
            ws_fields = task["params"]['fields']
            if ws_object and Validator.isValidObjectFieldsList(ws_fields):
                # Take Lock for this object => No Commit Allowed for this Object
                ws_object.lock(ws_object_id)
                # Write Data on local system
                response['data'] = ws_object.set(ws_object_id, ws_fields)
                # Release Lock for this object
                ws_object.unlock(ws_object_id)
                response['result'] = (response['data'] != False)

        # DELETE OBJECT
        if task['name'] == const.__SPL_F_DEL__:
            if ws_object:
                # Take Lock for this object => No Commit Allowed for this Object
                ws_object.lock(ws_object_id)
                response['data'] = ws_object.delete(ws_object_id)
                response['result'] = response['data']

        return response
Esempio n. 19
0
 def create(self):
     """Create a Faker Object """
     try:
         return ShortData.create(varchar=self._in["varchar"])
     except Exception as exception:
         return Framework.log().error(exception)