Esempio n. 1
0
 def __init__(self,
              verb,
              *flags,
              index=None,
              key=None,
              name=None,
              value=None,
              actions=None,
              escapes=None):
     '''
     Construct the action do.
     
     @param verb: string
         The perform action verb, basically what it should do.
     @param flags: arguments[string]
         The flags associated with the action perform.
     @param index: string|None
         The index to associated with the action perform.
     @param key: string|None
         The block key to associated with the action perform.
     @param name: string|None
         The name to associated with the action perform.
     @param value: string|None
         The value to associated with the action perform.
     @param actions: tuple(string)|None
         The action names to associated with the action perform.
     @param escapes: dictionary{string: string}
         The escape dictionary, as a key the value that needs to be escaped and as a value the replacing value.
     '''
     assert isinstance(verb, str), 'Invalid verb %s' % verb
     assert index is None or isinstance(index,
                                        str), 'Invalid index %s' % index
     assert key is None or isinstance(key, str), 'Invalid key %s' % key
     assert name is None or isinstance(name, str), 'Invalid name %s' % name
     assert value is None or isinstance(value,
                                        str), 'Invalid value %s' % value
     if actions is None: actions = ()
     elif not isinstance(actions, tuple): actions = tuple(actions)
     if escapes is None: escapes = immut()
     elif not isinstance(escapes, immut): escapes = immut(escapes)
     assert isinstance(actions, tuple), 'Invalid actions %s' % actions
     assert isinstance(escapes, dict), 'Invalid escapes %s' % escapes
     if __debug__:
         for flag in flags:
             assert isinstance(flag, str), 'Invalid flag %s' % flag
         for action in actions:
             assert isinstance(action, str), 'Invalid action %s' % action
         for replaced, replacer in escapes.items():
             assert isinstance(replaced,
                               str), 'Invalid replaced value %s' % replaced
             assert isinstance(replacer,
                               str), 'Invalid replacer value %s' % replacer
     self.verb = verb
     self.flags = frozenset(flags)
     self.index = index
     self.key = key
     self.name = name
     self.value = value
     self.actions = actions
     self.escapes = escapes
Esempio n. 2
0
    def property(self, name, value, indexBlock=None):
        '''
        @see: IRender.property
        
        @param indexBlock: string
            Index the object with the provided index.
        '''
        assert isinstance(name, str), 'Invalid name %s' % name
        assert isinstance(value, (str, list, dict)), 'Invalid value %s' % value
        if indexBlock is None and not self._block: indexBlock = NAME_BLOCK

        self.begin(name, indexBlock=indexBlock)
        if isinstance(value, list):
            for item in value:
                assert isinstance(item, str), 'Invalid list item %s' % item
                self.startElement(NAME_LIST_ITEM, immut())
                self.characters(item)
                self.endElement(NAME_LIST_ITEM)
        elif isinstance(value, dict):
            for key, item in value.items():
                assert isinstance(key, str), 'Invalid dictionary key %s' % key
                assert isinstance(item,
                                  str), 'Invalid dictionary value %s' % item
                self.startElement(NAME_DICT_ENTRY, immut())
                self.startElement(NAME_DICT_KEY, immut())
                self.characters(key)
                self.endElement(NAME_DICT_KEY)
                self.startElement(NAME_DICT_VALUE, immut())
                self.characters(item)
                self.endElement(NAME_DICT_VALUE)
                self.endElement(NAME_DICT_ENTRY)
        else:
            self.characters(value)
        self.end()
Esempio n. 3
0
 def property(self, name, value, indexBlock=None):
     '''
     @see: IRender.property
     
     @param indexBlock: string
         Index the object with the provided index.
     '''
     assert isinstance(name, str), 'Invalid name %s' % name
     assert isinstance(value, (str, list, dict)), 'Invalid value %s' % value
     if indexBlock is None and not self._block: indexBlock = NAME_BLOCK
     
     self.begin(name, indexBlock=indexBlock)
     if isinstance(value, list):
         for item in value:
             assert isinstance(item, str), 'Invalid list item %s' % item
             self.startElement(NAME_LIST_ITEM, immut())
             self.characters(item)
             self.endElement(NAME_LIST_ITEM)
     elif isinstance(value, dict):
         for key, item in value.items():
             assert isinstance(key, str), 'Invalid dictionary key %s' % key
             assert isinstance(item, str), 'Invalid dictionary value %s' % item
             self.startElement(NAME_DICT_ENTRY, immut())
             self.startElement(NAME_DICT_KEY, immut())
             self.characters(key)
             self.endElement(NAME_DICT_KEY)
             self.startElement(NAME_DICT_VALUE, immut())
             self.characters(item)
             self.endElement(NAME_DICT_VALUE)
             self.endElement(NAME_DICT_ENTRY)
     else:
         self.characters(value)
     self.end()
