Exemplo n.º 1
0
    def __init__(self, obj, tag):
        if not isinstance(obj, VReference):
            if isinstance(obj, VNativeObject):
                if obj._v_native_tag() != tag:
                    raise VTaggedParseError('VNative tag mismatch')
            else:
                raise VTaggedParseError('Not a VReference or VNativeObject')

        VEntity.__init__(self)
        self._v_int_native_obj = obj._v_proxy()
        self._v_tag = tag
        self._v_active = False
Exemplo n.º 2
0
    def decoder(self, obj):
        self.__lock.acquire()
        try:
            if not isinstance(obj, VTagged):
                raise VTaggedParseError('Object must be VTagged')
            value, tags = obj.value, obj.tags
            if not tags:
                raise VTaggedParseUnknown('No tags set on object')
            encoding, etags = VEntity._v_lazy_native(tags[0]), tags[1:]
            if not isinstance(encoding, (int, long) or encoding < -1):
                raise VTaggedParseUnknown()
            if encoding == -1:
                if len(etags) < 2:
                    raise VTaggedParseError()
                name, version = VEntity._v_lazy_native(etags[:2])
                mod_tags = etags[2:]
                try:
                    entry = self.__proxy.decoder_from_name(name, version)
                except VModuleError:
                    raise VTaggedParseUnknown()
                try:
                    return entry.decoder(value, *mod_tags)
                except Exception as e:
                    raise VTaggedParseError(e.args)

            oid_enc_type, oid_enc_len = encoding % 10, encoding // 10
            if oid_enc_type in (0, 1):
                if len(etags) < oid_enc_len:
                    raise VTaggedParseError()
                oid_tags, mod_tags = etags[:oid_enc_len], etags[oid_enc_len:]
                oid_tags = VEntity._v_lazy_native(oid_tags)
                for t in oid_tags:
                    if not isinstance(t, (int, long)) or t < 0:
                        raise VTaggedParseError()
            else:
                return VTaggedParseUnknown()
            if oid_enc_type == 1:
                oid_tags = self.VSE_OID_PREFIX + oid_tags
            oid = VObjectIdentifier(oid_tags)
            try:
                entry = self.__proxy.decoder_from_oid(oid)
            except VModuleError:
                raise VTaggedParseUnknown()
            try:
                return entry.decoder(value, *mod_tags)
            except Exception as e:
                raise VTaggedParseError(e.args)
        finally:
            self.__lock.release()
