Example #1
0
    def _set(self, instance, value, **kw):
        """Set the value of the field
        """
        logger.debug("ATFieldManager::set: value=%r" % value)

        # check field permission
        if not self.field.checkPermission("write", instance):
            raise Unauthorized(
                "You are not allowed to write the field {}".format(self.name))

        # check if field is writable
        if not self.field.writeable(instance):
            raise Unauthorized("Field {} is read only.".format(self.name))

        # id fields take only strings
        if self.name == "id":
            value = str(value)

        # get the field mutator
        mutator = self.field.getMutator(instance)

        # Inspect function and apply *args and **kwargs if possible.
        mapply(mutator, value, **kw)

        return True
Example #2
0
    def setDefaults(self, instance):
        """Only call during object initialization. Sets fields to
        schema defaults
        """
        # TODO think about layout/vs dyn defaults
        for field in self.values():
            if field.getName().lower() == 'id':
                continue
            if field.type == "reference":
                continue

            # always set defaults on writable fields
            mutator = field.getMutator(instance)
            if mutator is None:
                continue
            default = field.getDefault(instance)

            args = (default, )
            kw = {'field': field.__name__, '_initializing_': True}
            if shasattr(field, 'default_content_type'):
                # specify a mimetype if the mutator takes a
                # mimetype argument
                # if the schema supplies a default, we honour that,
                # otherwise we use the site property
                default_content_type = field.default_content_type
                if default_content_type is None:
                    default_content_type = getDefaultContentType(instance)
                kw['mimetype'] = default_content_type
            mapply(mutator, *args, **kw)
Example #3
0
    def _migrateSetValue(self, name, value, old_schema=None, **kw):
        """Try to set an object value using a variety of methods."""
        schema = self.Schema()
        # Migrate pre-AT 1.3 schemas.
        schema = fixSchema(schema)
        field = schema.get(name, None)
        # Try using the field's mutator
        if field:
            mutator = field.getMutator(self)
            if mutator is not None:
                try:
                    args = [value,]
                    mapply(mutator, *args, **kw)
                    return

                except (ConflictError, KeyboardInterrupt):
                    raise
                except:
                    log_exc()
        else:
            # Try setting an existing attribute
            if shasattr(self, name):
                setattr(self, name, value)
                return
        raise ValueError, 'name = %s, value = %s' % (name, value)
    def _set(self, instance, value, **kw):
        """Set the value of the field
        """
        logger.debug("ATFieldManager::set: value=%r" % value)

        # check field permission
        if not self.field.checkPermission("write", instance):
            raise Unauthorized("You are not allowed to write the field {}"
                               .format(self.name))

        # check if field is writable
        if not self.field.writeable(instance):
            raise Unauthorized("Field {} is read only."
                               .format(self.name))

        # id fields take only strings
        if self.name == "id":
            value = str(value)

        # get the field mutator
        mutator = self.field.getMutator(instance)

        # Inspect function and apply *args and **kwargs if possible.
        mapply(mutator, value, **kw)

        return True
Example #5
0
 def demarshall(self, instance, data, file=None, **kwargs):
     p = instance.getPrimaryField()
     # XXX Hardcoding field types is bad. :(
     if isinstance(p, (FileField, TextField)) and file:
         data = file
     mutator = p.getMutator(instance)
     mapply(mutator, data, **kwargs)
Example #6
0
    def setDefaults(self, instance):
        """Only call during object initialization. Sets fields to
        schema defaults
        """
        # TODO think about layout/vs dyn defaults
        for field in self.values():
            if field.getName().lower() == 'id':
                continue
            if field.type == "reference":
                continue

            # always set defaults on writable fields
            mutator = field.getMutator(instance)
            if mutator is None:
                continue
            default = field.getDefault(instance)

            args = (default,)
            kw = {'field': field.__name__,
                  '_initializing_': True}
            if shasattr(field, 'default_content_type'):
                # specify a mimetype if the mutator takes a
                # mimetype argument
                # if the schema supplies a default, we honour that,
                # otherwise we use the site property
                default_content_type = field.default_content_type
                if default_content_type is None:
                    default_content_type = getDefaultContentType(instance)
                kw['mimetype'] = default_content_type
            mapply(mutator, *args, **kw)
Example #7
0
    def set_field(self, obj, name, value):
        """Set the value

        :returns: List of updated/changed objects
        """

        # set of updated objects
        updated_objects = set()

        # lookup the schema field
        field = self.lookup_schema_field(obj, name)

        # field exists, set it with the value
        if field:

            # Check the permission of the field
            if not self.is_field_writeable(obj, field):
                logger.error("Field '{}' not writeable!".format(name))
                return []

            # get the field mutator (works only for AT content types)
            if hasattr(field, "getMutator"):
                mutator = field.getMutator(obj)
                mapply(mutator, value)
            else:
                # Set the value on the field directly
                field.set(obj, value)

            updated_objects.add(obj)

        # check if the object is an analysis and has an interim
        if self.is_analysis(obj):

            interims = obj.getInterimFields()
            interim_keys = map(lambda i: i.get("keyword"), interims)
            interims_writable = self.is_field_writeable(obj, "InterimFields")
            if name in interim_keys and interims_writable:
                for interim in interims:
                    if interim.get("keyword") == name:
                        interim["value"] = value
                # set the new interim fields
                obj.setInterimFields(interims)

            # recalculate dependent results for result and interim fields
            if name == "Result" or name in interim_keys:
                updated_objects.add(obj)
                updated_objects.update(self.recalculate_results(obj))

        # unify the list of updated objects
        updated_objects = list(updated_objects)

        # reindex the objects
        map(lambda obj: obj.reindexObject(), updated_objects)

        # notify that the objects were modified
        map(modified, updated_objects)

        return updated_objects