Esempio n. 4
0
    def __new__(cls, name, bases, namespace):
        if not bases: return super().__new__(cls, name, bases, namespace)

        attributes = {}
        for key, value in namespace.items():
            if isinstance(value, Attribute): attributes[key] = value

        namespace = {
            key: value
            for key, value in namespace.items() if key not in attributes
        }
        namespace['__slots__'] = tuple(attributes)

        self = super().__new__(cls, name, bases, namespace)

        for key, attribute in attributes.items():
            assert isinstance(attribute, Attribute)
            attribute.name = key
            attribute.clazz = self
            attribute.descriptor = getattr(self, key)
            attribute.locked = True
            setattr(self, key, attribute)

        # Adding also the parent attributes.
        for base in bases:
            if base is Bean: continue
            if isinstance(base, BeanMetaClass):
                assert isinstance(base, BeanMetaClass)
                attributes.update(base.__attributes__)

        self.__attributes__ = immut(attributes)

        return self
Esempio n. 5
0
 def value(self, name, value):
     '''
     @see: IRender.value
     '''
     self.xml.startElement(name, immut())
     self.xml.characters(value)
     self.xml.endElement(name)
Esempio n. 6
0
    def __new__(cls, name, bases, namespace):
        if not bases: return super().__new__(cls, name, bases, namespace)

        attributes = {}
        for key, value in namespace.items():
            if isinstance(value, Attribute): attributes[key] = value

        namespace = {key:value for key, value in namespace.items() if key not in attributes}
        namespace['__slots__'] = tuple(attributes)

        self = super().__new__(cls, name, bases, namespace)

        for key, attribute in attributes.items():
            assert isinstance(attribute, Attribute)
            attribute.name = key
            attribute.clazz = self
            attribute.descriptor = getattr(self, key)
            attribute.locked = True
            setattr(self, key, attribute)

        # Adding also the parent attributes.
        for base in bases:
            if base is Bean: continue
            if isinstance(base, BeanMetaClass):
                assert isinstance(base, BeanMetaClass)
                attributes.update(base.__attributes__)

        self.__attributes__ = immut(attributes)

        return self
Esempio n. 7
0
    def __new__(cls, name, bases, namespace):
        if not bases:
            definer = namespace.pop('__definer__', None)
            if not definer: raise TypeError('Invalid context definition, has no __definer__')
            self = super().__new__(cls, name, bases, namespace)
            self.__definer__ = definer
            self.__attributes__ = immut()
            return self

        definer = namespace.get('__definer__')
        if not definer:
            first = bases[0]
            if not isinstance(first, ContextMetaClass):
                raise TypeError('The first inherited class need to be a context class, invalid class %s' % first)
            assert isinstance(first, ContextMetaClass)
            definer = first.__definer__
        
        assert callable(definer), 'Invalid definer %s' % definer
        
        self = super().__new__(cls, *definer(name, bases, namespace))
        
        for name, attribute in self.__attributes__.items():
            assert isinstance(attribute, IAttribute)
            attribute.place(self, name)
        
        return self
Esempio n. 8
0
    def __new__(cls, name, bases, namespace):
        if not bases: return super().__new__(cls, name, bases, namespace)

        attributes = {}
        for key, value in namespace.items():
            if key in ALLOWED: continue
            if not isinstance(value, Attribute):
                raise TypeError('Invalid attribute \'%s\' for name \'%s\'' % (value, key))
            attributes[key] = value

        namespace = {key:value for key, value in namespace.items() if key not in attributes}
        namespace['__slots__'] = tuple(attributes)

        self = super().__new__(cls, name, bases, namespace)

        for key, attribute in attributes.items():
            assert isinstance(attribute, Attribute)
            attribute.name = key
            attribute.clazz = self
            attribute.descriptor = getattr(self, key)
            attribute.locked = True
            setattr(self, key, attribute)

        # Adding also the parent attributes.
        for base in bases:
            if base is Context: continue
            if not isinstance(base, ContextMetaClass):
                raise TypeError('A context class can only inherit other context classes, invalid class %s' % base)
            assert isinstance(base, ContextMetaClass)
            attributes.update(base.__attributes__)

        self.__attributes__ = immut(attributes)

        return self
