Ejemplo n.º 1
0
    def _create_request(self, recorder_type, client_request, **options):
        '''
        Creates request data.

        @param str recorder_type: recorder type
        @param dict client_request: client request
        @param dict client_response: client response
        @param dict error: error

        @return: request data
        '''

        request_header = \
            DynamicObject(recorder_type=recorder_type,
                          version=RequestRecordManager.CURRENT_REQUEST_HEADER_VERSION)

        data = \
            DynamicObject(request_header=request_header)

        request = \
            DynamicObject(request_id=client_request.id,
                          transaction_id=client_request.transaction_id,
                          user_name=client_request.user_name,
                          client_ip=client_request.ip,
                          service_id=client_request.command_key,
                          receieve_date=client_request.recieve_date,
                          request_date=client_request.request_date,
                          trace_id=client_request.trace_id,
                          data=data)

        return request
def login(login_request):
    """
    Authenticates the given credentials and returns login information.

    @param instance login_request: Raw request recevied from client.

    @return: login data
    @rtype: instance
    """
    converter = login_request.get_converter()

    if converter is not None:
        login_request = converter.to_internal(login_request.get_request_dict())
    else:
        login_request = login_request.get_request_dict()

    try:
        # For calculating execution time.
        process_start_time = time.time()

        if login_request.get('options') is None:
            login_request['options'] = {}

        login_request['options']['client_ip'] = login_request['ip']

        login_info = DynamicObject()
        login_info.ticket = authentication_services.login(login_request['user_name'],
                                                          login_request['password'],
                                                          **login_request['options'])
        login_info.data = {}
        login_info.login_date = datetime.datetime.now()

        # Note: This should be refactored later. (see comment on `login_event').
        login_event(None, None,
                    login_request['ip'],
                    login_request['user_name'],
                    login_request['password'],
                    result=login_info,
                    **login_request['options'])

        LOGGER.info('User[{user}@{ip}],Channel[{channel}],Ticket[{ticket}] logged in. Time: [{execution_time}]'.format(user=login_request['user_name'],
                                                                                                                       ip=login_request['ip'],
                                                                                                                       channel=login_request['options'].get('channel'),
                                                                                                                       ticket=login_info['ticket'],
                                                                                                                       execution_time=time.time() - process_start_time))

        if converter is not None:
            login_info = converter.to_external(login_info)

        return login_info

    except Exception as error:
        LOGGER.error('User[{user}@{ip}],Channel[{channel}] Login failed: {error}'.format(user=login_request['user_name'],
                                                                                                          ip=login_request['ip'],
                                                                                                          channel=login_request['options'].get('channel'),
                                                                                                          error=str(error)))
        raise
Ejemplo n.º 3
0
    def register(self, invoice_items):
        '''
        Registers new invoice.

        :param invoice_items:
        :return:
        '''

        if invoice_items is None or len(invoice_items) <= 0:
            raise InvoiceException('At least one item should be included.')

        current_user = get_current_user()
        store = get_current_transaction_store()

        invoice = InvoiceEntity()
        invoice.invoice_consumer_user_id = current_user.id
        invoice.invoice_date = datetime.datetime.now()
        invoice.invoice_status = InvoiceEntity.InvoiceStatusEnum.ORDERED
        invoice.invoice_id = unicode(unique_id_services.get_id('uuid'))
        store.add(invoice)

        counter = 1
        result = DynamicObject(entity_to_dic(invoice))
        result.invoice_items = []
        for item in invoice_items:
            item_entity = InvoiceItemEntity()
            item_entity.invoice_id = invoice.invoice_id
            item_entity.item_color = unicode(item.get('color'))
            item_entity.item_size = unicode(item.get('size'))
            item_entity.item_brand = unicode(item.get('brand'))
            item_entity.item_id = unicode(unique_id_services.get_id('uuid'))
            item_entity.item_price = Decimal(str(item.get('price')))
            item_entity.item_quantity = int(item.get('quantity'))
            item_entity.item_row = counter
            item_entity.item_product_id = unicode(item.get('product_id'))

            products_services.decrease_product_counter(
                item_entity.item_product_id)
            product = products_services.get(item_entity.item_product_id,
                                            fetch_details=False)
            if (product.product_whole_sale_type
                    == ProductsEntity.ProductWholesaleTypeEnum.WHOLESALE
                    and current_user.user_production_type !=
                    UserEntity.UserProductionTypeEnum.PRODUCER):
                raise InvoiceException(
                    "User [{0} - {1}] is not producer one and can not register "
                    "product [{2}] which is wholesale product type.".format(
                        current_user.user_id, current_user.user_name,
                        product.product_name))

            counter += 1

            store.add(item_entity)
            result.invoice_items.append(
                DynamicObject(entity_to_dic(item_entity)))

        return result