Exemplo n.º 3
0
    def _v_vse_decoder(cls, value, *tags):
        """Create object from VSE tag data"""
        if tags:
            raise VTaggedParseError('Encoding does not use residual tags')
        value = VEntity._v_lazy_native(value)
        if not isinstance(value, bytes):
            raise VTaggedParseError('Encoding value must be bytes data')

        _nums = []
        _offset = 0
        while value:
            _num, _b_read = netbytes_to_signedint(value)
            if _num is None:
                raise VTaggedParseError('Invalid number encoding')
            _nums.append(_num)
            value = value[_b_read:]
        if len(_nums) % 3 != 0:
            raise VTaggedParseError('Invalid number encoding')
        _vals = []
        for i in xrange(len(_nums) // 3):
            _digits = _nums[3 * i]
            _base = _nums[3 * i + 1]
            _exp = _nums[3 * i + 2]
            _vals.append(VFloat(_digits, _exp, base=_base))

        result = VArrayOfVFloat(_vals)
        return (lambda x: x[0], [result])
Exemplo n.º 4
0
 def __init__(self, dim, data=None, fill=None, lazy=True):
     VLockable.__init__(self)
     if len(dim) < 1:
         raise TypeError('Minimum 1 dimension required')
     for d in dim:
         if d <= 0:
             raise TypeError('Each dimension must be >0')
     self._dim = tuple(dim)
     mul, m = [], 1
     for d in dim:
         mul.append(m)
         m *= d
     _len = m
     self.__mul = tuple(mul)
     if data is None:
         fill = VEntity._v_lazy(fill)
         self._data = [fill] * (_len)
     else:
         if isinstance(data, VTuple):
             self._data = list(e for e in data)
         else:
             if lazy:
                 _lazy = VEntity._v_lazy
                 self._data = self._val_type()(_lazy(e) for e in data)
             else:
                 self._data = self._val_type()(iter(data))
                 for e in self._data:
                     if not isinstance(e, VEntity):
                         raise TypeError('Invalid element type')
         if len(self._data) != _len:
             raise TypeError('Data has incorrect dimensions')
Exemplo n.º 5
0
 def _v_vse_decoder(cls, value, *tags):
     """Returns decoder for :class:`versile.orb.entity.VTagged`."""
     if len(tags) != 2:
         raise VTaggedParseError('Encoding requires 2 residual tags')
     min_arg, max_arg = tags
     min_arg = VEntity._v_lazy_native(min_arg)
     max_arg = VEntity._v_lazy_native(max_arg)
     for arg in (min_arg, max_arg):
         if arg is None:
             continue
         if isinstance(arg, (int, long)) and arg >= 0:
             continue
         raise VTaggedParseError('Limit must be non-negative int or None')
     if min_arg is not None and max_arg is not None and max_arg < min_arg:
         raise VTaggedParseError('Max arguments must be None or > min args')
     if isinstance(value, VObject):
         value = value._v_proxy()
     if not isinstance(value, VProxy):
         raise VTaggedParseError('Encoding value must be object reference')
     return (lambda x: cls(*x), [value, min_arg, max_arg])
Exemplo n.º 6
0
    def __getitem__(self, key):
        """Gets a dictionary value.

        :param key: dictionary key
        :type  key: :class:`versile.orb.entity.VEntity` or lazy-convertible
        :returns:   dictionary value for key
        :rtype:     :class:`versile.orb.entity.VEntity`
        :raises:    :exc:`exceptions.KeyError`

        """
        with self:
            key = VEntity._v_lazy(key)
            return self.__value[key]
Exemplo n.º 7
0
    def _v_obj_from_recv(cls, obj, activate=False):
        """Parses obj, converting VPythonObject to VPythonObject._obj

        Also lazy-native converts from VEntity to native representation.

        """
        t = type(obj)
        if t in (tuple, set, frozenset):
            return t(cls._v_obj_from_recv(e) for e in obj)
        elif isinstance(obj, VNativeObject):
            return obj._obj
        elif isinstance(obj, VBasePython) and activate:
            obj._v_activate()
            return obj
        elif isinstance(obj, VBasePythonException) and activate:
            obj._v_activate()
            obj = VEntity._v_lazy_native(obj)
            return obj
        else:
            try:
                return VEntity._v_lazy_native(obj)
            except:
                return obj
Exemplo n.º 8
0
    def __init__(self, *args):
        if len(args) == 1:
            _dt = args[0]
            if not isinstance(_dt, datetime):
                raise TypeError('Single argument must be datetime object')
            try:
                _dt = _dt.astimezone(self._utc)
            except:
                raise ValueError('Datetime must be TZ aware (have time zone)')
            _conv = VUTCTime._v_converter(_dt)[1][0]
            args = (_conv.days, _conv.secs)

        if len(args) == 2:
            if _pyver == 2:
                _int_types = (int, long)
            else:
                _int_types = (int, )

            days = VEntity._v_lazy_native(args[0])
            secs = VEntity._v_lazy_native(args[1])
            if not isinstance(days, _int_types):
                raise TypeError('Days component must be an int (or long)')
            if not isinstance(secs, _int_types):
                # Later if such types are implemented, check for other
                # structures than VFloat that may be resolved as a number
                if not isinstance(secs, (Decimal, float, VFloat)):
                    raise TypeError('Secs must be integer or floating point')

                if not isinstance(secs, VFloat):
                    # Verify 'secs' is within allowed boundaries
                    if not (0 <= secs < 86402):
                        raise ValueError('Secs outside allowed boundaries')

            self.__days = days
            self.__secs = secs
        else:
            raise ValueError('Illegal number of arguments')
Exemplo n.º 9
0
    def _v_vse_decoder(cls, value, *tags):
        """Create object from VSE tag data"""
        if tags:
            raise VTaggedParseError('Encoding does not use residual tags')
        value = VEntity._v_lazy_native(value)
        if not isinstance(value, bytes):
            raise VTaggedParseError('Encoding value must be bytes data')

        if len(value) % 8 != 0:
            raise VTaggedParseError('Encoding must be multiple of 8 bytes')
        _nums = []
        _offset = 0
        while _offset < len(value):
            _nums.append(struct.unpack_from(b'>d', value, _offset)[0])
            _offset += 8
        result = VArrayOfDouble(_nums)
        return (lambda x: x[0], [result])
Exemplo n.º 10
0
    def _v_vse_decoder(cls, value, *tags):
        """Create object from VSE tag data"""
        if tags:
            raise VTaggedParseError('Encoding does not use residual tags')
        value = VEntity._v_lazy_native(value)
        if not isinstance(value, bytes):
            raise VTaggedParseError('Encoding value must be bytes data')

        _nums = []
        _offset = 0
        while value:
            _num, _b_read = netbytes_to_signedint(value)
            if _num is None:
                raise VTaggedParseError('Invalid number encoding')
            _nums.append(_num)
            value = value[_b_read:]
        result = VArrayOfVInteger(_nums)
        return (lambda x: x[0], [result])
Exemplo n.º 11
0
 def _v_convert_for_send(cls, result):
     """Parse 'result' for sending, into VEntity-compliant format."""
     try:
         return VEntity._v_lazy(result)
     except:
         if isinstance(result, Exception):
             if isinstance(result, VException):
                 return result
             # Try to up-convert local exception types
             args = [cls._v_convert_for_send(e) for e in result.args]
             name = cls._v_python_exc._CONVERSION.get(type(result), None)
             if name:
                 return cls._v_python_exc(name, *args)
             # If this failed, generate a non-standard VPythonException
             rcls = result.__class__
             e_name = '%s.%s' % (rcls.__module__, rcls.__name__)
             return cls._v_python_exc(e_name, *args)
         else:
             return cls(result)
     else:
         return result
Exemplo n.º 12
0
    def _vse_obj_decoder(self, value, *tags):
        if len(tags) != 1 or not isinstance(tags[0], VString):
            raise VTaggedParseError('Invalid residual tag format')
        residual_tag = VEntity._v_lazy_native(tags[0])

        self.__lock.acquire()
        try:
            decoders = self.__handlers.get(residual_tag, None)
        finally:
            self.__lock.release()

        if decoders:
            obj_decoder, exc_decoder = decoders
            decoded = obj_decoder(value)
        else:
            decoded = VNative(value, residual_tag)

        if self.__activates:
            decoded._v_activate()

        return (lambda args: decoded, [])
Exemplo n.º 13
0
    def __setitem__(self, index, value):
        """Sets an element of the array.

        :param index: array index
        :type  index: (int,)
        :param value: element value
        :type  value: :class:`versile.orb.entity.VEntity` or lazy-convertible
        :raises:      :exc:`exceptions.TypeError`\ ,
                      :exc:`exceptions.IndexError`

        """
        with self:
            if len(index) != len(self._dim):
                raise IndexError('Index has incorrect length')
            for i, d in zip(index, self._dim):
                if not 0 <= i < d:
                    raise IndexError('Index out of range')
            if not isinstance(value, VEntity):
                value = VEntity._v_lazy(value)
            pos = 0
            for i, m in zip(index, self.__mul):
                pos += i * m
            self._data[pos] = value
Exemplo n.º 14
0
 def _v_vse_decoder(cls, value, *tags):
     """Create object from VSE tag data"""
     dim = VEntity._v_lazy_native(tags)
     data = value
     _assemble = lambda args: cls(dim, data=args)
     return (_assemble, list(data))
Exemplo n.º 15
0
 def __init__(self, dim, data=None, fill=None, lazy=True):
     VEntity.__init__(self)
     VMultiArray.__init__(self, dim, data, fill, lazy)
Exemplo n.º 16
0
    def _v_vse_decoder(cls, value, *tags):
        """Create object from VSE tag data"""
        if len(tags) != 1:
            raise VTaggedParseError('Encoding requires a single residual tag')
        tag = tags[0]
        if _pyver == 2:
            _itypes = (int, long, VInteger)
        else:
            _itypes = (int, VInteger)
        if not isinstance(tag, _itypes):
            raise VTaggedParseError('Residual tag must be an integer')

        _val = VEntity._v_lazy_native(value)

        if tag == VConcept.TYPE_URL:
            if not isinstance(_val, tuple) or len(_val) != 2:
                raise VTaggedParseError('Value must be an 2-tuple')
            for _tmp in _val:
                if _pyver == 2:
                    if not isinstance(_tmp, unicode):
                        raise VTaggedParseError('Value element must be string')
                else:
                    if not isinstance(_tmp, str):
                        raise VTaggedParseError('Value element must be string')
            _prefix, _postfix = _val

            try:
                _result = VUrlConcept.create(_prefix, _postfix)
            except Exception as e:
                raise VTaggedParseError(e)
            else:
                return (lambda x: _result, [])

        if tag == VConcept.TYPE_EN_WIKIPEDIA:
            if _pyver == 2:
                if not isinstance(_val, unicode):
                    raise VTaggedParseError('Value must be string')
            else:
                if not isinstance(_val, str):
                    raise VTaggedParseError('Value must be string')

            try:
                _result = VEnWikipediaConcept.create(_val)
            except Exception as e:
                raise VTaggedParseError(e)
            else:
                return (lambda x: _result, [])

        if tag == VConcept.TYPE_VP_DEFINED:
            if not isinstance(value, _itypes):
                raise VTaggedParseError('Value must be an integer')
            _val = VEntity._v_lazy_native(value)

            try:
                _result = VPlatformConcept.create(_val)
            except Exception as e:
                raise VTaggedParseError(e)
            else:
                return (lambda x: _result, [])

        raise VTaggedParseError('Invalid residual tag value')