Esempio n. 9
0
 def objectStart(self, name, attributes=None):
     '''
     @see: IRender.objectStart
     '''
     if not self.processing: self.xml.startDocument()  # Start the document
     self.processing.append(name)
     self.xml.startElement(name, attributes or immut())
Esempio n. 10
0
 def value(self, name, value):
     '''
     @see: IRender.value
     '''
     self.xml.startElement(name, immut())
     self.xml.characters(value)
     self.xml.endElement(name)
Esempio n. 11
0
 def collectionStart(self, name, attributes=None):
     '''
     @see: IRender.collectionStart
     '''
     if not self.processing: self.xml.startDocument() # Start the document
     self.processing.append(name)
     self.xml.startElement(name, attributes or immut())
Esempio n. 12
0
 def __init__(self, verb, *flags, index=None, key=None, name=None, value=None, actions=None, escapes=None):
     '''
     Construct the action do.
     
     @param verb: string
         The perform action verb, basically what it should do.
     @param flags: arguments[string]
         The flags associated with the action perform.
     @param index: string|None
         The index to associated with the action perform.
     @param key: string|None
         The block key to associated with the action perform.
     @param name: string|None
         The name to associated with the action perform.
     @param value: string|None
         The value to associated with the action perform.
     @param actions: tuple(string)|None
         The action names to associated with the action perform.
     @param escapes: dictionary{string: string}
         The escape dictionary, as a key the value that needs to be escaped and as a value the replacing value.
     '''
     assert isinstance(verb, str), 'Invalid verb %s' % verb
     assert index is None or isinstance(index, str), 'Invalid index %s' % index
     assert key is None or isinstance(key, str), 'Invalid key %s' % key
     assert name is None or isinstance(name, str), 'Invalid name %s' % name
     assert value is None or isinstance(value, str), 'Invalid value %s' % value
     if actions is None: actions = ()
     elif not isinstance(actions, tuple): actions = tuple(actions)
     if escapes is None: escapes = immut()
     elif not isinstance(escapes, immut): escapes = immut(escapes)
     assert isinstance(actions, tuple), 'Invalid actions %s' % actions
     assert isinstance(escapes, dict), 'Invalid escapes %s' % escapes
     if __debug__:
         for flag in flags: assert isinstance(flag, str), 'Invalid flag %s' % flag
         for action in actions: assert isinstance(action, str), 'Invalid action %s' % action
         for replaced, replacer in escapes.items():
             assert isinstance(replaced, str), 'Invalid replaced value %s' % replaced
             assert isinstance(replacer, str), 'Invalid replacer value %s' % replacer
     self.verb = verb
     self.flags = frozenset(flags)
     self.index = index
     self.key = key
     self.name = name
     self.value = value
     self.actions = actions
     self.escapes = escapes
Esempio n. 13
0
def definerContext(name, bases, namespace):
    '''
    Process the provided context definition parameters.
        
    @param name: string
        The class name.
    @param bases: tuple(class)
        The inherited classes.
    @param namespace: dictionary{string, object}
        The context name space definition.
    @return: tuple(string, tuple(classes), dictionary{string, object})
        The name, basses and namespace to use in constructing the context class.
    '''
    assert isinstance(namespace, dict), 'Invalid namespace %s' % namespace
    assert isinstance(bases, tuple), 'Invalid bases %s' % bases
    assert bases, 'At least one base class is required'

    attributes = {}
    for key, value in namespace.items():
        if key in ALLOWED: continue
        if not isinstance(value, IAttribute):
            raise TypeError('Invalid attribute \'%s\' for name \'%s\'' %
                            (value, key))
        attributes[key] = value

    # Adding also the parent attributes.
    for base in bases:
        if base is Context: continue
        if not isinstance(base, ContextMetaClass):
            raise TypeError(
                'A context class can only inherit other context classes, invalid class %s'
                % base)
        assert isinstance(base, ContextMetaClass)
        if base.__definer__ != definerContext:
            raise TypeError(
                'Cannot define because of inherited context class %s' % base)

        for key, attribute in base.__attributes__.items():
            if key not in attributes: attributes[key] = attribute

    namespace['__attributes__'] = immut(attributes)
    return name, bases, namespace
