Examples of FieldHandler


Examples of org.exolab.castor.mapping.FieldHandler

        }

        TypeInfo typeInfo = getTypeInfo(fieldType, colHandler, fieldMap);

        ExtendedFieldHandler exfHandler = null;
        FieldHandler handler = null;

        // Check for user supplied FieldHandler
        if (fieldMap.getHandler() != null) {
            handler = getFieldHandler(fieldMap);

            // ExtendedFieldHandler?
            if (handler instanceof ExtendedFieldHandler) {
                exfHandler = (ExtendedFieldHandler) handler;
            }

            // Fix for CastorJDO from Steve Vaughan, CastorJDO requires FieldHandlerImpl
            // or a ClassCastException will be thrown... [KV 20030131 - also make sure
            // this new handler doesn't use it's own CollectionHandler otherwise it'll
            // cause unwanted calls to the getValue method during unmarshalling]
            colHandler = typeInfo.getCollectionHandler();
            typeInfo.setCollectionHandler(null);
            handler = new FieldHandlerImpl(handler, typeInfo);
            typeInfo.setCollectionHandler(colHandler);
            // End Castor JDO fix
        }

        boolean generalized = (exfHandler instanceof GeneralizedFieldHandler);

        // If generalized we need to change the fieldType to whatever is specified in the
        // GeneralizedFieldHandler so that the correct getter/setter methods can be found
        if (generalized) {
            fieldType = ((GeneralizedFieldHandler)exfHandler).getFieldType();
        }

        if (generalized || (handler == null)) {
            // Create TypeInfoRef to get new TypeInfo from call to createFieldHandler
            FieldHandler custom = handler;
            TypeInfoReference typeInfoRef = new TypeInfoReference();
            typeInfoRef.typeInfo = typeInfo;
            handler = createFieldHandler(javaClass, fieldType, fieldMap, typeInfoRef);
            if (custom != null) {
                ((GeneralizedFieldHandler) exfHandler).setFieldHandler(handler);
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

    private FieldHandler getFieldHandler(final FieldMapping fieldMap)
    throws MappingException {
       
        // If there is a custom field handler present in the mapping, that one
        // is returned.
        FieldHandler handler = (FieldHandler) _fieldHandlers.get(fieldMap.getHandler());
        if (handler != null) {
          return handler;
        }
       
        Class handlerClass = null;
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

            typeInfo = new TypeInfo(type, null, null, false, null, colHandler);

            //-- Create FieldHandler first, before the XMLFieldDescriptor
            //-- in case we need to use a custom handler

            FieldHandler handler = null;
            boolean customHandler = false;
            try {
                handler = new FieldHandlerImpl(methodSet.fieldName,
                                                null,
                                                null,
                                                methodSet.get,
                                                methodSet.set,
                                                typeInfo);
                //-- clean up
                if (methodSet.add != null)
                    ((FieldHandlerImpl)handler).setAddMethod(methodSet.add);

                if (methodSet.create != null)
                    ((FieldHandlerImpl)handler).setCreateMethod(methodSet.create);

                //-- handle Hashtable/Map
                if (isCollection && _saveMapKeys && isMapCollection(type)) {
                    ((FieldHandlerImpl)handler).setConvertFrom(new IdentityConvertor());
                }

                //-- look for GeneralizedFieldHandler
                FieldHandlerFactory factory = getHandlerFactory(type);
                if (factory != null) {
                    GeneralizedFieldHandler gfh = factory.createFieldHandler(type);
                    if (gfh != null) {
                        gfh.setFieldHandler(handler);
                        handler = gfh;
                        customHandler = true;
                        //-- swap type with the type specified by the
                        //-- custom field handler
                        if (gfh.getFieldType() != null) {
                            type = gfh.getFieldType();
                        }
                    }
                }

            }
            catch (MappingException mx) {
                throw new MarshalException(mx);
            }


            XMLFieldDescriptorImpl fieldDesc
                = createFieldDescriptor(type, methodSet.fieldName, xmlName);

            if (isCollection) {
                fieldDesc.setMultivalued(true);
                fieldDesc.setNodeType(NodeType.Element);
            }

            //-- check for instances of java.util.Date
            if (java.util.Date.class.isAssignableFrom(type)) {
                //handler = new DateFieldHandler(handler);
                if (!customHandler) {
                    dateDescriptors.add(fieldDesc);
                }
            }

            fieldDesc.setHandler(handler);
           
            //-- enable use parent namespace if explicit one doesn't exist
            fieldDesc.setUseParentsNamespace(true);

            //-- Wrap collections?
            if (isCollection && _wrapCollectionsInContainer) {
                String fieldName = COLLECTION_WRAPPER_PREFIX + methodSet.fieldName;
                //-- If we have a field 'c' that is a collection and
                //-- we want to wrap that field in an element <e>, we
                //-- need to create a field descriptor for
                //-- an object that represents the element <e> and
                //-- acts as a go-between from the parent of 'c'
                //-- denoted as P(c) and 'c' itself
                //
                //   object model: P(c) -> c
                //   xml : <p><e><c></e><p>

                //-- Make new class descriptor for the field that
                //-- will represent the container element <e>
                Class cType = ContainerElement.class;
                XMLClassDescriptorImpl containerClassDesc = new XMLClassDescriptorImpl(cType);

                //-- add the field descriptor to our new class descriptor
                containerClassDesc.addFieldDescriptor(fieldDesc);
                //-- nullify xmlName so that auto-naming will be enabled,
                //-- we can't do this in the constructor because
                //-- XMLFieldDescriptorImpl will create a default one.
                fieldDesc.setXMLName(null);
                fieldDesc.setMatches("*");

                //-- wrap the field handler in a special container field
                //-- handler that will actually do the delegation work
                FieldHandler cHandler = new ContainerFieldHandler(handler);
                fieldDesc.setHandler(cHandler);

                fieldDesc = createFieldDescriptor(cType, fieldName, xmlName);
                fieldDesc.setClassDescriptor(containerClassDesc);
                fieldDesc.setHandler(cHandler);

                //-- enable use parent namespace if explicit one doesn't exist
                fieldDesc.setUseParentsNamespace(true);
               
            }
            //-- add FieldDescriptor to ClassDescriptor
            classDesc.addFieldDescriptor(fieldDesc);


        } //-- end of method loop

        //-- If we didn't find any methods we can try
        //-- direct field access
        if (methodCount == 0) {

            Field[] fields = c.getFields();
            Hashtable descriptors = new Hashtable();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];

                Class owner = field.getDeclaringClass();

                //-- ignore fields from super-class, that will be
                //-- introspected separately, if necessary
                if (owner != c) {
                    //-- if declaring class is anything but
                    //-- an interface, than just continue,
                    //-- the field comes from a super class
                    //-- (e.g. java.lang.Object)
                    if (!owner.isInterface()) continue;

                    //-- owner is an interface, is it an
                    //-- interface this class implements
                    //-- or a parent class?
                    if (interfaces.length > 0) {
                        boolean found = false;
                        for (int count = 0; count < interfaces.length; count++) {
                            if (interfaces[count] == owner) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) continue;
                    }
                }

                //-- make sure field is not transient or static final
                int modifiers = field.getModifiers();
                if (Modifier.isTransient(modifiers)) continue;
                if (Modifier.isFinal(modifiers) &&
                    Modifier.isStatic(modifiers))
                    continue;

                Class type = field.getType();



                if (!isDescriptable(type)) continue;

                //-- Built-in support for JDK 1.1 Collections
                //-- we need to a pluggable interface for
                //-- JDK 1.2+
                boolean isCollection = isCollection(type);


                TypeInfo typeInfo = null;
                CollectionHandler colHandler = null;

                //-- If the type is a collection and there is no add method,
                //-- then we obtain a CollectionHandler
                if (isCollection) {

                    try {
                        colHandler = CollectionHandlers.getHandler(type);
                    }
                    catch(MappingException mx) {
                        //-- No CollectionHandler available, continue
                        //-- without one...
                    }

                    //-- Find component type
                    if (type.isArray()) {
                        //-- Byte arrays are handled as a special case
                        //-- so don't use CollectionHandler
                        if (type.getComponentType() == Byte.TYPE) {
                            colHandler = null;
                        }
                        else type = type.getComponentType();

                    }
                }

                String fieldName = field.getName();
                String xmlName = _xmlNaming.toXMLName(fieldName);

                //-- Create FieldHandler first, before the XMLFieldDescriptor
                //-- in case we need to use a custom handler

                typeInfo = new TypeInfo(type, null, null, false, null, colHandler);

                FieldHandler handler = null;
                boolean customHandler = false;
                try {
                    handler = new FieldHandlerImpl(field, typeInfo);

                    //-- handle Hashtable/Map
                    if (isCollection && _saveMapKeys && isMapCollection(type)) {
                        ((FieldHandlerImpl)handler).setConvertFrom(new IdentityConvertor());
                    }

                    //-- look for GeneralizedFieldHandler
                    FieldHandlerFactory factory = getHandlerFactory(type);
                    if (factory != null) {
                        GeneralizedFieldHandler gfh = factory.createFieldHandler(type);
                        if (gfh != null) {
                            gfh.setFieldHandler(handler);
                            handler = gfh;
                            customHandler = true;
                            //-- swap type with the type specified by the
                            //-- custom field handler
                            if (gfh.getFieldType() != null) {
                                type = gfh.getFieldType();
                            }
                        }
                    }
                }
                catch (MappingException mx) {
                    throw new MarshalException(mx);
                }

                XMLFieldDescriptorImpl fieldDesc =
                        createFieldDescriptor(type, fieldName, xmlName);

                if (isCollection) {
                    fieldDesc.setNodeType(NodeType.Element);
                    fieldDesc.setMultivalued(true);
                }
                descriptors.put(xmlName, fieldDesc);
                classDesc.addFieldDescriptor(fieldDesc);
                fieldDesc.setHandler(handler);

                //-- enable use parent namespace if explicit one doesn't exist
                fieldDesc.setUseParentsNamespace(true);

                //-- check for instances of java.util.Date
                if (java.util.Date.class.isAssignableFrom(type)) {
                    if (!customHandler) {
                        dateDescriptors.add(fieldDesc);
                    }
                }

            }
        } //-- end of direct field access


        //-- A temporary fix for java.util.Date
        if (dateDescriptors != null) {
            for (int i = 0; i < dateDescriptors.size(); i++) {
                XMLFieldDescriptorImpl fieldDesc =
                    (XMLFieldDescriptorImpl) dateDescriptors.get(i);
                FieldHandler handler = fieldDesc.getHandler();
                fieldDesc.setImmutable(true);
                DateFieldHandler dfh = new DateFieldHandler(handler);

                //-- patch for java.sql.Date
                Class type = fieldDesc.getFieldType();
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

                    if (desc == null) {
                        continue;
                    }

                    FieldHandler handler = desc.getHandler();

                    if (handler.getValue(object) != null) {
                         //Special case if we have a Vector, an ArrayList
                         //or an Array --> need to check if it is not empty
                         if (desc.isMultivalued()) {
                             Object temp = handler.getValue(object);
                             //-- optimize this?
                             if (Array.getLength(temp) == 0) {
                                  temp = null;
                                  continue;
                             }
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

            else
                result = ((XMLClassDescriptor)fieldDesc.getClassDescriptor()).canAccept(name, namespace, tempObject);
        }
        //4-- Check if the value is set or not
        else {
            FieldHandler handler = fieldDesc.getHandler();

            boolean checkPrimitiveValue = true;
            if (handler instanceof AbstractFieldHandler) {
                hasValue = ((AbstractFieldHandler)handler).hasValue( object );
                //-- poor man's check for a generated handler, since
                //-- all generated handlers extend XMLFieldHandler, however
                //-- this doesn't guarantee that that handler is indeed
                //-- a generated handler, it does however mean that
                //-- the handler definately didn't come from the
                //-- MappingLoader.
                //checkPrimitiveValue = (!(handler instanceof XMLFieldHandler));
            }
            else {
                hasValue = (handler.getValue(object) != null);
            }

            //-- patch for primitives, we should check
            //-- for the has-method somehow...but this
            //-- is good enough for now. This may break
            //-- some non-Castor-generated code with
            //-- primitive values that have been set
            //-- with the same as the defaults
            if (hasValue &&
                checkPrimitiveValue &&
                fieldDesc.getFieldType().isPrimitive())
            {
                if (isDefaultPrimitiveValue(handler.getValue( object ))) {
                    hasValue = false;
                }
            }
            //-- end patch
            result = !hasValue;
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

        }
       
        TypeInfo typeInfo = getTypeInfo(fieldType, colHandler, fieldMap);
           
        ExtendedFieldHandler exfHandler = null;
        FieldHandler handler = null;
       
        //-- check for user supplied FieldHandler
        if (fieldMap.getHandler() != null) {
           
            Class handlerClass = resolveType(fieldMap.getHandler());
           
            if (!FieldHandler.class.isAssignableFrom(handlerClass)) {
                String err = "The class '" + fieldMap.getHandler()
                    + "' must implement " + FieldHandler.class.getName();
                throw new MappingException(err);
            }
           
            //-- get default constructor to invoke. We can't use the
            //-- newInstance method unfortunately becaue FieldHandler
            //-- overloads this method
            Constructor constructor = null;
            try {
                constructor = handlerClass.getConstructor(new Class[0]);
                handler = (FieldHandler)
                    constructor.newInstance(new Object[0]);
            } catch (Exception except) {
                String err = "The class '" + handlerClass.getName()
                    + "' must have a default public constructor.";
                throw new MappingException(err);
            }
           
           
            //-- ExtendedFieldHandler?
            if (handler instanceof ExtendedFieldHandler) {
                exfHandler = (ExtendedFieldHandler) handler;
            }
           
            //-- Fix for Castor JDO from Steve Vaughan, Castor JDO
            //-- requires FieldHandlerImpl or a ClassCastException
            //-- will be thrown... [KV 20030131 - also make sure this new handler
            //-- doesn't use it's own CollectionHandler otherwise
            //-- it'll cause unwanted calls to the getValue method during
            //-- unmarshalling]
            colHandler = typeInfo.getCollectionHandler();
            typeInfo.setCollectionHandler(null);
            handler = new FieldHandlerImpl(handler, typeInfo);
            typeInfo.setCollectionHandler(colHandler);
            //-- End Castor JDO fix
           
        }
       
        boolean generalized = (exfHandler instanceof GeneralizedFieldHandler);
       
        //-- if generalized we need to change the fieldType to whatever
        //-- is specified in the GeneralizedFieldHandler so that the
        //-- correct getter/setter methods can be found
        FieldHandler custom = handler;
        if (generalized) {
            fieldType = ((GeneralizedFieldHandler) exfHandler).getFieldType();
        }
       
        if (generalized || (handler == null)) {
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

        FieldMapping ssnrFM = new FieldMapping();
        TypeInfo ssnrType = new TypeInfo(java.lang.Long.class);
        // Set columns required (= not null)
        ssnrType.setRequired(true);

        FieldHandler ssnrHandler;
        try {
            Method ssnrGetMethod = Father.class.getMethod("getSsnr", null);
            Method ssnrSetMethod = Father.class.getMethod("setSsnr", new Class[]{
                long.class});

            ssnrHandler = new FieldHandlerImpl(ssnrFieldName, null, null,
                ssnrGetMethod, ssnrSetMethod, ssnrType);

        } catch (SecurityException e1) {
            throw new RuntimeException(e1.getMessage());
        } catch (MappingException e1) {
            throw new RuntimeException(e1.getMessage());
        } catch (NoSuchMethodException e1) {
            throw new RuntimeException(e1.getMessage());
        }
        // Instantiate ssnr field descriptor
        ssnrFieldDescr = new FieldDescriptorImpl(ssnrFieldName, ssnrType,ssnrHandler, false);
        ssnrFieldDescr.addNature(FieldDescriptorJDONature.class.getName());
        FieldDescriptorJDONature ssnrFieldJdoNature = new FieldDescriptorJDONature(ssnrFieldDescr);
        ssnrFieldJdoNature.setSQLName(new String[] { "ssnr" });
        ssnrFieldJdoNature.setSQLType(new int[] {SQLTypeInfos.javaType2sqlTypeNum(java.lang.Long.class) });
        ssnrFieldJdoNature.setManyTable(null);
        ssnrFieldJdoNature.setManyKey(new String[] {});
        ssnrFieldJdoNature.setDirtyCheck(false);
        ssnrFieldJdoNature.setReadOnly(false);

        ssnrFieldDescr.setContainingClassDescriptor(this);
        ssnrFieldDescr.setIdentity(true);
        ssnrFM.setIdentity(true);
        ssnrFM.setDirect(false);
        ssnrFM.setName("ssnr");
        ssnrFM.setRequired(true);
        ssnrFM.setSetMethod("setSsnr");
        ssnrFM.setGetMethod("getSsnr");
        Sql ssnrSql = new Sql();
        ssnrSql.addName("ssnr");
        ssnrSql.setType("integer");
        ssnrFM.setSql(ssnrSql);
        ssnrFM.setType("long");
        choice.addFieldMapping(ssnrFM);

        //firstName field
        String firstNameFieldName = "firstName";
        FieldDescriptorImpl firstNameFieldDescr;
        FieldMapping firstNameFM = new FieldMapping();
        TypeInfo firstNameType = new TypeInfo(java.lang.String.class);
        // Set columns required (= not null)
        firstNameType.setRequired(true);

        FieldHandler firstNameHandler;
        try {
            Method firstNameGetMethod = Father.class.getMethod("getFirstName", null);
            Method firstNameSetMethod = Father.class.getMethod("setFirstName", new Class[]{
                java.lang.String.class});

            firstNameHandler = new FieldHandlerImpl(firstNameFieldName, null, null,
                firstNameGetMethod, firstNameSetMethod, firstNameType);

        } catch (SecurityException e1) {
            throw new RuntimeException(e1.getMessage());
        } catch (MappingException e1) {
            throw new RuntimeException(e1.getMessage());
        } catch (NoSuchMethodException e1) {
            throw new RuntimeException(e1.getMessage());
        }
        // Instantiate firstName field descriptor
        firstNameFieldDescr = new FieldDescriptorImpl(firstNameFieldName, firstNameType,firstNameHandler, false);
        firstNameFieldDescr.addNature(FieldDescriptorJDONature.class.getName());
        FieldDescriptorJDONature firstNameFieldJdoNature = new FieldDescriptorJDONature(firstNameFieldDescr);
        firstNameFieldJdoNature.setSQLName(new String[] { "firstName" });
        firstNameFieldJdoNature.setSQLType(new int[] {SQLTypeInfos.javaType2sqlTypeNum(java.lang.String.class) });
        firstNameFieldJdoNature.setManyTable(null);
        firstNameFieldJdoNature.setManyKey(new String[] {});
        firstNameFieldJdoNature.setDirtyCheck(false);
        firstNameFieldJdoNature.setReadOnly(false);

        firstNameFieldDescr.setContainingClassDescriptor(this);
        firstNameFieldDescr.setIdentity(false);
        firstNameFM.setIdentity(false);
        firstNameFM.setDirect(false);
        firstNameFM.setName("firstName");
        firstNameFM.setRequired(true);
        firstNameFM.setSetMethod("setFirstName");
        firstNameFM.setGetMethod("getFirstName");
        Sql firstNameSql = new Sql();
        firstNameSql.addName("firstName");
        firstNameSql.setType("varchar");
        firstNameFM.setSql(firstNameSql);
        firstNameFM.setType("java.lang.String");
        choice.addFieldMapping(firstNameFM);

        //lastName field
        String lastNameFieldName = "lastName";
        FieldDescriptorImpl lastNameFieldDescr;
        FieldMapping lastNameFM = new FieldMapping();
        TypeInfo lastNameType = new TypeInfo(java.lang.String.class);
        // Set columns required (= not null)
        lastNameType.setRequired(true);

        FieldHandler lastNameHandler;
        try {
            Method lastNameGetMethod = Father.class.getMethod("getLastName", null);
            Method lastNameSetMethod = Father.class.getMethod("setLastName", new Class[]{
                java.lang.String.class});
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

        String id = null;
        try {
            ClassDescriptorResolver classDescriptorResolver = context.getClassDescriptorResolver();
            ClassDescriptor classDescriptor = classDescriptorResolver.resolve(object.getClass());
            FieldDescriptor fieldDescriptor = classDescriptor.getIdentity();
            FieldHandler fieldHandler = fieldDescriptor.getHandler();
            id = (String) fieldHandler.getValue(object);
        } catch (Exception e) {
            String err = "The object associated with IDREF \"" + object
            + "\" of type " + object.getClass() + " has no ID!";
            throw new ValidationException(err);
        }
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

                    }
                }


                try {
                    FieldHandler handler = cdesc.getHandler();
                    boolean addObject = true;
                    if (_reuseObjects) {
                        //-- check to see if we need to
                        //-- add the object or not
                        Object tmp = handler.getValue(state.object);
                        if (tmp != null) {
                            //-- Do not add object if values
                            //-- are equal
                            addObject = (!tmp.equals(value));
                        }
                    }
                    if (addObject) handler.setValue(state.object, value);
                }
                catch(java.lang.IllegalStateException ise) {
                    String err = "unable to add text content to ";
                    err += descriptor.getXMLName();
                    err += " due to the following error: " + ise;
                    throw new SAXException(err, ise);
                }
            }
            //-- Handle references
            else if (descriptor.isReference()) {
                UnmarshalState pState = (UnmarshalState) _stateInfo.peek();
                processIDREF(state.buffer.toString(), descriptor, pState.object);
                _namespaces = _namespaces.getParent();
                return;
            } else {
                //-- check for non-whitespace...and report error
                if (!isWhitespace(state.buffer)) {
                    String err = "Illegal Text data found as child of: "
                        + name;
                    err += "\n  value: \"" + state.buffer + "\"";
                    throw new SAXException(err);
                }
            }
        }
       
        //-- We're finished processing the object, so notify the
        //-- Listener (if any).
        if (_unmarshalListener != null && state.object != null) {
            _unmarshalListener.unmarshalled(state.object,
                    (state.parent == null) ? null : state.parent.object);
        }

        //-- if we are at root....just validate and we are done
         if (_stateInfo.empty()) {
             if (isValidating()) {
                ValidationException first = null;
                ValidationException last = null;
               
                //-- check unresolved references
                if (_resolveTable != null && !getInternalContext().getLenientIdValidation()) {
                    Enumeration enumeration = _resolveTable.keys();
                    while (enumeration.hasMoreElements()) {
                        Object ref = enumeration.nextElement();
                        //if (ref.toString().startsWith(MapItem.class.getName())) continue;
                        String msg = "unable to resolve reference: " + ref;                       
                        if (first == null) {
                            first = new ValidationException(msg);
                            last = first;
                        }
                        else {
                            last.setNext(new ValidationException(msg));
                            last = last.getNext();
                        }                           
                    }
                }
                try {
                    Validator validator = new Validator();
                    ValidationContext context = new ValidationContext();
                    context.setInternalContext(getInternalContext());
                    validator.validate(state.object, context);
                    if (!getInternalContext().getLenientIdValidation()) {
                        validator.checkUnresolvedIdrefs(context);
                    }
                    context.cleanup();
                }
                catch(ValidationException vEx) {
                    if (first == null)
                        first = vEx;
                    else
                        last.setNext(vEx);
                }
                if (first != null) {
                    throw new SAXException(first);
                }
            }
            return;
        }
        
        //-- Add object to parent if necessary

        if (descriptor.isIncremental()) {
            //-- remove current namespace scoping
           _namespaces = _namespaces.getParent();
           return; //-- already added
        }

        Object val = state.object;
       
        //--special code for AnyNode handling
        if (_node != null) {
           val = _node;
           _node = null;
        }

        //-- save fieldState
        UnmarshalState fieldState = state;

        //-- have we seen this object before?
        boolean firstOccurance = false;

        //-- get target object
        state = (UnmarshalState) _stateInfo.peek();
        if (state.wrapper) {
            state = fieldState.targetState;
        }
       
        //-- check to see if we have already read in
        //-- an element of this type.
        //-- (Q: if we have a container, do we possibly need to
        //--     also check the container's multivalued status?)
        if ( ! descriptor.isMultivalued() ) {

            if (state.isUsed(descriptor)) {
               
                String err = "element \"" + name;
                err += "\" occurs more than once. (parent class: " + state.type.getName() + ")";
               
                String location = name;
                while (!_stateInfo.isEmpty()) {
                    UnmarshalState tmpState = (UnmarshalState)_stateInfo.pop();
                    if (!tmpState.wrapper) {
                        if (tmpState.fieldDesc.isContainer()) continue;
                    }
                    location = state.elementName + "/" + location;
                }
               
                err += "\n location: /" + location;
               
                ValidationException vx =
                    new ValidationException(err);
               
              throw new SAXException(vx);
            }
            state.markAsUsed(descriptor);
            //-- if this is the identity then save id
            if (state.classDesc.getIdentity() == descriptor) {
                state.key = val;
            }
        }
        else {
            //-- check occurance of descriptor
            if (!state.isUsed(descriptor)) {
                firstOccurance = true;
            }
               
            //-- record usage of descriptor
            state.markAsUsed(descriptor);           
        }

        try {
            FieldHandler handler = descriptor.getHandler();
            //check if the value is a QName that needs to
            //be resolved (ns:value -> {URI}value)
            String valueType = descriptor.getSchemaType();
            if ((valueType != null) && (valueType.equals(QNAME_NAME))) {
                 val = resolveNamespace(val);
            }

            boolean addObject = true;
            if (_reuseObjects && fieldState.primitiveOrImmutable) {
                 //-- check to see if we need to
                 //-- add the object or not
                 Object tmp = handler.getValue(state.object);
                 if (tmp != null) {
                     //-- Do not add object if values
                     //-- are equal
                     addObject = (!tmp.equals(val));
                 }
            }
           
            //-- special handling for mapped objects
            if (descriptor.isMapped()) {
                if (!(val instanceof MapItem)) {
                    MapItem mapItem = new MapItem(fieldState.key, val);
                    val = mapItem;
                }
                else {
                    //-- make sure value exists (could be a reference)
                    MapItem mapItem = (MapItem)val;
                    if (mapItem.getValue() == null) {
                        //-- save for later...
                        addObject = false;
                        addReference(mapItem.toString(), state.object, descriptor);
                    }
                }
            }
           
            if (addObject) {
                //-- clear any collections if necessary
                if (firstOccurance && _clearCollections) {
                    handler.resetValue(state.object);
                }

                if (descriptor.isMultivalued()
                        && descriptor.getSchemaType() != null
                        && descriptor.getSchemaType().equals("list")
                        && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
                    List values = (List) val;
                    for (Iterator iterator = values.iterator(); iterator.hasNext();) {
                        //-- finally set the value!!
                        Object value = iterator.next();
                        handler.setValue(state.object, value);
                       
                        // If there is a parent for this object, pass along
                        // a notification that we've finished adding a child
                        if ( _unmarshalListener != null ) {
                            _unmarshalListener.fieldAdded(descriptor.getFieldName(), state.object, fieldState.object);
                        }
                    }
                } else {
               
                    //-- finally set the value!!
                    handler.setValue(state.object, val);

                    // If there is a parent for this object, pass along
                    // a notification that we've finished adding a child
                    if ( _unmarshalListener != null ) {
                        _unmarshalListener.fieldAdded(descriptor.getFieldName(), state.object, fieldState.object);
View Full Code Here

Examples of org.exolab.castor.mapping.FieldHandler

            Object containerObject = null;

            //1-- the container is not multivalued (not a collection)
            if (!descriptor.isMultivalued()) {
                // Check if the container object has already been instantiated
                FieldHandler handler = descriptor.getHandler();
                containerObject = handler.getValue(object);
                if (containerObject != null){
                    if (state.classDesc != null) {
                      if (state.classDesc.canAccept(name, namespace, containerObject)) {
                            //remove the descriptor from the used list
                            parentState.markAsNotUsed(descriptor);
                        }
                    }
                    else {
                        //remove the descriptor from the used list
                        parentState.markAsNotUsed(descriptor);
                    }
                }
                else {
                    containerObject = handler.newInstance(object);
                }

            }
            //2-- the container is multivalued
            else {
                Class containerClass = descriptor.getFieldType();
                try {
                     containerObject = containerClass.newInstance();
                }
                catch(Exception ex) {
                    throw new SAXException(ex);
                }
            }
            state.object = containerObject;
            state.type = containerObject.getClass();

            //we need to recall startElement()
            //so that we can find a more appropriate descriptor in for the given name
            _namespaces = _namespaces.createNamespaces();
            startElement(name, namespace, atts);
            return;
        }
        //--End of the container support
       
       

        //-- Find object type and create new Object of that type
        state.fieldDesc = descriptor;

        /* <update>
            *  we need to add this code back in, to make sure
            *  we have proper access rights.
            *
        if (!descriptor.getAccessRights().isWritable()) {
            if (debug) {
                buf.setLength(0);
                buf.append("The field for element '");
                buf.append(name);
                buf.append("' is read-only.");
                message(buf.toString());
            }
            return;
        }
        */

        //-- Find class to instantiate
        //-- check xml names to see if we should look for a more specific
        //-- ClassDescriptor, otherwise just use the one found in the
        //-- descriptor
        classDesc = null;
        if (cdInherited != null) classDesc = cdInherited;
        else if (!name.equals(descriptor.getXMLName()))
            classDesc = resolveByXMLName(name, namespace, null);

        if (classDesc == null)
            classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
        FieldHandler handler = descriptor.getHandler();
        boolean useHandler = true;

        try {

            //-- Get Class type...first use ClassDescriptor,
            //-- since it could be more specific than
            //-- the FieldDescriptor
            if (classDesc != null) {
                _class = classDesc.getJavaClass();

                //-- XXXX This is a hack I know...but we
                //-- XXXX can't use the handler if the field
                //-- XXXX types are different
                if (descriptor.getFieldType() != _class) {
                    state.derived = true;
                }
            }
            else {
                _class = descriptor.getFieldType();
            }
           
            //-- This *shouldn't* happen, but a custom implementation
            //-- could return null in the XMLClassDesctiptor#getJavaClass
            //-- or XMLFieldDescriptor#getFieldType. If so, just replace
            //-- with java.lang.Object.class (basically "anyType").
            if (_class == null) {
                _class = java.lang.Object.class;
            }

            // Retrieving the xsi:type attribute, if present
            String currentPackage = getJavaPackage(parentState.type);
            String instanceType = getInstanceType(atts, currentPackage);
            if (instanceType != null) {
               
                Class instanceClass = null;
                try {

                    XMLClassDescriptor instanceDesc
                        = getClassDescriptor(instanceType, _loader);

                    boolean loadClass = true;

                    if (instanceDesc != null) {
                        instanceClass = instanceDesc.getJavaClass();
                        classDesc = instanceDesc;
                        if (instanceClass != null) {
                            loadClass = (!instanceClass.getName().equals(instanceType));
                        }
                    }

                    if (loadClass) {
                        instanceClass = loadClass(instanceType, null);
                        //the FieldHandler can be either an XMLFieldHandler
                        //or a FieldHandlerImpl
                        FieldHandler tempHandler = descriptor.getHandler();

                        boolean collection = false;
                        if (tempHandler instanceof FieldHandlerImpl) {
                            collection = ((FieldHandlerImpl) tempHandler).isCollection();
                        }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.