Ejemplo n.º 4
0
 def __init__(self, request, result, call_context):
     DynamicObject.__init__(self)
     self.request_id = request.id
     self.transaction_id = request.transaction_id
     self.trace_id = request.trace_id
     self.result = result
     self.context = call_context
     self.request_date = request.request_date
     self.recieve_date = request.recieve_date
     self.send_date = datetime.datetime.now()
Ejemplo n.º 5
0
    def get_info(self):
        '''
        Returns information about active request processor.
        
        @return: DynamicObject
        '''

        processor = self.get_processor()
        info = DynamicObject(mode=processor.get_name())
        info.update(processor.get_params())
        return info
Ejemplo n.º 6
0
    def register(self, channel_id, certificate, **options):
        '''
        Registers a new channel.
        
        @param channel_id: channel ID
        @param certificate: certificate content
        @param **options: 
            description: channel description
            enabled: channel enable flag
        '''

        message = 'Trying to register channel [{0}]'
        ChannelManager.LOGGER.debug(message.format(channel_id))

        # Checking channel existence
        if self.is_registered(channel_id):
            message = _('Channel {0} is already registered.')
            raise ChannelManagerException(message.format(channel_id))

        # Checking the previous channel with the same certificate
        registered_channel = \
            self.try_get_by_certificate(certificate)
        if registered_channel is not None:
            message = _('Certificate is in use.')
            raise ChannelManagerException(message)

        # Deciding on important parameters
        options['description'] = options.get('description')
        options['enabled'] = options.get('enabled')
        if options['enabled'] is None:
            options['enabled'] = True
        options['certificate_required'] = options.get('certificate_required')
        if options['certificate_required'] is None:
            options['certificate_required'] = True

        # Setting allowed and denied commands
        options['allowed'] = options.get('allowed')
        options['denied'] = options.get('denied')

        # Creating channel information
        channel = DynamicObject(id=channel_id, certificate=certificate)
        channel.update(options)

        # Registering channel
        self._channels[channel_id] = channel

        message = 'Channel [{0}] successfully registered'
        ChannelManager.LOGGER.info(message.format(channel_id))
Ejemplo n.º 7
0
    def bulk_execute(self, commands, **options):
        '''
        Executes a command by given key.
        
        @param commands: command data list as dict<command_key, args, kwargs>:
            command_key: command key
            args: command arguments
            kwargs: command keyword arguments
        @param **options: 
        @return: object
        '''

        if len(commands) == 0:
            raise CommandManagerException('There is no command to execute.')

        results = []
        for command_data in commands:
            command_key = command_data['command_key']
            args = command_data.get('args', tuple())
            if not isinstance(args, (tuple, list)):
                args = (args, )
            kwargs = command_data.get('kwargs', dict())
            result = self.execute(command_key, *args, **kwargs)
            results.append(
                DynamicObject(command_key=command_key, command_result=result))
        return results
Ejemplo n.º 8
0
    def select(self, fields, command_key, *args, **kwargs):
        '''
        Executes a command and returns requested fields. 
        
        @param fields: list of requested fields 
        @param command_key: command key
        @param *args:
        @param **kwargs:
        
        @return: [DynamicObject<fields>]  
        '''

        result = self.execute(command_key, *args, **kwargs)
        results = result
        if not isinstance(result, list):
            results = [result]

        if fields is None or len(fields) == 0:
            return results

        selected_resultes = []
        for obj in results:
            record = DynamicObject()
            for field in fields:
                record[field] = obj.get(field)
            selected_resultes.append(record)
        return selected_resultes