Esempio n. 14
0
def definerContext(name, bases, namespace):
    '''
    Process the provided context definition parameters.
        
    @param name: string
        The class name.
    @param bases: tuple(class)
        The inherited classes.
    @param namespace: dictionary{string, object}
        The context name space definition.
    @return: tuple(string, tuple(classes), dictionary{string, object})
        The name, basses and namespace to use in constructing the context class.
    '''
    assert isinstance(namespace, dict), 'Invalid namespace %s' % namespace
    assert isinstance(bases, tuple), 'Invalid bases %s' % bases
    assert bases, 'At least one base class is required'
    
    attributes = {}
    for key, value in namespace.items():
        if key in ALLOWED: continue
        if not isinstance(value, IAttribute):
            raise TypeError('Invalid attribute \'%s\' for name \'%s\'' % (value, key))
        attributes[key] = value
    for key in attributes: namespace.pop(key)
    
    # Adding also the parent attributes.
    for base in bases:
        if base is Context: continue
        if not isinstance(base, ContextMetaClass):
            raise TypeError('A context class can only inherit other context classes, invalid class %s' % base)
        assert isinstance(base, ContextMetaClass)
        if base.__definer__ != definerContext:
            raise TypeError('Cannot define because of inherited context class %s' % base)
        
        for key, attribute in base.__attributes__.items():
            if key not in attributes: attributes[key] = attribute
    
    namespace['__attributes__'] = immut(attributes)
    return name, bases, namespace
Esempio n. 15
0
 def begin(self, name, attributes=None, indexBlock=None, indexAttributesCapture=immut()):
     '''
     Begins a XML tag.
     
     @param attributes: dictionary{string: string}
         The attributes to associate with the object.
     @param indexBlock: string
         Index the object with the provided index.
     @param indexAttributesCapture: dictionary{string: string}
         The dictionary containing as a key the attribute name and as a value the key name as registered
         to associate with the attribute capture.
     '''
     isAdjust = False
     if self._adjust:
         self.startDocument()  # Start the document
         if indexBlock is None:
             assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
             assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
             index = self._index(NAME_XML_START_ADJUST)
             index(IND_DECL)
             isAdjust = True
         self._adjust = False
     if not isAdjust:
         if self._block:
             assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
             assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
             index = None
         elif indexBlock:
             assert isinstance(indexBlock, str), 'Invalid index block %s' % indexBlock
             assert isinstance(indexAttributesCapture, dict), 'Invalid index attributes capture %s' % indexAttributesCapture
             index = self._index(PATTERN_XML_BLOCK % indexBlock)
             self._block = True
         else: index = None
     
     if self._pending_start_element:
         self._write('>')
         if self._pendingStart: self._pendingStart(EIND_TAG)
         self._pending_start_element = False
         self._pendingStart = None
     
     if index: index(SIND_TAG)
     self._write('<')
     if index: index(SIND_NAME)
     self._write(name)
     if index: index(EIND_NAME)
     
     if index: index(SIND_ATTRS)
     if attributes:
         assert isinstance(attributes, dict), 'Invalid attributes %s' % attributes
         for nameAttr, valueAttr in attributes.items():
             assert isinstance(nameAttr, str), 'Invalid attribute name %s' % nameAttr
             assert isinstance(valueAttr, str), 'Invalid attribute value %s' % valueAttr
             
             iname = indexAttributesCapture.get(nameAttr)
             if iname:
                 self._write(' %s=' % nameAttr)
                 index(PSIND_ATTR_CAPTURE % iname, offset=1)  # offset +1 for the comma
                 self._write(quoteattr(valueAttr))
                 index(PEIND_ATTR_CAPTURE % iname, offset= -1)  # offset -1 for the comma
             else: self._write(' %s=%s' % (nameAttr, quoteattr(valueAttr)))
     if index: index(EIND_ATTRS)
             
     if self._short_empty_elements:
         self._pending_start_element = True
         self._pendingStart = index
     else:
         self._write('>')
         if index: index(EIND_TAG)
         
     self._stack.append((name, index, isAdjust))
     return self