Example #8
0
def setDefaults(self, instance):
    """Only call during object initialization, this function sets fields
    to schema defaults.  It's adapted from the original to support
    IAcquireFieldDefaults adapters.  If IAcquireFieldDefaults adapter
    does not find a suitable field, or that field's value is Falseish,
    this function will not continue with the normal default machinery.
    """
    for field in self.values():

        # ## bika addition: we fire adapters for IAcquireFieldDefaults.
        # If IAcquireFieldDefaults returns None, this signifies "ignore" return.
        # First adapter found with non-None result, wins.
        value = None
        if shasattr(field, 'acquire'):
            adapters = {}
            for adapter in getAdapters((instance,), IAcquireFieldDefaults):
                sort_val = getattr(adapter[1], 'sort', 1000)
                if sort_val not in adapters:
                    adapters[sort_val] = []
                adapters[sort_val].append(adapter)
            if adapters:
                keys = sorted(adapters.keys())
                keys.reverse()
                adapter = adapters[keys[0]]
                _value = adapter[0][1](field)
                if _value is not None:
                    value = _value

        if field.getName().lower() == 'id':
            continue

        # If our adapter reflects a value for a reference field, it will
        # be permitted.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default,)
        kw = {'field': field.__name__,
              '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a mimetype argument if
            # the schema supplies a default, we honour that, otherwise we use
            # the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
Example #9
0
def setDefaults(self, instance):
    """Only call during object initialization, this function sets fields
    to schema defaults.  It's adapted from the original to support
    IAcquireFieldDefaults adapters.  If IAcquireFieldDefaults adapter
    does not find a suitable field, or that field's value is Falseish,
    this function will not continue with the normal default machinery.
    """
    for field in self.values():

        # ## bika addition: we fire adapters for IAcquireFieldDefaults.
        # If IAcquireFieldDefaults returns None, this signifies "ignore" return.
        # First adapter found with non-None result, wins.
        value = None
        if shasattr(field, 'acquire'):
            adapters = {}
            for adapter in getAdapters((instance, ), IAcquireFieldDefaults):
                sort_val = getattr(adapter[1], 'sort', 1000)
                if sort_val not in adapters:
                    adapters[sort_val] = []
                adapters[sort_val].append(adapter)
            if adapters:
                keys = sorted(adapters.keys())
                keys.reverse()
                adapter = adapters[keys[0]]
                _value = adapter[0][1](field)
                if _value is not None:
                    value = _value

        if field.getName().lower() == 'id':
            continue

        # If our adapter reflects a value for a reference field, it will
        # be permitted.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default, )
        kw = {'field': field.__name__, '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a mimetype argument if
            # the schema supplies a default, we honour that, otherwise we use
            # the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
def fromFile(obj, stream):
    REQUEST = obj.REQUEST
    RESPONSE = REQUEST.RESPONSE
    marshaller = CalendarMarshaller()
    args = [obj, '']
    items = []
    kwargs = {'file':stream,
              'context':obj,
              'items': items,
              'REQUEST':REQUEST,
              'RESPONSE':RESPONSE}
    mapply(marshaller.demarshall, *args, **kwargs)
    return items
def fromFile(obj, stream):
    REQUEST = obj.REQUEST
    RESPONSE = REQUEST.RESPONSE
    marshaller = CalendarMarshaller()
    args = [obj, '']
    items = []
    kwargs = {
        'file': stream,
        'context': obj,
        'items': items,
        'REQUEST': REQUEST,
        'RESPONSE': RESPONSE
    }
    mapply(marshaller.demarshall, *args, **kwargs)
    return items
 def fromFile(self, stream):
     """ Import events from a file into this calendar
     """
     REQUEST = self.REQUEST
     RESPONSE = REQUEST.RESPONSE
     marshaller = self.Schema().getLayerImpl('marshall')
     args = [self, '']
     items = []
     kwargs = {'file':stream,
               'context':self,
               'items': items,
               'REQUEST':REQUEST,
               'RESPONSE':RESPONSE}
     mapply(marshaller.demarshall, *args, **kwargs)
     return items
Example #13
0
 def getArrayJS(self, field, context):
     method = getattr(context, field.vocabulary, None)
     if method and callable(method):
         args = []
         kw = {'content_instance': context, 'field': self, 'extended': True}
         value = mapply(method, *args, **kw)
     return simplejson.dumps(value)
Example #14
0
    def __getitem__(self, key):
        """Overloads the object's item access.
        """
        # Don't allow key access to hidden attributes
        if key.startswith('_'):
            raise Unauthorized, key

        schema = self.Schema()
        keys = schema.keys()

        if key not in keys and not key.startswith('_'):
            # XXX Fix this in AT 1.4
            value= getattr(aq_inner(self).aq_explicit, key, _marker) or \
                   getattr(aq_parent(aq_inner(self)).aq_explicit, key, _marker)
            if value is _marker:
                raise KeyError, key
            else:
                return value

        field = schema[key]
        accessor = field.getEditAccessor(self)
        if not accessor:
            accessor = field.getAccessor(self)

        # This is the access mode used by external editor. We need the
        # handling provided by BaseUnit when its available
        kw = {'raw':1, 'field': field.__name__}
        value = mapply(accessor, **kw)
        return value
Example #15
0
    def __getitem__(self, key):
        """Overloads the object's item access.
        """
        # Don't allow key access to hidden attributes
        if key.startswith('_'):
            raise Unauthorized, key

        schema = self.Schema()
        keys = schema.keys()

        if key not in keys and not key.startswith('_'):
            # XXX Fix this in AT 1.4
            value = getattr(aq_inner(self).aq_explicit, key, _marker) or \
                getattr(aq_parent(aq_inner(self)).aq_explicit, key, _marker)
            if value is _marker:
                raise KeyError, key
            else:
                return value

        field = schema[key]
        accessor = field.getEditAccessor(self)
        if not accessor:
            accessor = field.getAccessor(self)

        # This is the access mode used by external editor. We need the
        # handling provided by BaseUnit when its available
        kw = {'raw': 1, 'field': field.__name__}
        value = mapply(accessor, **kw)
        return value
Example #16
0
def setDefaults(self, instance):
    """Only call during object initialization. Sets fields to
    schema defaults
    """
    # # TODO think about layout/vs dyn defaults
    for field in self.values():

        value = None

        # if analysis request, set sampling date to default to today
        if field.getName().lower() == 'samplingdate' \
                and instance.portal_type == 'AnalysisRequest':
            now = DateTime().strftime("%Y-%m-%d %H:%M")
            value = now

        # From here, the rest of the body of the original function:
        # Products.Archetypes.Schema.BasicSchema#setDefaults

        if field.getName().lower() == 'id':
            continue
        # The original version skipped all reference fields.  I obviously do
        # find some use in defining their defaults anyway, so if our adapter
        # reflects a value for a reference field, I will allow it.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default,)
        kw = {'field': field.__name__,
              '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a
            # mimetype argument
            # if the schema supplies a default, we honour that,
            # otherwise we use the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
Example #17
0
 def fromFile(self, stream):
     """ Import events from a file into this calendar
     """
     REQUEST = self.REQUEST
     RESPONSE = REQUEST.RESPONSE
     marshaller = self.Schema().getLayerImpl('marshall')
     args = [self, '']
     items = []
     kwargs = {
         'file': stream,
         'context': self,
         'items': items,
         'REQUEST': REQUEST,
         'RESPONSE': RESPONSE
     }
     mapply(marshaller.demarshall, *args, **kwargs)
     return items
 def _set(self, field, value, **kw):
     """ set the raw value of the field
     """
     logger.debug("ATDataManager::set: field=%r, value=%r", field, value)
     # get the field mutator
     mutator = field.getMutator(self.context)
     # Inspect function and apply positional and keyword arguments if
     # possible.
     return mapply(mutator, value, **kw)
Example #19
0
 def _set(self, field, value, **kw):
     """ set the raw value of the field
     """
     logger.debug("ATDataManager::set: field=%r, value=%r", field, value)
     # get the field mutator
     mutator = field.getMutator(self.context)
     # Inspect function and apply positional and keyword arguments if
     # possible.
     return mapply(mutator, value, **kw)
 def getArrayJS(self, field, context): 
     method = getattr(context, field.vocabulary, None)                                                                                                                  
     if method and callable(method):
         args = []                                                                                                                                                        
         kw = { 'content_instance' : context,                                                                                                                         
                 'field' : self,
                 'extended': True 
         }                                                                                                                                            
         value = mapply(method, *args, **kw)           
     return simplejson.dumps ( value )
 def _processForm(self, data=1, metadata=None, REQUEST=None, values=None):
     """BaseObject._processForm override 
       this patch is done to make processForm possible by fieldset
       when IMultiPageSchema is not implemented
     """
 
     request = REQUEST or self.REQUEST
     if values:
         form = values
     else:
         form = request.form
           
     fieldset = form.get('fieldset', None)
     if fieldset is None :
         ArticleMixin._processForm(self, data=data, metadata=metadata,
                                   REQUEST=REQUEST, values=values)
     else :                  
         schema = self.Schema()
         schemata = self.Schemata()
         fields = []
 
         fields = schemata[fieldset].fields()                
 
         form_keys = form.keys()
 
         for field in fields:
 
             if not field.writeable(self):
 
                 continue
 
             widget = field.widget
             result = widget.process_form(self, field, form,
                                          empty_marker=_marker)
             if result is _marker or result is None: continue
 
             # Set things by calling the mutator
             mutator = field.getMutator(self)
             __traceback_info__ = (self, field, mutator)
             result[1]['field'] = field.__name__
             mapply(mutator, result[0], **result[1])
 
         self.reindexObject()        
    def importCalendar(self, stream, dest=None, kw_map=None, do_action=False):	
        from Products.Calendaring.marshaller import CalendarMarshaller
        mt = getToolByName(self, 'portal_membership')
        if mt.isAnonymousUser():
            raise Unauthorized
        if dest is None:
            dest = self.getDestination()
        marshaller = CalendarMarshaller()

        REQUEST = self.REQUEST
        RESPONSE = REQUEST.RESPONSE
        args = [dest, '']
        items = []
        kwargs = {'file':stream,
                  'context':self,
                  'items': items,
		  'do_action':False,
                  'REQUEST':REQUEST,
                  'RESPONSE':RESPONSE}
        mapply(marshaller.demarshall, *args, **kwargs)	
        return items
Example #23
0
    def importCalendar(self, stream, dest=None, kw_map=None, do_action=False):
        from Products.Calendaring.marshaller import CalendarMarshaller
        mt = getToolByName(self, 'portal_membership')
        if mt.isAnonymousUser():
            raise Unauthorized
        if dest is None:
            dest = self.getDestination()
        marshaller = CalendarMarshaller()

        REQUEST = self.REQUEST
        RESPONSE = REQUEST.RESPONSE
        args = [dest, '']
        items = []
        kwargs = {
            'file': stream,
            'context': self,
            'items': items,
            'do_action': False,
            'REQUEST': REQUEST,
            'RESPONSE': RESPONSE
        }
        mapply(marshaller.demarshall, *args, **kwargs)
        return items
Example #24
0
    def marshall(self, instance, **kwargs):
        p = instance.getPrimaryField()
        body = p and instance[p.getName()] or ''
        pname = p and p.getName() or None
        content_type = length = None
        # Gather/Guess content type
        if IBaseUnit.providedBy(body):
            content_type = str(body.getContentType())
            body = body.getRaw()
        else:
            if p and hasattr(p, 'getContentType'):
                content_type = p.getContentType(instance) or 'text/plain'
            else:
                content_type = body and guess_content_type(
                    body) or 'text/plain'

        headers = []
        fields = [
            f for f in instance.Schema().fields() if f.getName() != pname
        ]

        # Include the internal version of IUUID(instance). We're setting this
        # value in the same class, so accessing it directly here saves a
        # Component Registry lookup for every object being exported
        if hasattr(aq_base(instance), UUID_ATTR):
            # Non-referencable content isn't exportable by default, but we should
            # shouldn't include the uuid if it's not there.
            headers.append(('UID', getattr(aq_base(instance), UUID_ATTR,
                                           None)))

        for field in fields:
            if field.type in ('file', 'image', 'object'):
                continue
            accessor = field.getEditAccessor(instance)
            if not accessor:
                continue
            kw = {'raw': 1, 'field': field.__name__}
            value = mapply(accessor, **kw)
            if type(value) in [ListType, TupleType]:
                value = '\n'.join([str(v) for v in value])
            headers.append((field.getName(), str(value)))

        headers.append(('Content-Type', content_type or 'text/plain'))

        header = formatRFC822Headers(headers)
        data = '%s\n\n%s' % (header, body)
        length = len(data)

        return (content_type, length, data)
Example #25
0
 def _migrateSetValue(self, name, value, old_schema=None, **kw):
     """Try to set an object value using a variety of methods."""
     schema = self.Schema()
     # Migrate pre-AT 1.3 schemas.
     schema = fixSchema(schema)
     field = schema.get(name, None)
     # Try using the field's mutator
     if field:
         mutator = field.getMutator(self)
         if mutator is not None:
             try:
                 args = [value]
                 mapply(mutator, *args, **kw)
                 return
             except (ConflictError, KeyboardInterrupt):
                 raise
             except:
                 log_exc()
     else:
         # Try setting an existing attribute
         if shasattr(self, name):
             setattr(self, name, value)
             return
     raise ValueError, 'name = %s, value = %s' % (name, value)
Example #26
0
    def marshall(self, instance, **kwargs):
        p = instance.getPrimaryField()
        body = p and instance[p.getName()] or ''
        pname = p and p.getName() or None
        content_type = length = None
        # Gather/Guess content type
        if IBaseUnit.providedBy(body):
            content_type = str(body.getContentType())
            body = body.getRaw()
        else:
            if p and hasattr(p, 'getContentType'):
                content_type = p.getContentType(instance) or 'text/plain'
            else:
                content_type = body and guess_content_type(body) or 'text/plain'

        headers = []
        fields = [f for f in instance.Schema().fields()
                  if f.getName() != pname]
        
        # Include the internal version of IUUID(instance). We're setting this
        # value in the same class, so accessing it directly here saves a
        # Component Registry lookup for every object being exported
        if hasattr(aq_base(instance), UUID_ATTR):
            # Non-referencable content isn't exportable by default, but we should
            # shouldn't include the uuid if it's not there.
            headers.append(('UID', getattr(aq_base(instance), UUID_ATTR, None)))
        
        for field in fields:
            if field.type in ('file', 'image', 'object'):
                continue
            accessor = field.getEditAccessor(instance)
            if not accessor:
                continue
            kw = {'raw': 1, 'field': field.__name__}
            value = mapply(accessor, **kw)
            if type(value) in [ListType, TupleType]:
                value = '\n'.join([str(v) for v in value])
            headers.append((field.getName(), str(value)))

        headers.append(('Content-Type', content_type or 'text/plain'))

        header = formatRFC822Headers(headers)
        data = '%s\n\n%s' % (header, body)
        length = len(data)

        return (content_type, length, data)
Example #27
0
 def delegate(self, method, obj, data=None, file=None, **kw):
     if file is not None:
         kw['file'] = file
     __traceback_info__ = (method, obj, kw)
     context = getContext(obj, kw.get('REQUEST'))
     if context is not obj:
         # If the object is being created by means of a PUT
         # then it has no context, and some of the stuff
         # we are doing here may require a context.
         # Wrapping it in an ImplicitAcquisitionWrapper should
         # be safe as long as nothing tries to persist
         # a reference to the wrapped object.
         obj = ImplicitAcquisitionWrapper(obj, context)
     tool = getToolByName(obj, TOOL_ID, None)
     components = None
     if tool is not None:
         info = kw.copy()
         info['data'] = data
         info['mode'] = method
         components = tool.getMarshallersFor(obj, **info)
     else:
         # Couldn't find a context to get
         # hold of the tool or the tool is not installed.
         logger.log(
             logging.DEBUG, 'Could not find the marshaller tool. '
             'It might not be installed or you might not '
             'be providing enough context to find it.')
     # We just use the first component, if one is returned.
     if components:
         marshaller = getComponent(components[0])
     else:
         # If no default marshaller was provided then we complain.
         if self.fallback is None:
             raise MarshallingException(
                 "Couldn't get a marshaller for %r, %r" % (obj, kw))
         # Otherwise, use the default marshaller provided. Note it
         # must be an instance, not a factory.
         marshaller = self.fallback
     __traceback_info__ = (marshaller, method, obj, kw)
     args = (obj, )
     if method == 'demarshall':
         args += (data, )
     method = getattr(marshaller, method)
     return mapply(method, *args, **kw)
Example #28
0
 def delegate(self, method, obj, data=None, file=None, **kw):
     if file is not None:
         kw['file'] = file
     __traceback_info__ = (method, obj, kw)
     context = getContext(obj, kw.get('REQUEST'))
     if context is not obj:
         # If the object is being created by means of a PUT
         # then it has no context, and some of the stuff
         # we are doing here may require a context.
         # Wrapping it in an ImplicitAcquisitionWrapper should
         # be safe as long as nothing tries to persist
         # a reference to the wrapped object.
         obj = ImplicitAcquisitionWrapper(obj, context)
     tool = getToolByName(obj, TOOL_ID, None)
     components = None
     if tool is not None:
         info = kw.copy()
         info['data'] = data
         info['mode'] = method
         components = tool.getMarshallersFor(obj, **info)
     else:
         # Couldn't find a context to get
         # hold of the tool or the tool is not installed.
         logger.log(logging.DEBUG, 'Could not find the marshaller tool. '
             'It might not be installed or you might not '
             'be providing enough context to find it.')
     # We just use the first component, if one is returned.
     if components:
         marshaller = getComponent(components[0])
     else:
         # If no default marshaller was provided then we complain.
         if self.fallback is None:
             raise MarshallingException(
                 "Couldn't get a marshaller for %r, %r" % (obj, kw))
         # Otherwise, use the default marshaller provided. Note it
         # must be an instance, not a factory.
         marshaller = self.fallback
     __traceback_info__ = (marshaller, method, obj, kw)
     args = (obj,)
     if method == 'demarshall':
         args += (data,)
     method = getattr(marshaller, method)
     return mapply(method, *args, **kw)
Example #29
0
    def marshall(self, instance, **kwargs):
        p = instance.getPrimaryField()
        body = p and instance[p.getName()] or ''
        pname = p and p.getName() or None
        content_type = length = None
        # Gather/Guess content type
        if IBaseUnit.providedBy(body):
            content_type = str(body.getContentType())
            body = body.getRaw()
        else:
            if p and hasattr(p, 'getContentType'):
                content_type = p.getContentType(instance) or 'text/plain'
            else:
                content_type = body and guess_content_type(
                    body) or 'text/plain'

        headers = []
        fields = [
            f for f in instance.Schema().fields() if f.getName() != pname
        ]
        for field in fields:
            if field.type in ('file', 'image', 'object'):
                continue
            accessor = field.getEditAccessor(instance)
            if not accessor:
                continue
            kw = {'raw': 1, 'field': field.__name__}
            value = mapply(accessor, **kw)
            if type(value) in [ListType, TupleType]:
                value = '\n'.join([str(v) for v in value])
            headers.append((field.getName(), str(value)))

        headers.append(('Content-Type', content_type or 'text/plain'))

        header = formatRFC822Headers(headers)
        data = '%s\n\n%s' % (header, body)
        length = len(data)

        return (content_type, length, data)
Example #30
0
    def marshall(self, instance, **kwargs):
        p = instance.getPrimaryField()
        body = p and instance[p.getName()] or ''
        pname = p and p.getName() or None
        content_type = length = None
        # Gather/Guess content type
        if IBaseUnit.providedBy(body):
            content_type = str(body.getContentType())
            body = body.getRaw()
        else:
            if p and hasattr(p, 'getContentType'):
                content_type = p.getContentType(instance) or 'text/plain'
            else:
                content_type = body and guess_content_type(
                    body) or 'text/plain'

        headers = []
        fields = [f for f in instance.Schema().fields()
                  if f.getName() != pname]
        for field in fields:
            if field.type in ('file', 'image', 'object'):
                continue
            accessor = field.getEditAccessor(instance)
            if not accessor:
                continue
            kw = {'raw': 1, 'field': field.__name__}
            value = mapply(accessor, **kw)
            if type(value) in [ListType, TupleType]:
                value = '\n'.join([str(v) for v in value])
            headers.append((field.getName(), str(value)))

        headers.append(('Content-Type', content_type or 'text/plain'))

        header = formatRFC822Headers(headers)
        data = '%s\n\n%s' % (header, body)
        length = len(data)

        return (content_type, length, data)
Example #31
0
    def marshall(self, instance, **kwargs):
        p = instance.getPrimaryField()
        body = p and instance[p.getName()] or ""
        pname = p and p.getName() or None
        content_type = length = None
        # Gather/Guess content type
        if IBaseUnit.isImplementedBy(body):
            content_type = str(body.getContentType())
            body = body.getRaw()
        else:
            if p and hasattr(p, "getContentType"):
                content_type = p.getContentType(instance) or "text/plain"
            else:
                content_type = body and guess_content_type(body) or "text/plain"

        headers = []
        fields = [f for f in instance.Schema().fields() if f.getName() != pname]
        for field in fields:
            if field.type in ("file", "image", "object"):
                continue
            accessor = field.getEditAccessor(instance)
            if not accessor:
                continue
            kw = {"raw": 1, "field": field.__name__}
            value = mapply(accessor, **kw)
            if type(value) in [ListType, TupleType]:
                value = "\n".join([str(v) for v in value])
            headers.append((field.getName(), str(value)))

        headers.append(("Content-Type", content_type or "text/plain"))

        header = formatRFC822Headers(headers)
        data = "%s\n\n%s" % (header, body)
        length = len(data)

        return (content_type, length, data)
Example #32
0
    def _processForm(self, data=1, metadata=None, REQUEST=None, values=None):
        request = REQUEST or self.REQUEST
        if values:
            form = values
        else:
            form = request.form
        fieldset = form.get('fieldset', None)
        schema = self.Schema()
        schemata = self.Schemata()
        fields = []

        if not IMultiPageSchema.providedBy(self):
            fields = schema.fields()
        elif fieldset is not None:
            fields = schemata[fieldset].fields()
        else:
            if data: fields += schema.filterFields(isMetadata=0)
            if metadata: fields += schema.filterFields(isMetadata=1)

        form_keys = form.keys()

        for field in fields:
            ## Delegate to the widget for processing of the form
            ## element.  This means that if the widget needs _n_
            ## fields under a naming convention it can handle this
            ## internally.  The calling API is process_form(instance,
            ## field, form) where instance should rarely be needed,
            ## field is the field object and form is the dict. of
            ## kv_pairs from the REQUEST
            ##
            ## The product of the widgets processing should be:
            ##   (value, **kwargs) which will be passed to the mutator
            ##   or None which will simply pass

            if not field.writeable(self):
                # If the field has no 'w' in mode, or the user doesn't
                # have the required permission, or the mutator doesn't
                # exist just bail out.
                continue

            try:
                # Pass validating=False to inform the widget that we
                # aren't in the validation phase, IOW, the returned
                # data will be forwarded to the storage
                result = field.widget.process_form(self, field, form,
                                                   empty_marker=_marker,
                                                   validating=False)
            except TypeError:
                # Support for old-style process_form methods
                result = field.widget.process_form(self, field, form,
                                                   empty_marker=_marker)

            if result is _marker or result is None:
                continue

            # Set things by calling the mutator
            mutator = field.getMutator(self)
            __traceback_info__ = (self, field, mutator)
            result[1]['field'] = field.__name__
            mapply(mutator, result[0], **result[1])

        self.reindexObject()
def PUT(self, REQUEST=None, RESPONSE=None):
    """ HTTP PUT handler with marshalling support
    """
    if not REQUEST:
        REQUEST = self.REQUEST
    if not RESPONSE:
        RESPONSE = REQUEST.RESPONSE
    if not self.Schema().hasLayer('marshall'):
        RESPONSE.setStatus(501)  # Not implemented
        return RESPONSE

    self.dav__init(REQUEST, RESPONSE)
    collection_check(self)

    self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
    is_new_object = self.checkCreationFlag()

    file = REQUEST.get('BODYFILE', _marker)
    if file is _marker:
        data = REQUEST.get('BODY', _marker)
        if data is _marker:
            raise AttributeError, 'REQUEST neither has a BODY nor a BODYFILE'
    else:
        data = ''
        file.seek(0)

    mimetype = REQUEST.get_header('content-type', None)
    # mimetype, if coming from request can be like:
    # text/plain; charset='utf-8'
    #
    # XXX we should really parse the extra params and pass them on as
    # keyword arguments.
    if mimetype is not None:
        mimetype = str(mimetype).split(';')[0].strip()

    filename = posixpath.basename(REQUEST.get('PATH_INFO', self.getId()))
    # XXX remove after we are using global services
    # use the request to find an object in the traversal hierachy that is
    # able to acquire a mimetypes_registry instance
    # This is a hack to avoid the acquisition problem on FTP/WebDAV object
    # creation
    parents = (self,) + tuple(REQUEST.get('PARENTS', ()))
    context = None
    for parent in parents:
        if getToolByName(parent, 'mimetypes_registry', None) is not None:
            context = parent
            break

    # Marshall the data
    marshaller = self.Schema().getLayerImpl('marshall')

    args = [self, data]
    kwargs = {'file': file,
              'context': context,
              'mimetype': mimetype,
              'filename': filename,
              'REQUEST': REQUEST,
              'RESPONSE': RESPONSE}
    ddata = mapply(marshaller.demarshall, *args, **kwargs)

    if (shasattr(self, 'demarshall_hook') and self.demarshall_hook):
        self.demarshall_hook(ddata)
    self.manage_afterPUT(data, marshall_data=ddata, **kwargs)
    self.reindexObject()
    self.unmarkCreationFlag()

    if is_new_object:
        event.notify(WebDAVObjectInitializedEvent(self))
    else:
        event.notify(WebDAVObjectEditedEvent(self))

    RESPONSE.setStatus(204)
    return RESPONSE
Example #34
0
    def simpleProcessForm(self, data=1, metadata=0, REQUEST=None, values=None):
        """Processes the schema looking for data in the form.
        """

        # customized to process a single field instead of multiple fields

        is_new_object = self.checkCreationFlag()

        request = REQUEST or self.REQUEST
        _marker = []
        if values:
            form = values
        else:
            form = request.form

        fieldname = form.get('specific_field')
        if not fieldname:
            raise ValueError("Please provide a specific field")

        field = ISchema(self)[fieldname]
        result = field.widget.process_form(self, field, form,
                                           empty_marker=_marker)
        try:
            # Pass validating=False to inform the widget that we
            # aren't in the validation phase, IOW, the returned
            # data will be forwarded to the storage
            result = field.widget.process_form(self, field, form,
                                               empty_marker=_marker,
                                               validating=False)
        except TypeError:
            # Support for old-style process_form methods
            result = field.widget.process_form(self, field, form,
                                               empty_marker=_marker)

        # Set things by calling the mutator
        mutator = field.getMutator(self)
        # __traceback_info__ = (self, field, mutator) #was this line used?
        result[1]['field'] = field.__name__
        mapply(mutator, result[0], **result[1])

        self.reindexObject()

        self.unmarkCreationFlag()
        # NOTE: at the moment, this is not very elegant
        # the problem is that the objects, when are editing
        # in a composite manner with the aggregated edit view,
        # will change their ids after the first save. For example
        # when editing the title for a Specification, it will
        # change its id. This means that all the URLs that are
        # already on the page (for example adding a PolicyQuestion)
        # will be invalid. To solve this particular case we make
        # the page reload after editing the Title. In all other cases
        # we want to either skip this behaviour or make those objects
        # have their _at_rename_after_creation set to False
        if self._at_rename_after_creation and is_new_object \
                and fieldname == 'title':
            self._renameAfterCreation(check_auto_id=True)

        # Post create/edit hooks
        if is_new_object:
            self.at_post_create_script()
            event.notify(ObjectAddedEvent(self))
            event.notify(ObjectInitializedEvent(self))
        else:
            self.at_post_edit_script()
            event.notify(ObjectEditedEvent(self))

        return
Example #35
0
def setMetadataMap(ob, metadata):
    """ sets a simple map with metadata on the current context.
        we also do some conversions for old metadata ini files.
    """
    _marker = []
    compatibility = {
        'NACE': 'nace',
        'keywords': 'subject',
    }
    for comp in compatibility.keys():
        if comp in metadata:
            metadata[compatibility[comp]] = metadata[comp]
            del metadata[comp]

    # we dont want to set the language explicitly
    if 'language' in metadata:
        del metadata['language']

    # convert old MTSubject
    if 'MTSubject' in metadata:
        newmt = []
        mt = metadata['MTSubject']
        for m in mt:
            newmt.append(os.path.basename(str(m)))
        metadata['multilingual_thesaurus'] = newmt
        del metadata['MTSubject']

    # convert the old country path notation to ISOCode notation
    if 'Country' in metadata:
        c = metadata['Country']
        newc = []
        for C in c:
            elems = C.split("/")
            if len(elems) < 2:
                continue
            elif len(elems) == 2:
                newc.append('EU')
            else:
                if str(elems[2]) == 'MS':
                    newc.append('EU')
                else:
                    newc.append(str(elems[2]))
        metadata['country'] = newc
        del metadata['Country']

    for key in metadata:

        field = ob.getField(key)
        if field is None:
            continue

        result = field.widget.process_form(ob,
                                           field,
                                           metadata,
                                           empty_marker=_marker,
                                           validating=False)
        if result is _marker or result is None:
            continue

        mutator = field.getMutator(ob)
        __traceback_info__ = (ob, field, mutator)
        result[1]['field'] = field.__name__
        mapply(mutator, result[0], **result[1])

    ob.reindexObject()
Example #36
0
def patched_processForm(self,
                        data=1,
                        metadata=None,
                        REQUEST=None,
                        values=None):
    request = REQUEST or self.REQUEST
    if values:
        form = values
    else:
        form = request.form
    fieldset = form.get('fieldset', None)
    schema = self.Schema()
    schemata = self.Schemata()
    fields = []

    if MULTI_PAGE and not IMultiPageSchema.providedBy(self):
        fields = schema.fields()
    elif fieldset is not None:
        fields = schemata[fieldset].fields()
    else:
        if data:
            fields += schema.filterFields(isMetadata=0)
        if metadata:
            fields += schema.filterFields(isMetadata=1)

    form_keys = form.keys()

    for field in fields:
        ## Delegate to the widget for processing of the form
        ## element.  This means that if the widget needs _n_
        ## fields under a naming convention it can handle this
        ## internally.  The calling API is process_form(instance,
        ## field, form) where instance should rarely be needed,
        ## field is the field object and form is the dict. of
        ## kv_pairs from the REQUEST
        ##
        ## The product of the widgets processing should be:
        ##   (value, **kwargs) which will be passed to the mutator
        ##   or None which will simply pass

        if not field.writeable(self):
            # If the field has no 'w' in mode, or the user doesn't
            # have the required permission, or the mutator doesn't
            # exist just bail out.
            continue

        try:
            # Pass validating=False to inform the widget that we
            # aren't in the validation phase, IOW, the returned
            # data will be forwarded to the storage
            result = field.widget.process_form(self,
                                               field,
                                               form,
                                               empty_marker=_marker,
                                               validating=False)
        except TypeError:
            # Support for old-style process_form methods
            result = field.widget.process_form(self,
                                               field,
                                               form,
                                               empty_marker=_marker)

        if result is _marker or result is None:
            continue

        # Set things by calling the mutator
        mutator = field.getMutator(self)
        __traceback_info__ = (self, field, mutator)
        result[1]['field'] = field.__name__
        mapply(mutator, result[0], **result[1])

    self.reindexObject()
Example #37
0
def PUT(self, REQUEST=None, RESPONSE=None):
    """ HTTP PUT handler with marshalling support
    """
    if not REQUEST:
        REQUEST = self.REQUEST
    if not RESPONSE:
        RESPONSE = REQUEST.RESPONSE
    if not self.Schema().hasLayer('marshall'):
        RESPONSE.setStatus(501)  # Not implemented
        return RESPONSE

    self.dav__init(REQUEST, RESPONSE)
    collection_check(self)

    self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
    is_new_object = self.checkCreationFlag()

    file = REQUEST.get('BODYFILE', _marker)
    if file is _marker:
        data = REQUEST.get('BODY', _marker)
        if data is _marker:
            raise AttributeError, 'REQUEST neither has a BODY nor a BODYFILE'
    else:
        data = ''
        file.seek(0)

    mimetype = REQUEST.get_header('content-type', None)
    # mimetype, if coming from request can be like:
    # text/plain; charset='utf-8'
    #
    # XXX we should really parse the extra params and pass them on as
    # keyword arguments.
    if mimetype is not None:
        mimetype = str(mimetype).split(';')[0].strip()

    filename = posixpath.basename(REQUEST.get('PATH_INFO', self.getId()))
    # XXX remove after we are using global services
    # use the request to find an object in the traversal hierachy that is
    # able to acquire a mimetypes_registry instance
    # This is a hack to avoid the acquisition problem on FTP/WebDAV object
    # creation
    parents = (self, ) + tuple(REQUEST.get('PARENTS', ()))
    context = None
    for parent in parents:
        if getToolByName(parent, 'mimetypes_registry', None) is not None:
            context = parent
            break

    # Marshall the data
    marshaller = self.Schema().getLayerImpl('marshall')

    args = [self, data]
    kwargs = {
        'file': file,
        'context': context,
        'mimetype': mimetype,
        'filename': filename,
        'REQUEST': REQUEST,
        'RESPONSE': RESPONSE
    }
    ddata = mapply(marshaller.demarshall, *args, **kwargs)

    if (shasattr(self, 'demarshall_hook') and self.demarshall_hook):
        self.demarshall_hook(ddata)
    self.manage_afterPUT(data, marshall_data=ddata, **kwargs)
    self.reindexObject()
    self.unmarkCreationFlag()

    if is_new_object:
        event.notify(WebDAVObjectInitializedEvent(self))
    else:
        event.notify(WebDAVObjectEditedEvent(self))

    RESPONSE.setStatus(204)
    return RESPONSE
    def _processForm(self, data=1, metadata=None, REQUEST=None, values=None):
        request = REQUEST or self.REQUEST
        if values:
            form = values
        else:
            form = request.form
        fieldset = form.get('fieldset', None)
        schema = self.Schema()
        schemata = self.Schemata()
        fields = []

        if not IMultiPageSchema.providedBy(self):
            fields = schema.fields()
        elif fieldset is not None:
            fields = schemata[fieldset].fields()
        else:
            if data:
                fields += schema.filterFields(isMetadata=0)
            if metadata:
                fields += schema.filterFields(isMetadata=1)

        canonical = self.isCanonical()
        for field in fields:
            if not canonical:
                # On non-canonical items the translate screen shows language
                # independent fields in view mode. This means the form will not
                # contain their data. The contract for processForm is that
                # missing fields can be interpreted as "delete all". We need to
                # avoid this for LP or we might accidentally delete data.
                if getattr(field, 'languageIndependent', False):
                    continue

            # Delegate to the widget for processing of the form
            # element.  This means that if the widget needs _n_
            # fields under a naming convention it can handle this
            # internally.  The calling API is process_form(instance,
            # field, form) where instance should rarely be needed,
            # field is the field object and form is the dict. of
            # kv_pairs from the REQUEST
            #
            # The product of the widgets processing should be:
            #   (value, **kwargs) which will be passed to the mutator
            #   or None which will simply pass

            if not field.writeable(self):
                # If the field has no 'w' in mode, or the user doesn't
                # have the required permission, or the mutator doesn't
                # exist just bail out.
                continue

            try:
                # Pass validating=False to inform the widget that we
                # aren't in the validation phase, IOW, the returned
                # data will be forwarded to the storage
                result = field.widget.process_form(self,
                                                   field,
                                                   form,
                                                   empty_marker=_marker,
                                                   validating=False)
            except TypeError:
                # Support for old-style process_form methods
                result = field.widget.process_form(self,
                                                   field,
                                                   form,
                                                   empty_marker=_marker)

            if result is _marker or result is None:
                continue

            # Set things by calling the mutator
            mutator = field.getMutator(self)
            __traceback_info__ = (self, field, mutator)
            result[1]['field'] = field.__name__
            mapply(mutator, result[0], **result[1])

        self.reindexObject()
def setMetadataMap(ob, metadata):
    """ sets a simple map with metadata on the current context.
        we also do some conversions for old metadata ini files.
    """
    _marker = []
    compatibility = {'NACE': 'nace',
                     'keywords': 'subject',
                     }
    for comp in compatibility.keys():
        if comp in metadata:
            metadata[compatibility[comp]] = metadata[comp]
            del metadata[comp]

    # we dont want to set the language explicitly
    if 'language' in metadata:
        del metadata['language']

    # convert old MTSubject
    if 'MTSubject' in metadata:
        newmt = []
        mt = metadata['MTSubject']
        for m in mt:
            newmt.append(os.path.basename(str(m)))
        metadata['multilingual_thesaurus'] = newmt
        del metadata['MTSubject']

    # convert the old country path notation to ISOCode notation
    if 'Country' in metadata:
        c = metadata['Country']
        newc = []
        for C in c:
            elems = C.split("/")
            if len(elems) < 2:
                continue
            elif len(elems) == 2:
                newc.append('EU')
            else:
                if str(elems[2]) == 'MS':
                    newc.append('EU')
                else:
                    newc.append(str(elems[2]))
        metadata['country'] = newc
        del metadata['Country']

    for key in metadata:

        field = ob.getField(key)
        if field is None:
            continue

        result = field.widget.process_form(ob, field, metadata,
                                               empty_marker=_marker,
                                               validating=False)
        if result is _marker or result is None:
            continue

        mutator = field.getMutator(ob)
        __traceback_info__ = (ob, field, mutator)
        result[1]['field'] = field.__name__
        mapply(mutator, result[0], **result[1])

    ob.reindexObject()
 def __init__(self, *args, **kw):
     self._extra = kw['extra']
     del kw['extra']
     args = (self,) + args
     mapply(PageTemplateFile.__init__, *args, **kw)
Example #41
0
 def __init__(self, *args, **kw):
     self._extra = kw['extra']
     del kw['extra']
     args = (self, ) + args
     mapply(PageTemplateFile.__init__, *args, **kw)