Ejemplo n.º 9
0
    def get_users(self, **options):
        """
        Returns users using given options.

        @return: [DynamicObject<user info...>]
        """

        expressions = []

        statuses = options.get('statuses')
        if statuses is not None and len(statuses) > 0:
            expressions.append(In(UserEntity.user_status, statuses))

        types = options.get('types')
        if types is not None and len(types) > 0:
            expressions.append(In(UserEntity.user_type, types))

        store = get_current_transaction_store()
        entities = store.find(UserEntity, And(*expressions))

        results = []
        for user in entities:
            if user.user_id not in ('admin', 'root', 'support'):
                results.append(DynamicObject(entity_to_dic(user)))

        return results
Ejemplo n.º 10
0
    def execute(self, ip, ticket, user_name, command_key, *args, **kargs):
        '''
        Executes the given command.
        
        @param ip: client ip
        @param ticket: user ticket
        @param user_name: user name
        @param command_key: command key
        
        @return: object
        
        @note: This method is existed for backward compability.
            `execute_ex' should be used instead.
        '''
        request = self._client_request_class(
            DynamicObject(request_id=None,
                          transaction_id=None,
                          request_date=None,
                          ip=ip,
                          ticket=ticket,
                          user_name=user_name,
                          command_key=command_key,
                          command_args=args,
                          command_kwargs=kargs,
                          timeout=None,
                          context=None))

        response = self._communicator.execute(self, request)

        return response['result']
Ejemplo n.º 11
0
    def get_product_brands(self, product_id, **options):
        '''
        Returns product brands.

        :param product_id:
        :return:
        '''

        store = get_current_transaction_store()

        statement = \
            Select(columns=[ProductsBrandsEntity.product_brand,
                            ProductsBrandsEntity.product_brand_id],
                   where=And(ProductsBrandsEntity.product_id == product_id),
                   tables=[ProductsBrandsEntity])

        results = []
        for (product_brand, product_brand_id) in store.execute(statement):
            results.append(
                DynamicObject(product_brand=product_brand,
                              product_brand_id=product_brand_id))

        concat_results = options.get('concat_results')
        if concat_results is None:
            concat_results = False

        if concat_results:
            return ','.join([b.product_brand for b in results])

        return results
Ejemplo n.º 12
0
    def get_events(self):
        '''
        Returns all registered events.
        '''

        results = []
        for event in self._events.values():
            event_hanlders = event.get_handlers()
            handlers = []
            for event_hanlder in event_hanlders:
                handlers.append(
                    DynamicObject(name=event_hanlder.get_name(),
                                  enable=event_hanlder.is_enable()))
            results.append(
                DynamicObject(name=event.get_name(),
                              enable=event.is_enable(),
                              handlers=handlers))
        return results
Ejemplo n.º 13
0
    def get(self, product_history_id):
        """
        Returns product history info.

        :param product_history_id:
        :return:
        """

        entity = self._get(product_history_id)
        return DynamicObject(entity_to_dic(entity))
Ejemplo n.º 14
0
 def _session_to_dynamic_object(self, session):
     '''
     @param session:
     '''
     
     return DynamicObject(id = session.get_id(),
                          state = session.get_state(),
                          creation_date = session.get_creation_date(),
                          user_id = session.get_user_id(),
                          client_ip = session.get_client_ip()) 
Ejemplo n.º 15
0
 def _create_cache_(self, sock, ip, name, data):
     request = ('create', name, data)
     request = cPickle.dumps(request)
     sock.send(request)
     response = sock.recv(MAX_DATA_SIZE)
     port, auth_key = cPickle.loads(response)
     if port == 0:
         raise RemoteCacheProviderException(
             "Could'nt create cache[{name}]".format(name=name))
     return DynamicObject(ip=ip, cache_port=port, auth_key=auth_key)
Ejemplo n.º 16
0
    def create_user(self, id, password, fullname, **options):
        '''
        Creates a new user.
        
        @param id: user ID
        @param password: password
        @param fullname: full name
        @param **options: 
        '''

        return DynamicObject(id = id, password = password, name = id, fullname = fullname)