Esempio n. 16
0
'''

from ally.api.config import GET, INSERT, UPDATE, DELETE
from ally.api.operator.container import Service, Call
from ally.api.operator.type import TypeModel, TypeModelProperty, TypeService
from ally.api.type import typeFor, Input
from ally.core.impl.invoker import InvokerRestructuring, InvokerCall
from ally.core.impl.node import NodePath, NodeProperty, MatchProperty
from ally.core.spec.resources import Match, Node, Path, ConverterPath, \
    IResourcesRegister, Invoker, PathExtended
from ally.support.util import immut
from collections import deque, Iterable

# --------------------------------------------------------------------

METHOD_NODE_ATTRIBUTE = immut({GET: 'get', INSERT: 'insert', UPDATE: 'update', DELETE: 'delete'})
# Mapping of method and node attribute where the invoker is kept for that method.

# --------------------------------------------------------------------

def pushMatch(matches, match):
    '''
    Adds the match to the matches list, returns True if the match(es) have been added successfully, False if no
    match was added.
    
    @param matches: list[Match]
        The matches to push the match.
    @param match: boolean|list[Match]|tuple(Match)|Match
        The match to push to the the matches list.
    @return: boolean
        True if the match(es) have been added successfully, False if no match was added.
Esempio n. 17
0
Provides HTTP server specification.
'''

from ally.api.config import GET, DELETE, INSERT, UPDATE
from ally.http.spec.server import METHOD_GET, METHOD_DELETE, METHOD_POST, \
    METHOD_PUT, METHOD_OPTIONS
from ally.support.util import immut
import abc

# --------------------------------------------------------------------
# Additional HTTP methods.

OPTIONS = 16
UNKNOWN = -1

METHODS_TO_CORE = immut({METHOD_GET: GET, METHOD_DELETE: DELETE, METHOD_POST: INSERT,
                         METHOD_PUT: UPDATE, METHOD_OPTIONS: OPTIONS})

CORE_TO_METHODS = immut({GET: METHOD_GET, DELETE: METHOD_DELETE, INSERT: METHOD_POST,
                         UPDATE: METHOD_PUT, OPTIONS: METHOD_OPTIONS})

# --------------------------------------------------------------------

class IEncoderPath(metaclass=abc.ABCMeta):
    '''
    Provides the path encoding.
    '''

    @abc.abstractmethod
    def encode(self, path, parameters=None):
        '''
        Encodes the provided path to a full request path.
Esempio n. 18
0
    def begin(self,
              name,
              attributes=None,
              indexBlock=None,
              indexAttributesCapture=immut()):
        '''
        Begins a XML tag.
        
        @param attributes: dictionary{string: string}
            The attributes to associate with the object.
        @param indexBlock: string
            Index the object with the provided index.
        @param indexAttributesCapture: dictionary{string: string}
            The dictionary containing as a key the attribute name and as a value the key name as registered
            to associate with the attribute capture.
        '''
        isAdjust = False
        if self._adjust:
            self.startDocument()  # Start the document
            if indexBlock is None:
                assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                index = self._index(NAME_XML_START_ADJUST)
                index(IND_DECL)
                isAdjust = True
            self._adjust = False
        if not isAdjust:
            if self._block:
                assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                index = None
            elif indexBlock:
                assert isinstance(indexBlock,
                                  str), 'Invalid index block %s' % indexBlock
                assert isinstance(
                    indexAttributesCapture, dict
                ), 'Invalid index attributes capture %s' % indexAttributesCapture
                index = self._index(PATTERN_XML_BLOCK % indexBlock)
                self._block = True
            else:
                index = None

        if self._pending_start_element:
            self._write('>')
            if self._pendingStart: self._pendingStart(EIND_TAG)
            self._pending_start_element = False
            self._pendingStart = None

        if index: index(SIND_TAG)
        self._write('<')
        if index: index(SIND_NAME)
        self._write(name)
        if index: index(EIND_NAME)

        if index: index(SIND_ATTRS)
        if attributes:
            assert isinstance(attributes,
                              dict), 'Invalid attributes %s' % attributes
            for nameAttr, valueAttr in attributes.items():
                assert isinstance(nameAttr,
                                  str), 'Invalid attribute name %s' % nameAttr
                assert isinstance(
                    valueAttr, str), 'Invalid attribute value %s' % valueAttr

                iname = indexAttributesCapture.get(nameAttr)
                if iname:
                    self._write(' %s=' % nameAttr)
                    index(PSIND_ATTR_CAPTURE % iname,
                          offset=1)  # offset +1 for the comma
                    self._write(quoteattr(valueAttr))
                    index(PEIND_ATTR_CAPTURE % iname,
                          offset=-1)  # offset -1 for the comma
                else:
                    self._write(' %s=%s' % (nameAttr, quoteattr(valueAttr)))
        if index: index(EIND_ATTRS)

        if self._short_empty_elements:
            self._pending_start_element = True
            self._pendingStart = index
        else:
            self._write('>')
            if index: index(EIND_TAG)

        self._stack.append((name, index, isAdjust))
        return self
