Package org.exolab.castor.mapping.xml

Examples of org.exolab.castor.mapping.xml.FieldMapping


        }

        XMLClassDescriptor xmlClass;
        FieldDescriptor[] fields;
        ClassMapping classMap;
        FieldMapping fieldMap;

        boolean introspected = false;
        try {
            if (_forceIntrospection) {
                xmlClass = _internalContext.getIntrospector().generateClassDescriptor(cls);
                introspected = true;
            } else {
                xmlClass = (XMLClassDescriptor) _internalContext.getXMLClassDescriptorResolver().resolve(cls);
                introspected = _internalContext.getIntrospector().introspected(xmlClass);
            }
        } catch (Exception except) {
            throw new MappingException(except);
        }
        classMap = new ClassMapping();
        classMap.setName(cls.getName());
        classMap.setDescription("Default mapping for class " + cls.getName());

        // -- prevent default access from showing up in the mapping
        classMap.setAccess(null);

        // -- map-to
        MapTo mapTo = new MapTo();
        mapTo.setXml(xmlClass.getXMLName());
        mapTo.setNsUri(xmlClass.getNameSpaceURI());
        mapTo.setNsPrefix(xmlClass.getNameSpacePrefix());
        classMap.setMapTo(mapTo);

        // -- add mapping to hashtable before processing
        // -- fields so we can do recursive processing
        _mappings.put(cls, classMap);

        fields = xmlClass.getFields();
        for (int i = 0; i < fields.length; ++i) {
            FieldDescriptor fdesc = fields[i];

            String fieldName = fdesc.getFieldName();

            boolean isContainer = false;
            // -- check for collection wrapper
            if (introspected && fieldName.startsWith("##container")) {
                fdesc = fdesc.getClassDescriptor().getFields()[0];
                fieldName = fdesc.getFieldName();
                isContainer = true;
            }

            Class fieldType = fdesc.getFieldType();

            // -- check to make sure we can find the accessors...
            // -- if we used introspection we don't need to
            // -- enter this block...only when descriptors
            // -- were generated using the source code generator
            // -- or by hand.
            if ((!introspected) && fieldName.startsWith(UNDERSCORE)) {
                // -- check to see if we need to remove underscore
                if (!_mappingLoader.canFindAccessors(cls, fieldName, fieldType)) {
                    fieldName = fieldName.substring(1);
                }

                // -- check to see if we need to remove "List" prefix
                // -- used by generated source code
                if (!_mappingLoader.canFindAccessors(cls, fieldName, fieldType)) {
                    if (fieldName.endsWith("List")) {
                        int len = fieldName.length() - 4;
                        String tmpName = fieldName.substring(0, len);
                        if (_mappingLoader.canFindAccessors(cls, tmpName, fieldType)) {
                            fieldName = tmpName;
                        }
                    }
                }
            }

            fieldMap = new FieldMapping();
            fieldMap.setName(fieldName);

            // -- unwrap arrays of objects
            boolean isArray = fieldType.isArray();
            while (fieldType.isArray()) {
                fieldType = fieldType.getComponentType();
            }

            // -- To prevent outputing of optional fields...check
            // -- for value first before setting
            if (fdesc.isRequired()) {
                fieldMap.setRequired(true);
            }
            if (fdesc.isTransient()) {
                fieldMap.setTransient(true);
            }
            if (fdesc.isMultivalued()) {
                // -- special case for collections
                if (isContainer) {
                    // -- backwards than what you'd expect, but
                    // -- if the collection had a "container" wrapper
                    // -- then we specify container="false" in the
                    // -- mapping file.
                    fieldMap.setContainer(false);
                }

                // -- try to guess collection type
                if (isArray) {
                    fieldMap.setCollection(FieldMappingCollectionType.ARRAY);
                } else {
                    // -- if the fieldType is the collection, then set
                    // appropriate
                    // -- collection type
                    String colName = CollectionHandlers.getCollectionName(fieldType);
                    if (colName != null) {
                        fieldMap.setCollection(FieldMappingCollectionType.valueOf(colName));
                        fieldType = Object.class;
                    } else if (_mappingLoader.returnsArray(cls, fieldName, fieldType)) {
                        // -- help maintain compatibility with generated
                        // descriptors
                        fieldMap.setCollection(FieldMappingCollectionType.ARRAY);
                    } else {
                        fieldMap.setCollection(FieldMappingCollectionType.ENUMERATE);
                    }
                }
            }

            // -- fieldType
            fieldMap.setType(fieldType.getName());

            // -- handle XML Specific information
            fieldMap.setBindXml(new BindXml());
            fieldMap.getBindXml().setName(((XMLFieldDescriptor) fdesc).getXMLName());
            fieldMap.getBindXml().setNode(
                    BindXmlNodeType.valueOf(((XMLFieldDescriptor) fields[i]).getNodeType()
                            .toString()));
            if (classMap.getClassChoice() == null) {
                classMap.setClassChoice(new ClassChoice());
            }
View Full Code Here


            AttributeListImpl attrs = new AttributeListImpl();

            for (int i = 0; i < attrCols.length; i++) {
                String attrCol = attrCols[i];
                Integer attrColNum = (Integer) _cols.get(attrCol);
                FieldMapping field = desc.getAttr(attrCol);
                String attrName = null;
                if (field.getBindXml() == null || field.getBindXml().getName() == null) {
                attrName = field.getName();
                } else {
                attrName = field.getBindXml().getName();
                }

                String attrValue = rs.getString(attrColNum.intValue());
                attrs.addAttribute(attrName, "CDATA", attrValue);
            }

            _handler.startElement(elementName, attrs);

            for (int j = 0; j < simpleElementCols.length; j++) {
                String simpleElementCol = simpleElementCols[j];
                Integer elementColNum = (Integer) _cols.get(simpleElementCol);
                FieldMapping elField = desc.getSimpleElement(simpleElementCol);
                String elName = null;
                if (elField.getBindXml() == null || elField.getBindXml().getName() == null) {
                elName = elField.getName();
                } else {
                elName = elField.getBindXml().getName();
                }

                String elValue = rs.getString(elementColNum.intValue());
                _handler.startElement(elName, new AttributeListImpl());
                _handler.characters(elValue.toCharArray(), 0, elValue.length());
View Full Code Here

        }

        String table = mapTo.getTable();

            FieldMapping[] fields = clsMapping.getClassChoice().getFieldMapping();
        FieldMapping identity = null;

            String identityName = clsMapping.getIdentity(0);

        for (int j = 0; j < fields.length; j++) {
            if (fields[j].getName().equals(identityName)) {
            identity = fields[j];
            break;
            }
        }

        if (identity == null) {
            throw new DTXException("no identity field in class: " + clsMapping.getName());
        }

        Sql identitySQLElement = identity.getSql();

        if (identitySQLElement == null) {
            throw new DTXException("no identity SQL info in class: " + clsMapping.getName());
        }

        String identitySQL = identitySQLElement.getName()[0];

        _ids.add(table + "." + identitySQL);

        DTXClassDescriptor desc = new DTXClassDescriptor(clsMapping);

        _classes.put(table + "." + identitySQL, desc);

        // If this class extends another class, create a join with the parent table and
        // add the load fields of the parent class (but not the store fields)
        if (clsMapping.getExtends() != null) {

        /**
          * TODO : Needs to be resolved by Hand
          */

            MapTo extendsTo = new MapTo()//(ClassMapping) clsMapping.getExtends()).getMapTo();
            if (extendsTo == null) {
                throw new DTXException("no mapping info for extends table.");
            }
            String extendsTable = extendsTo.getTable();
            expr.addInnerJoin(table, identitySQL, extendsTable, identitySQL);
            /**
             * needs to be resolved by hand
             */
            initQuery(new ClassMapping(), expr);
            //(ClassMapping) clsMapping.getExtends(), expr);
        }

        for (int i = 0; i < fields.length; ++i) {
            FieldMapping field = fields[i];
            Sql fieldSql = field.getSql();
            ClassMapping relMapping = _eng.getClassMapping(field.getType());

            if (fieldSql == null) {
                if (relMapping != null) {

                    // We have a one-to-many relationship with a sub object.
                    // get those objects, too.

                    FieldMapping[] relFields = relMapping.getClassChoice().getFieldMapping();
                    MapTo relMapTo = relMapping.getMapTo();

                    if (relMapTo == null) {
                        throw new DTXException("dtx.NoRelatedMapTo");
                    }

                    String relTable = relMapTo.getTable();

                    String foreKey = null;

                    for (int k = 0; k < relFields.length; k++) {
                        Sql relSql = relFields[k].getSql();
                        if (relSql != null) {
                            String type = relFields[k].getType();
                            if (type != null && type.equals(clsMapping.getName())) {
                                foreKey = relSql.getName()[0];
                            }
                        }
                    }

                    if (foreKey != null) {
                        expr.addOuterJoin(table, identitySQL, relTable, foreKey);
                        DTXClassDescriptor relDesc = new DTXClassDescriptor(relMapping);

                        for (int n = 0; n < relFields.length; n++) {
                            FieldMapping relField = relFields[n];
                            Sql relSql = relFields[n].getSql();
                            if (relSql != null) {
                                String relFieldName = relSql.getName()[0];
                                if (relFieldName == null) {
                                    relFieldName = relFields[n].getName();
                                }
                                String relFullName = relTable + "." + relFieldName;

                                BindXml relFieldXml = relFields[n].getBindXml();
                                String node = "element";
                                if (relFieldXml != null) {
                                    node = relFieldXml.getNode().toString();
                                }

                                if (!relFieldName.equals(foreKey)) {
                                    expr.addColumn(relTable, relFieldName);
                                    _cols.put(relTable + "." + relFieldName,
                                            new Integer(++_lastCol));

                                    if (node.equalsIgnoreCase("attribute")) {
                                        relDesc.addAttr(relFullName, relField);
                                    } else if (node.equalsIgnoreCase("element")) {
                                        relDesc.addSimpleElement(relFullName, relField);
                                    } else if (node.equalsIgnoreCase("text")) {
                                        relDesc.setTextCol(relFullName, relField);
                                    }
                                }
                                if (relField.getName().equals(relMapping.getIdentity(0))) {
                                    _ids.add(relTable + "." + relFieldName);
                                    desc.addContained(relTable + "." + relFieldName, relMapping);
                                    _classes.put(relTable + "." + relFieldName, relDesc);
                                }
                            }
View Full Code Here

        if (name.indexOf(".") > 0) {
            name = name.substring(name.indexOf(".") + 1);
        }

        FieldMapping[] fields = clsMapping.getClassChoice().getFieldMapping();
        FieldMapping field = null;

        for (int i = 0; i < fields.length; ++i) {
            if (fields[i].getSql() != null && fields[i].getName().equals(name)) {
                field = fields[i];
                break;
            }
        }

        if (field == null) {
            throw new DTXException("The field " + name + " was not found");
        }

        Sql fieldSql = field.getSql();
        String table = clsMapping.getMapTo().getTable();

        if (value.startsWith("$")) {
            expr.addParameter(table, fieldSql.getName()[0], op);
        } else {
View Full Code Here

     * @return jdo field descriptor for id
     */
    private FieldDescriptor initId(final ClassChoice choice) {
        String idFieldName = "id";
        FieldDescriptorImpl idFieldDescr;
        FieldMapping idFM = new FieldMapping();
        TypeInfo idType = new TypeInfo(java.lang.Integer.class);
        // Set columns required (=not null)
        idType.setRequired(true);
       
        FieldHandler idHandler;
        try {
            idHandler = new FieldHandlerImpl(idFieldName, null, null,
                    Address.class.getMethod("getId", null), Address.class
                            .getMethod("setId", new Class[] { int.class }),
                    idType);
        } catch (SecurityException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1.getMessage());
        } catch (MappingException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1.getMessage());
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1.getMessage());
        }

        // Instantiate title field descriptor
        idFieldDescr = new FieldDescriptorImpl(idFieldName, idType, idHandler, false);
       
        idFieldDescr.addNature(FieldDescriptorJDONature.class.getName());
        FieldDescriptorJDONature idJdoNature = new FieldDescriptorJDONature(idFieldDescr);
       
        idJdoNature.setSQLName(new String[] { idFieldName });
        idJdoNature.setSQLType(new int[] { SQLTypeInfos.javaType2sqlTypeNum(java.lang.Integer.class) });
        idJdoNature.setManyKey(null);
        idJdoNature.setDirtyCheck(false);
        idJdoNature.setReadOnly(false);

        // Set parent class descriptor
        idFieldDescr.setContainingClassDescriptor(this);
        idFieldDescr.setClassDescriptor(this);
        idFieldDescr.setIdentity(true);
       
        idFM.setIdentity(true);
        idFM.setDirect(false);
        idFM.setName("id");
        idFM.setRequired(true);
        idFM.setSetMethod("setId");
        idFM.setGetMethod("getId");
        idFM.setType("integer");

        Sql idSql = new Sql();
        idSql.addName("id");
        idSql.setType("integer");

        idFM.setSql(idSql);

        // Add field mappings
        choice.addFieldMapping(idFM);
        return idFieldDescr;
    }
View Full Code Here

            classChoice = new ClassChoice();
            classMapping.setClassChoice(classChoice);
        }

        //-- create field mapping
        FieldMapping fieldMap = new FieldMapping();
        classChoice.addFieldMapping(fieldMap);
        String fieldName = member.getName();
        if (fieldName.charAt(0) == '_') {
            fieldName = fieldName.substring(1);
        }
        fieldMap.setName(fieldName);
        String className = getClassName(xsType.getJType());
        if (className.equals("byte[]")) {
            className = "bytes";
        }
        fieldMap.setType(className);

        BindXml bindXml = new BindXml();
        fieldMap.setBindXml(bindXml);

        String nodeName = xmlNature.getNodeName();
        if ((nodeName != null) && (!isText)) {
            bindXml.setName(nodeName);
        }

        if (isAttribute) {
            bindXml.setNode(BindXmlNodeType.ATTRIBUTE);
        } else if (isText) {
            bindXml.setNode(BindXmlNodeType.TEXT);
        } else {
            bindXml.setNode(BindXmlNodeType.ELEMENT);
        }

        switch (xsType.getType()) {
            case XSType.IDREF_TYPE :
                bindXml.setReference(true);
                break;
            case XSType.ID_TYPE :
                classMapping.addIdentity(member.getName());
                break;
            case XSType.QNAME_TYPE :
                bindXml.setType("QName");
            default:
                break;
        }

        //-- set any user-specified field handler
        fieldMap.setHandler(member.getXMLFieldHandler());

        //-- container
        if (member.isContainer()) {
            fieldMap.setContainer(true);
        }

        // Handle namespaces.  FieldInfo namespace has higher priority than ClassInfo namespace.
        // TODO Need to add better namespace support to bind-xml element,
        //      it's not very good at the moment
//      nsURI = member.getNamespaceURI();
//      if (nsURI != null) {
//          jsc.add("desc.setNameSpaceURI(\"");
//          jsc.append(nsURI);
//          jsc.append("\");");
//      }
//
//      if (any && member.getNamespaceURI() == null) {
//          nsURI = null;
//      }

        // required
        if (xmlNature.isRequired()) {
            fieldMap.setRequired(true);
        }

        // nillable
        if (member.isNillable()) {
            // TODO Mapping file needs nillable support!
View Full Code Here

            keyGen = _keyGenRegistry.getKeyGenerator(keygenerator.toUpperCase());
        }
        table.setKeyGenerator(keyGen);

        while (ef.hasMoreElements()) {
            FieldMapping fm = (FieldMapping) ef.nextElement();

            // Skip if <sql> tag is not defined and we have no mapping to DB.
            if (fm.getSql() == null) { continue; }

            boolean isFieldIdentity = fm.getIdentity();
            if (!isUseFieldIdentity) {
                isFieldIdentity = _mappingHelper.isIdentity(cm, fm);
            }
           
            // Checke for many-key, many-table definition.
            if (fm.getSql().getManyTable() != null) {
                    // Generate resolving table for many-many relationship
                    addResolveField(fm, cm);
            }
                   
            // Process column creation if sql name is defined.
            String[] sqlnames = fm.getSql().getName();             
            if ((sqlnames != null) && (sqlnames.length > 0)
                    && (fm.getSql().getManyTable() == null)) {
                // Normal case, using sql name as column name.
                String sqltype = fm.getSql().getType();

                TypeInfo typeInfo = null;
                ClassMapping cmRef = null;
                String[] refIdTypes = null;
                boolean isUseReferenceType = false;

                // Get type info.
                if (sqltype != null) {
                    typeInfo = _typeMapper.getType(sqltype);
                }

                // If typeInfo is null, this table has a reference to another one.
                if (typeInfo == null) {
                    cmRef = _mappingHelper.getClassMappingByName(fm.getType());
                    // Use field type if reference class could not be found.
                    if (cmRef == null) {                       
                        typeInfo = _typeMapper.getType(fm.getType());
                       
                        if (typeInfo == null) {
                            throw new TypeNotFoundException("can not resolve type "
                                + fm.getType() + " in class '" + cm.getName() + "'");
                        }
                    } else {
                        isUseReferenceType = true;
                        refIdTypes = _mappingHelper.resolveTypeReferenceForIds(
                                fm.getType());

                        // If number of reference table's Id's differ from number of
                        // field elements.
                        if (refIdTypes.length != sqlnames.length) {
                            throw new TypeNotFoundException(
                                    "number of reference table's Id differs"
                                            + " to number of field elements '"
                                            + fm.getName() + "' of class '"
                                            + cm.getName() + "'"
                                            + refIdTypes.length + "," + sqlnames.length);
                        }
                    }
                }

                // Create fields.
                for (int i = 0; i < sqlnames.length; i++) {
                    Field field = _schemaFactory.createField();
                    field.setConfiguration(_configuration);

                    if (isUseReferenceType) {
                        // Each sqlname correspond to a identity of the reference table.
                        // Should be able to get the original type of the reference
                        // field.
                        typeInfo = _typeMapper.getType(refIdTypes[i]);
                        if (typeInfo == null) {
                            throw new TypeNotFoundException(
                                    "can not find reference type "
                                    + refIdTypes[i] + " of class " + cm.getName());
                        }
                    }

                    // process attributes of field
                    field.setName(sqlnames[i]);
                    field.setTable(table);
                    field.setType(typeInfo);
                    field.setIdentity(isFieldIdentity);
                    field.setRequired(fm.getRequired());
                    field.setKeyGenerator(keyGen);

                    table.addField(field);
                   
                    if (isFieldIdentity) {
View Full Code Here

            keyGen = _keyGenRegistry.getKeyGenerator(keygenerator.toUpperCase());
        }
        table.setKeyGenerator(keyGen);

        while (extendEf.hasMoreElements()) {
            FieldMapping extendFm = (FieldMapping) extendEf.nextElement();

            // Skip if <sql> tag is not defined.
            if (extendFm.getSql() == null) { continue; }

            boolean isFieldIdentity = extendFm.getIdentity();
            if (!isUseFieldIdentity) {
                isFieldIdentity = _mappingHelper.isIdentity(extendCm, extendFm);
            }
           
            // Checke for many-key, many-table definition.
            if (isFieldIdentity && extendFm.getSql().getManyKeyCount() <= 0) {
                // Column is defiend as normal column in child, but it is id which is
                // inherited from parent.
                if (mergeIfDefInBothClasses(table, cm, extendFm)) { continue; }
               
                String[] sqlnames = extendFm.getSql().getName();
                String sqltype = extendFm.getSql().getType();

                TypeInfo typeInfo = null;
                ClassMapping cmRef = null;
                String[] refIdTypes = null;
                boolean isUseReferenceType = false;
               
                if (sqltype != null) {
                    typeInfo = _typeMapper.getType(sqltype);
                }

                // If typeInfo is null, this table has a reference to another one.
                if (typeInfo == null) {
                    cmRef = _mappingHelper.getClassMappingByName(extendFm.getType());
                    // If cmRef is null, the reference class could not be found.
                    if (cmRef == null) {                       
                        typeInfo = _typeMapper.getType(extendFm.getType());
                       
                        if (typeInfo == null) {
                            throw new TypeNotFoundException("can not resolve type "
                                + extendFm.getType());
                        }
                    } else {
                        isUseReferenceType = true;
                        refIdTypes = _mappingHelper.resolveTypeReferenceForIds(extendFm
                                .getType());

                        // If number of reference table's Ids differ from number of
                        // field elements.
                        if (refIdTypes.length != sqlnames.length) {
                            throw new TypeNotFoundException(
                                    "number of reference table's Id differs"
                                            + " to number of field elements '"
                                            + extendFm.getName() + "' of class '"
                                            + extendCm.getName() + "'"
                                            + refIdTypes.length + "," + sqlnames.length);
                        }
                    }
                }
View Full Code Here

    private boolean mergeIfDefInBothClasses(final Table table,
            final ClassMapping cm, final FieldMapping extendFm) {
        Enumeration ef = cm.getClassChoice().enumerateFieldMapping();
       
        while (ef.hasMoreElements()) {
            FieldMapping fm = (FieldMapping) ef.nextElement();
            String fname = fm.getName();
            // If extend field has the same name with one of parent's fields.
            if (fname != null && fname.equalsIgnoreCase(extendFm.getName())) {
                if (fm.getSql() == null) { continue; }
                String[] sqlnames = fm.getSql().getName();
                for (int i = 0; i < sqlnames.length; i++) {
                    table.getField(sqlnames[i]).setIdentity(true);
                }
                return true;
            }
View Full Code Here

            mapto.setTable(fm.getSql().getManyTable());
            resolveCm.setMapTo(mapto);
            _resolveTable.put(fm.getSql().getManyTable(), resolveCm);
        }

        FieldMapping resolveFm = new FieldMapping();
        resolveFm.setIdentity(true);
        resolveFm.setName(cm.getMapTo().getTable());
        resolveFm.setType(cm.getName());

        ClassChoice cc = resolveCm.getClassChoice();
        if (cc == null) {
            cc = new ClassChoice();
            resolveCm.setClassChoice(cc);
        }
        cc.addFieldMapping(resolveFm);

        Sql sql = new Sql();
        String[] sqlname = fm.getSql().getManyKey();
        if (sqlname == null || sqlname.length == 0) {
            _mappingHelper.getClassMappingSqlIdentity(cm, true);
        }
        sql.setName(sqlname);
        resolveFm.setSql(sql);
    }
View Full Code Here

TOP

Related Classes of org.exolab.castor.mapping.xml.FieldMapping

Copyright © 2018 www.massapicom. 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.