Example #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
Example #2
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
Example #3
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
Example #4
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
Example #5
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")
Example #6
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)
Example #7
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
Example #8
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
Example #9
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)
Example #10
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
Example #11
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)
Example #12
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
Example #13
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
Example #14
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
Example #15
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)