Esempio n. 19
0
    def begin(self,
              name,
              of,
              attributes=None,
              indexBlock=None,
              indexAttributesCapture=immut()):
        '''
        Used to open a JSON object.
        
        @param attributes: dictionary{string: string}
            The attributes to associate with the object.
        @param indexBlock: string
            Index the object with the provided index.
        @param indexAttributesCapture: dictionary{string: string}
            The dictionary containing as a key the attribute name and as a value the key name as registered
            to associate with the attribute capture.
        '''
        hasNameProp = self._stack and self._stack[0][0] == OF_OBJECT
        isAdjust, hasName = False, of == OF_COLLECTION or hasNameProp
        if self._adjust:
            if indexBlock is None:
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                assert of in (
                    OF_OBJECT,
                    OF_COLLECTION), 'Invalid adjusting for of %s action' % of
                index = self._index(NAME_JSON_START_ADJUST)
                isAdjust = True
            self._adjust = False
        if not isAdjust:
            if self._block:
                assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                index = None
            elif indexBlock:
                assert isinstance(indexBlock,
                                  str), 'Invalid index block %s' % indexBlock
                assert isinstance(
                    indexAttributesCapture, dict
                ), 'Invalid index attributes capture %s' % indexAttributesCapture
                if hasName:
                    index = self._index(PATTERN_JSON_BLOCK_NAMED % indexBlock)
                else:
                    index = self._index(PATTERN_JSON_BLOCK_UNAMED % indexBlock,
                                        {KEY_NAME: name})
                self._block = True
            else:
                index = None

        if index: index(SIND_ENTRY, SIND_COMMA)
        if not self._first:
            self._out.write(',')
        if of == OF_PROPERTY: self._first = False
        else: self._first = True
        if index: index(EIND_COMMA)

        if hasNameProp:
            if index: index(SIND_NAME, offset=1)  # offset +1 for the comma
            self._out.write('"%s"' % name)
            if index: index(EIND_NAME, offset=-1)  # offset -1 for the comma
            self._out.write(':')
        elif index:
            index(SIND_NAME, EIND_NAME)

        self._stack.appendleft((of, index, isAdjust))
        if of == OF_PROPERTY: return

        if index: index(SIND_VALUE)
        self._out.write('{')

        if index: index(SIND_ATTRS)
        if attributes:
            assert isinstance(attributes,
                              dict), 'Invalid attributes %s' % attributes
            for nameAttr, valueAttr in attributes.items():
                assert isinstance(nameAttr,
                                  str), 'Invalid attribute name %s' % nameAttr

                if self._first: self._first = False
                else: self._out.write(',')
                self._out.write('"%s"' % nameAttr)
                self._out.write(':')

                iname = indexAttributesCapture.get(nameAttr)
                if iname:
                    offset = 1 if isinstance(valueAttr, str) else 0
                    index(PSIND_ATTR_CAPTURE % iname,
                          offset=offset)  # offset +1 for the comma
                    self._out.write(encode(valueAttr))
                    index(PEIND_ATTR_CAPTURE % iname,
                          offset=-offset)  # offset -1 for the comma
                else:
                    self._out.write(encode(valueAttr))
        if index: index(EIND_ATTRS)

        if of == OF_COLLECTION:
            if not self._first:
                self._out.write(',')
                self._first = True

            if index: index(SIND_NAME, offset=1)  # offset +1 for the comma
            self._out.write('"%s"' % name)
            if index: index(EIND_NAME, offset=-1)  # offset -1 for the comma
            self._out.write(':[')

        if isAdjust: index(IND_DECL)