Ejemplo n.º 17
0
    def find(self, **options):
        """
        Searches product histories.

        :param optiosn:
        :return:
        """

        from_edit_date = options.get('from_edit_date')
        to_edit_date = options.get('to_edit_date')
        from_price = options.get('from_price')
        to_price = options.get('to_price')
        name = options.get('name')
        categories = options.get('categories')
        include_out_of_stock = options.get('include_out_of_stock')
        if include_out_of_stock is None:
            include_out_of_stock = False

        expressions = []
        if not include_out_of_stock:
            expressions.append(
                ProductsHistoryEntity.product_history_status ==
                ProductsHistoryEntity.ProductHistoryStatusEnum.IN_STOCK)
        if from_edit_date is not None:
            expressions.append(ProductsHistoryEntity.product_history_edit_date
                               >= from_edit_date)
        if to_edit_date is not None:
            expressions.append(
                ProductsHistoryEntity.product_history_edit_date <= to_edit_date
            )
        if from_price is not None:
            expressions.append(
                ProductsHistoryEntity.product_history_price >= from_price)
        if to_price is not None:
            expressions.append(
                ProductsHistoryEntity.product_history_price >= to_price)
        if name is not None and name.strip() != "":
            expressions.append(
                Like(ProductsHistoryEntity.product_history_name,
                     "%{0}%".format(name)))
        if categories is not None and len(categories) > 0:
            expressions.append(
                In(ProductsHistoryEntity.product_history_category, categories))

        store = get_current_transaction_store()
        entities = store.find(
            ProductsHistoryEntity, And(*expressions)).order_by(
                ProductsHistoryEntity.product_history_edit_date)

        results = []
        for entity in entities:
            results.append(DynamicObject(entity_to_dic(entity)))

        return results
Ejemplo n.º 18
0
    def get(self, invoice_id):
        '''
        Returns invoice info.

        :param invoice_id:
        :return:
        '''

        entity = self._get(invoice_id)

        invoice = DynamicObject(entity_to_dic(entity))

        store = get_current_transaction_store()
        item_entities = \
            store.find(InvoiceItemEntity, InvoiceItemEntity.invoice_id == invoice_id).order_by(InvoiceItemEntity.item_row)

        invoice.items = []
        for item in item_entities:
            invoice.items.append(DynamicObject(entity_to_dic(item)))

        return invoice
Ejemplo n.º 19
0
 def get_permission(self, id):
     '''
     Returns specified permission information.
     @param id:
     '''
     
     store = get_current_transaction_store()
     entity = store.get(PermissionEntity, unicode(id))
     if entity is None:
         message = _('Permission [{permission_id}] not found.')
         raise PermissionNotFoundException(message.format(permission_id = id))
     return DynamicObject(entity_to_dic(entity))
Ejemplo n.º 20
0
    def get(self, purchase_id):
        '''
        Returns Purchase info.

        :param Purchase_id:
        :return:
        '''

        entity = self._get(purchase_id)

        purchase = DynamicObject(entity_to_dic(entity))

        store = get_current_transaction_store()
        item_entities = \
            store.find(PurchasesCommentEntity, PurchasesCommentEntity.purchase_id == purchase_id).order_by(PurchasesCommentEntity.purchase_comment_date)

        purchase.items = []
        for item in item_entities:
            purchase.items.append(DynamicObject(entity_to_dic(item)))

        return purchase
Ejemplo n.º 21
0
    def logout(self, ip, ticket, user_name):
        '''
        Log outs the user.
         
        @param ip: client ip
        @param ticket: user ticket
        @param user_name: user name
        '''
        logout_request = self._client_request_class(
            DynamicObject(ip=ip, ticket=ticket, user_name=user_name))

        return self._communicator.logout(self, logout_request)
Ejemplo n.º 22
0
    def get_default_settings(self, process_unit_name):
        '''
        Returns default settings of given process unit.
        
        @param process_unit_name: process unit name
        @return: DynamicObject
        '''

        # Getting process unit default parameters
        params = self.__get_process_unit_config__(process_unit_name)

        return DynamicObject(params)