Esempio n. 20
0
    def begin(self, name, of, attributes=None, indexBlock=None, indexAttributesCapture=immut()):
        '''
        Used to open a JSON object.
        
        @param attributes: dictionary{string: string}
            The attributes to associate with the object.
        @param indexBlock: string
            Index the object with the provided index.
        @param indexAttributesCapture: dictionary{string: string}
            The dictionary containing as a key the attribute name and as a value the key name as registered
            to associate with the attribute capture.
        '''
        hasNameProp = self._stack and self._stack[0][0] == OF_OBJECT
        isAdjust, hasName = False, of == OF_COLLECTION or hasNameProp
        if self._adjust:
            if indexBlock is None:
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                assert of in (OF_OBJECT, OF_COLLECTION), 'Invalid adjusting for of %s action' % of
                index = self._index(NAME_JSON_START_ADJUST)
                isAdjust = True
            self._adjust = False
        if not isAdjust:
            if self._block:
                assert indexBlock is None, 'No index block expected, but got %s' % indexBlock
                assert not indexAttributesCapture, 'No attributes capture expected, but got %s' % indexAttributesCapture
                index = None
            elif indexBlock:
                assert isinstance(indexBlock, str), 'Invalid index block %s' % indexBlock
                assert isinstance(indexAttributesCapture, dict), 'Invalid index attributes capture %s' % indexAttributesCapture
                if hasName: index = self._index(PATTERN_JSON_BLOCK_NAMED % indexBlock)
                else: index = self._index(PATTERN_JSON_BLOCK_UNAMED % indexBlock, {KEY_NAME: name})
                self._block = True
            else: index = None

        if index: index(SIND_ENTRY, SIND_COMMA)
        if not self._first:
            self._out.write(',')
        if of == OF_PROPERTY: self._first = False
        else: self._first = True
        if index: index(EIND_COMMA)
            
        if hasNameProp:
            if index: index(SIND_NAME, offset=1)  # offset +1 for the comma
            self._out.write('"%s"' % name)
            if index: index(EIND_NAME, offset= -1)  # offset -1 for the comma
            self._out.write(':')
        elif index: index(SIND_NAME, EIND_NAME)
        
        self._stack.appendleft((of, index, isAdjust))
        if of == OF_PROPERTY: return
        
        if index: index(SIND_VALUE)
        self._out.write('{')
        
        if index: index(SIND_ATTRS)
        if attributes:
            assert isinstance(attributes, dict), 'Invalid attributes %s' % attributes
            for nameAttr, valueAttr in attributes.items():
                assert isinstance(nameAttr, str), 'Invalid attribute name %s' % nameAttr
                
                if self._first: self._first = False
                else: self._out.write(',')
                self._out.write('"%s"' % nameAttr)
                self._out.write(':')

                iname = indexAttributesCapture.get(nameAttr)
                if iname:
                    offset = 1 if isinstance(valueAttr, str) else 0
                    index(PSIND_ATTR_CAPTURE % iname, offset=offset)  # offset +1 for the comma
                    self._out.write(encode(valueAttr))
                    index(PEIND_ATTR_CAPTURE % iname, offset= -offset)  # offset -1 for the comma
                else: self._out.write(encode(valueAttr))
        if index: index(EIND_ATTRS)
        
        if of == OF_COLLECTION:
            if not self._first:
                self._out.write(',')
                self._first = True
                
            if index: index(SIND_NAME, offset=1)  # offset +1 for the comma
            self._out.write('"%s"' % name)
            if index: index(EIND_NAME, offset= -1)  # offset -1 for the comma
            self._out.write(':[')
        
        if isAdjust: index(IND_DECL)
Esempio n. 21
0
from ally.api.config import GET, INSERT, UPDATE, DELETE
from ally.api.operator.container import Service, Call
from ally.api.operator.type import TypeModel, TypeModelProperty, TypeService
from ally.api.type import typeFor, Input
from ally.core.impl.invoker import InvokerRestructuring, InvokerCall
from ally.core.impl.node import NodePath, NodeProperty, MatchProperty
from ally.core.spec.resources import Match, Node, Path, ConverterPath, \
    IResourcesRegister, Invoker, PathExtended
from ally.support.util import immut
from collections import deque, Iterable

# --------------------------------------------------------------------

METHOD_NODE_ATTRIBUTE = immut({
    GET: 'get',
    INSERT: 'insert',
    UPDATE: 'update',
    DELETE: 'delete'
})
# Mapping of method and node attribute where the invoker is kept for that method.

# --------------------------------------------------------------------


def pushMatch(matches, match):
    '''
    Adds the match to the matches list, returns True if the match(es) have been added successfully, False if no
    match was added.
    
    @param matches: list[Match]
        The matches to push the match.
    @param match: boolean|list[Match]|tuple(Match)|Match
Esempio n. 22
0
    def populate(self, identifier, obj):
        '''
        Populates the gateway based on the provided dictionary object.
        @see: gateway-http/gateway.http.gateway
        
        @param identifier: Identifier
            The identifier object to populate.
        @param obj: dictionary{string: string|list[string]}
            The dictionary used for defining the gateway object, the object as is defined from response.
        @return: Identifier
            The populated identifier object.
        '''
        assert isinstance(identifier, Identifier), 'Invalid identifier %s' % identifier
        assert isinstance(obj, dict), 'Invalid object %s' % obj
        
        pattern = obj.get('Pattern')
        if pattern:
            assert isinstance(pattern, str), 'Invalid pattern %s' % pattern
            identifier.pattern = re.compile(pattern)
        
        headers = obj.get('Headers', immut()).get('Headers')
        if headers:
            assert isinstance(headers, list), 'Invalid headers %s' % headers
            if __debug__:
                for header in headers: assert isinstance(header, str), 'Invalid header value %s' % header
            identifier.headers.extend(re.compile(header) for header in headers)
        
        methods = obj.get('Methods', immut()).get('Methods')
        if methods:
            assert isinstance(methods, list), 'Invalid methods %s' % methods
            if __debug__:
                for method in methods: assert isinstance(method, str), 'Invalid method value %s' % method
            identifier.methods.update(method.upper() for method in methods)
            
        errors = obj.get('Errors', immut()).get('Errors')
        if errors:
            assert isinstance(errors, list), 'Invalid errors %s' % errors
            for error in errors:
                try: identifier.errors.add(int(error))
                except ValueError: raise ValueError('Invalid error value \'%s\'' % error)
        
        gateway = identifier.gateway
        assert isinstance(gateway, GatewayRepository), 'Invalid gateway %s' % gateway
        
        gateway.filters = obj.get('Filters', immut()).get('Filters')
        if __debug__ and gateway.filters:
            assert isinstance(gateway.filters, list), 'Invalid filters %s' % gateway.filters
            for item in gateway.filters: assert isinstance(item, str), 'Invalid filter value %s' % item
                
#        gateway.host = obj.get('Host')
#        assert not gateway.host or isinstance(gateway.host, str), 'Invalid host %s' % gateway.host
#        
#        gateway.protocol = obj.get('Protocol')
#        assert not gateway.protocol or isinstance(gateway.protocol, str), 'Invalid protocol %s' % gateway.protocol
        
        gateway.navigate = obj.get('Navigate')
        assert not gateway.navigate or isinstance(gateway.navigate, str), 'Invalid navigate %s' % gateway.navigate
        
        putHeaders = obj.get('PutHeaders', immut()).get('PutHeaders')
        if putHeaders:
            assert isinstance(putHeaders, list), 'Invalid put headers %s' % putHeaders
            if __debug__:
                for putHeader in putHeaders:
                    assert isinstance(putHeader, str), 'Invalid put header value %s' % putHeader
                    assert len(putHeader.split(':')), 'Invalid put header value %s' % putHeader
            gateway.putHeaders = [putHeader.split(':', 1) for putHeader in putHeaders]
        
        return identifier