Ejemplo n.º 23
0
    def get_by_name(self, name, category, **options):
        """
        Returns product info.

        :param category:
        :param name:
        :return:
        """

        unique_name = generate_product_unique_name(name, category)

        store = get_current_transaction_store()
        entity = store.find(
            ProductsEntity,
            ProductsEntity.product_unique_name == unique_name).one()

        if entity is None:
            raise ProductsException("Product [{0}] not found".format(name))

        product = DynamicObject(entity_to_dic(entity))

        fetch_details = options.get('fetch_details')
        if fetch_details is None:
            fetch_details = True

        if fetch_details:
            store = get_current_transaction_store()

            product.colors = []
            colors = store.find(
                ProductsColorsEntity,
                ProductsColorsEntity.product_id == product.product_id)
            product.colors.extend(
                [DynamicObject(entity_to_dic(e)) for e in colors])

            product.sizes = []
            sizes = store.find(
                ProductsSizesEntity,
                ProductsSizesEntity.product_id == product.product_id)
            product.sizes.extend(
                [DynamicObject(entity_to_dic(e)) for e in sizes])

            product.brands = []
            brands = store.find(
                ProductsBrandsEntity,
                ProductsBrandsEntity.product_id == product.product_id)
            product.brands.extend(
                [DynamicObject(entity_to_dic(e)) for e in brands])

        return product
Ejemplo n.º 24
0
def ddict_to_dict(ddct):
    '''
    Converts a DDictionary object to Python dictionary.
    
    @param ddct: DDictionary
    '''
    if ddct is None:
        return None
    dct = DynamicObject()
    for k in ddct:
        v = ddct[k]
        dct[k] = dobject_to_object(v)
    return dct
Ejemplo n.º 25
0
    def get_role(self, id):
        '''
        Returns role information by given role ID.
        
        @param role_id: role ID
        '''

        store = get_current_transaction_store()
        entity = store.get(RoleEntity, unicode(id))
        if entity is None:
            message = _('Role [{role_id}] not found.')
            raise RoleNotFoundException(message.format(role_id = id))
        return DynamicObject(entity_to_dic(entity))
Ejemplo n.º 26
0
    def __get_process_unit_config__(self, name):
        '''
        Returns process unit configuration from batch.config file.
        
        @param name: process unit name
        '''

        # Getting batch configuration store
        config_store = config.get_app_config_store('batch')

        # Getting default parameters from configuration file.
        if config_store.has_section(name):
            return config_store.get_section_data(name)
        return DynamicObject(thread_count=1)
Ejemplo n.º 27
0
    def login_ex(self, ip, user_name, password, **options):
        '''
        Logins in application.
        
        @param ip: client IP address
        @param user_name: user name
        @param password: user password
        '''
        login_request = self._client_request_class(
            DynamicObject(ip=ip,
                          user_name=user_name,
                          password=password,
                          options=options))

        return self._communicator.login(self, login_request)
Ejemplo n.º 28
0
 def get_user(self, id):
     '''
     Returns user information by specified name
     
     @param id: user name
     
     @return: user data as DynamicObject
     '''
     
     store = get_current_transaction_store()
     entity = store.get(UserEntity, unicode(id))
     if entity is None:
         message = 'User [{user_id}] not found.'
         raise UserNotFoundException(message.format(user_id = id))
     return DynamicObject(entity_to_dic(entity))
Ejemplo n.º 29
0
    def get_permission_roles(self, permission_id, **options):
        '''
        Returns all roles which are including specified permission.
        
        @param permission_id: permission ID
        
        @return: [role as DynamicObject]
        '''

        store = get_current_transaction_store()
        entities = store.find(RoleEntity, And(RoleEntity.id == Role2PermissionEntity.role_id,
                                              Role2PermissionEntity.permission_id == unicode(permission_id)))
        results = []
        for entity in entities:
            results.append(DynamicObject(entity_to_dic(entity)))
        return results
Ejemplo n.º 30
0
 def get_role_users(self, role_id, **options):
     '''
     Returns all user which are assigned to specified role.
     
     @param role_id: role ID
     
     @return: [user as DynamicObject]
     '''
     
     store = get_current_transaction_store()
     entities = store.find(UserEntity, And(UserEntity.id == User2RoleEntity.user_id,
                                           User2RoleEntity.role_id == unicode(role_id)))
     results = []
     for entity in entities:
         results.append(DynamicObject(entity_to_dic(entity)))
     return results