Search in sources :

Example 21 with TypeManager

use of org.datanucleus.store.types.TypeManager in project datanucleus-api-jdo by datanucleus.

the class JDOMetaDataHandler method startElement.

/**
 * Handler method called at the start of an element.
 * @param uri URI of the tag
 * @param localName Local name
 * @param qName Element name
 * @param attrs Attributes for this element
 * @throws SAXException in parsing errors
 */
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    if (charactersBuffer.length() > 0) {
        // Cater for subelements that appear before the end of the body text (save the body text with the
        // parent)
        String currentString = getString().trim();
        if (getStack() instanceof QueryMetaData) {
            ((QueryMetaData) getStack()).setQuery(currentString.trim());
        }
    }
    if (localName.length() < 1) {
        localName = qName;
    }
    try {
        if (localName.equals("jdo")) {
            FileMetaData filemd = (FileMetaData) getStack();
            filemd.setType(MetadataFileType.JDO_FILE);
            filemd.setCatalog(getAttr(attrs, "catalog"));
            filemd.setSchema(getAttr(attrs, "schema"));
        } else if (localName.equals("orm")) {
            FileMetaData filemd = (FileMetaData) getStack();
            filemd.setType(MetadataFileType.JDO_ORM_FILE);
            filemd.setCatalog(getAttr(attrs, "catalog"));
            filemd.setSchema(getAttr(attrs, "schema"));
        } else if (localName.equals("jdoquery")) {
            FileMetaData filemd = (FileMetaData) getStack();
            filemd.setType(MetadataFileType.JDO_QUERY_FILE);
        } else if (localName.equals("fetch-plan")) {
            FileMetaData filemd = (FileMetaData) metadata;
            FetchPlanMetaData fpmd = filemd.newFetchPlanMetadata(getAttr(attrs, "name"));
            fpmd.setMaxFetchDepth(getAttr(attrs, "max-fetch-depth"));
            fpmd.setFetchSize(getAttr(attrs, "fetch-size"));
            pushStack(fpmd);
        } else if (localName.equals("package")) {
            FileMetaData filemd = (FileMetaData) getStack();
            PackageMetaData pmd = filemd.newPackageMetadata(getAttr(attrs, "name"));
            pmd.setCatalog(getAttr(attrs, "catalog"));
            pmd.setSchema(getAttr(attrs, "schema"));
            pushStack(pmd);
        } else if (localName.equals("class")) {
            PackageMetaData pmd = (PackageMetaData) getStack();
            ClassMetaData cmd = newClassObject(pmd, attrs);
            pmd.addClass(cmd);
            pushStack(cmd);
        } else if (localName.equals("interface")) {
            PackageMetaData pmd = (PackageMetaData) getStack();
            InterfaceMetaData imd = newInterfaceObject(pmd, attrs);
            pmd.addInterface(imd);
            pushStack(imd);
        } else if (localName.equals("primary-key")) {
            MetaData md = getStack();
            PrimaryKeyMetaData pkmd = new PrimaryKeyMetaData();
            pkmd.setName(getAttr(attrs, "name"));
            pkmd.setColumnName(getAttr(attrs, "column"));
            if (md instanceof AbstractClassMetaData) {
                ((AbstractClassMetaData) md).setPrimaryKeyMetaData(pkmd);
            } else if (md instanceof JoinMetaData) {
                ((JoinMetaData) md).setPrimaryKeyMetaData(pkmd);
            }
            pushStack(pkmd);
        } else if (localName.equals("implements")) {
            ClassMetaData cmd = (ClassMetaData) getStack();
            ImplementsMetaData imd = new ImplementsMetaData(getAttr(attrs, "name"));
            cmd.addImplements(imd);
            pushStack(imd);
        } else if (localName.equals("property")) {
            MetaData parent = getStack();
            if (parent instanceof AbstractClassMetaData) {
                AbstractClassMetaData acmd = (AbstractClassMetaData) parent;
                PropertyMetaData propmd = newPropertyObject(acmd, attrs);
                acmd.addMember(propmd);
                pushStack(propmd);
            } else if (parent instanceof EmbeddedMetaData) {
                EmbeddedMetaData emd = (EmbeddedMetaData) parent;
                PropertyMetaData propmd = newPropertyObject(emd, attrs);
                emd.addMember(propmd);
                pushStack(propmd);
            } else if (parent instanceof ImplementsMetaData) {
                ImplementsMetaData implmd = (ImplementsMetaData) parent;
                PropertyMetaData propmd = newPropertyObject(implmd, attrs);
                implmd.addProperty(propmd);
                pushStack(propmd);
            } else if (parent instanceof FetchGroupMetaData) {
                FetchGroupMetaData fgmd = (FetchGroupMetaData) parent;
                FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(fgmd, getAttr(attrs, "name"));
                fgmmd.setRecursionDepth(getAttr(attrs, "recursion-depth"));
                fgmmd.setProperty();
                fgmd.addMember(fgmmd);
                pushStack(fgmmd);
            }
        } else if (localName.equals("datastore-identity")) {
            AbstractClassMetaData acmd = (AbstractClassMetaData) getStack();
            IdentityMetaData idmd = new IdentityMetaData();
            idmd.setColumnName(getAttr(attrs, "column"));
            idmd.setValueStrategy(ValueGenerationStrategy.getIdentityStrategy(getAttr(attrs, "strategy")));
            idmd.setSequence(getAttr(attrs, "sequence"));
            acmd.setIdentityMetaData(idmd);
            pushStack(idmd);
        } else if (localName.equals("inheritance")) {
            MetaData parent = getStack();
            AbstractClassMetaData acmd = (AbstractClassMetaData) parent;
            InheritanceMetaData inhmd = new InheritanceMetaData();
            inhmd.setStrategy(getAttr(attrs, "strategy"));
            acmd.setInheritanceMetaData(inhmd);
            pushStack(inhmd);
        } else if (localName.equals("discriminator")) {
            MetaData md = getStack();
            if (md instanceof InheritanceMetaData) {
                InheritanceMetaData inhmd = (InheritanceMetaData) md;
                DiscriminatorMetaData dismd = inhmd.newDiscriminatorMetadata();
                dismd.setColumnName(getAttr(attrs, "column"));
                dismd.setValue(getAttr(attrs, "value"));
                dismd.setStrategy(getAttr(attrs, "strategy"));
                dismd.setIndexed(getAttr(attrs, "indexed"));
                pushStack(dismd);
            } else if (md instanceof EmbeddedMetaData) {
                EmbeddedMetaData embmd = (EmbeddedMetaData) md;
                DiscriminatorMetaData dismd = embmd.newDiscriminatorMetadata();
                dismd.setColumnName(getAttr(attrs, "column"));
                dismd.setValue(getAttr(attrs, "value"));
                dismd.setStrategy(getAttr(attrs, "strategy"));
                dismd.setIndexed(getAttr(attrs, "indexed"));
                pushStack(dismd);
            }
        } else if (localName.equals("query")) {
            MetaData emd = getStack();
            String name = getAttr(attrs, "name");
            String lang = getAttr(attrs, "language");
            if (!StringUtils.isWhitespace(lang)) {
                if (// Convert to JDOQL
                lang.equals(JDOQuery.JDOQL_QUERY_LANGUAGE)) {
                    lang = QueryLanguage.JDOQL.toString();
                } else if (// Convert to SQL
                lang.equals(JDOQuery.SQL_QUERY_LANGUAGE)) {
                    lang = QueryLanguage.SQL.toString();
                } else if (// Convert to JPQL
                lang.equals(JDOQuery.JPQL_QUERY_LANGUAGE)) {
                    lang = QueryLanguage.JPQL.toString();
                }
            }
            if (emd instanceof ClassMetaData) {
                ClassMetaData cmd = (ClassMetaData) emd;
                if (StringUtils.isWhitespace(name)) {
                    throw new InvalidClassMetaDataException("044154", cmd.getFullClassName());
                }
                QueryMetaData qmd = new QueryMetaData(name);
                qmd.setScope(cmd.getFullClassName());
                qmd.setLanguage(lang);
                qmd.setUnmodifiable(getAttr(attrs, "unmodifiable"));
                qmd.setResultClass(getAttr(attrs, "result-class"));
                qmd.setUnique(getAttr(attrs, "unique"));
                qmd.setFetchPlanName(getAttr(attrs, "fetch-plan"));
                cmd.addQuery(qmd);
                pushStack(qmd);
            } else if (emd instanceof InterfaceMetaData) {
                InterfaceMetaData imd = (InterfaceMetaData) emd;
                if (StringUtils.isWhitespace(name)) {
                    throw new InvalidClassMetaDataException("044154", imd.getFullClassName());
                }
                QueryMetaData qmd = new QueryMetaData(name);
                qmd.setScope(imd.getFullClassName());
                qmd.setLanguage(lang);
                qmd.setUnmodifiable(getAttr(attrs, "unmodifiable"));
                qmd.setResultClass(getAttr(attrs, "result-class"));
                qmd.setUnique(getAttr(attrs, "unique"));
                qmd.setFetchPlanName(getAttr(attrs, "fetch-plan"));
                imd.addQuery(qmd);
                pushStack(qmd);
            } else if (emd instanceof FileMetaData) {
                FileMetaData filemd = (FileMetaData) emd;
                QueryMetaData qmd = filemd.newQueryMetadata(name);
                qmd.setLanguage(lang);
                qmd.setUnmodifiable(getAttr(attrs, "unmodifiable"));
                qmd.setResultClass(getAttr(attrs, "result-class"));
                qmd.setUnique(getAttr(attrs, "unique"));
                qmd.setFetchPlanName(getAttr(attrs, "fetch-plan"));
                pushStack(qmd);
            }
        } else if (localName.equals("sequence")) {
            PackageMetaData pmd = (PackageMetaData) getStack();
            SequenceMetaData seqmd = pmd.newSequenceMetadata(getAttr(attrs, "name"), getAttr(attrs, "strategy"));
            seqmd.setFactoryClass(getAttr(attrs, "factory-class"));
            seqmd.setDatastoreSequence(getAttr(attrs, "datastore-sequence"));
            String seqSize = getAttr(attrs, "allocation-size");
            if (seqSize != null) {
                seqmd.setAllocationSize(seqSize);
            }
            String seqStart = getAttr(attrs, "initial-value");
            if (seqStart != null) {
                seqmd.setInitialValue(seqStart);
            }
            pushStack(seqmd);
        } else if (localName.equals("field")) {
            MetaData md = getStack();
            if (md instanceof FetchGroupMetaData) {
                FetchGroupMetaData fgmd = (FetchGroupMetaData) md;
                FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(md, getAttr(attrs, "name"));
                fgmmd.setRecursionDepth(getAttr(attrs, "recursion-depth"));
                fgmd.addMember(fgmmd);
                pushStack(fgmmd);
                return;
            }
            FieldMetaData fmd = newFieldObject(md, attrs);
            if (md instanceof ClassMetaData) {
                ClassMetaData cmd = (ClassMetaData) md;
                cmd.addMember(fmd);
            } else if (md instanceof EmbeddedMetaData) {
                EmbeddedMetaData emd = (EmbeddedMetaData) md;
                emd.addMember(fmd);
            } else if (md instanceof ForeignKeyMetaData) {
                ForeignKeyMetaData fkmd = (ForeignKeyMetaData) md;
                fkmd.addMember(fmd.getName());
            } else if (md instanceof IndexMetaData) {
                IndexMetaData imd = (IndexMetaData) md;
                imd.addMember(fmd.getName());
            } else if (md instanceof UniqueMetaData) {
                UniqueMetaData umd = (UniqueMetaData) md;
                umd.addMember(fmd.getName());
            }
            pushStack(fmd);
        } else if (localName.equals("join")) {
            MetaData parent = getStack();
            String tableName = getAttr(attrs, "table");
            String columnName = getAttr(attrs, "column");
            String outer = getAttr(attrs, "outer");
            IndexedValue indexed = IndexedValue.getIndexedValue(getAttr(attrs, "indexed"));
            String unique = getAttr(attrs, "unique");
            String deleteAction = getAttr(attrs, "delete-action");
            JoinMetaData joinmd = null;
            if (parent instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) parent;
                joinmd = fmd.newJoinMetaData();
            } else if (parent instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) parent;
                joinmd = new JoinMetaData();
                cmd.addJoin(joinmd);
            } else if (parent instanceof InheritanceMetaData) {
                InheritanceMetaData inhmd = (InheritanceMetaData) parent;
                joinmd = inhmd.newJoinMetadata();
            } else {
                throw new NucleusUserException("Error processing JDO XML metadata. Found \"join\" with parent " + StringUtils.toJVMIDString(parent) + " - not supported");
            }
            joinmd.setTable(tableName);
            joinmd.setColumnName(columnName);
            joinmd.setOuter(MetaDataUtils.getBooleanForString(outer, false));
            joinmd.setIndexed(indexed);
            joinmd.setUnique(unique);
            joinmd.setDeleteAction(deleteAction);
            pushStack(joinmd);
        } else if (localName.equals("map")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            MapMetaData mapmd = fmd.newMapMetaData();
            mapmd.setKeyType(getAttr(attrs, "key-type"));
            String embKeyStr = getAttr(attrs, "embedded-key");
            if (!StringUtils.isWhitespace(embKeyStr)) {
                mapmd.setEmbeddedKey(Boolean.valueOf(embKeyStr));
            }
            String serKeyStr = getAttr(attrs, "serialized-key");
            if (!StringUtils.isWhitespace(serKeyStr)) {
                mapmd.setSerializedKey(Boolean.valueOf(serKeyStr));
            }
            String depKeyStr = getAttr(attrs, "dependent-key");
            if (!StringUtils.isWhitespace(depKeyStr)) {
                mapmd.setDependentKey(Boolean.valueOf(depKeyStr));
            }
            mapmd.setValueType(getAttr(attrs, "value-type"));
            String embValStr = getAttr(attrs, "embedded-value");
            if (!StringUtils.isWhitespace(embValStr)) {
                mapmd.setEmbeddedValue(Boolean.valueOf(embValStr));
            }
            String serValStr = getAttr(attrs, "serialized-value");
            if (!StringUtils.isWhitespace(serValStr)) {
                mapmd.setSerializedValue(Boolean.valueOf(serValStr));
            }
            String depValStr = getAttr(attrs, "dependent-value");
            if (!StringUtils.isWhitespace(depValStr)) {
                mapmd.setDependentValue(Boolean.valueOf(depValStr));
            }
            pushStack(mapmd);
        } else if (localName.equals("array")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            ArrayMetaData arrmd = fmd.newArrayMetaData();
            arrmd.setElementType(getAttr(attrs, "element-type"));
            String embElemStr = getAttr(attrs, "embedded-element");
            if (!StringUtils.isWhitespace(embElemStr)) {
                arrmd.setEmbeddedElement(Boolean.valueOf(embElemStr));
            }
            String serElemStr = getAttr(attrs, "serialized-element");
            if (!StringUtils.isWhitespace(serElemStr)) {
                arrmd.setSerializedElement(Boolean.valueOf(serElemStr));
            }
            String depElemStr = getAttr(attrs, "dependent-element");
            if (!StringUtils.isWhitespace(depElemStr)) {
                arrmd.setDependentElement(Boolean.valueOf(depElemStr));
            }
            pushStack(arrmd);
        } else if (localName.equals("collection")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            CollectionMetaData collmd = fmd.newCollectionMetaData();
            collmd.setElementType(getAttr(attrs, "element-type"));
            String embElemStr = getAttr(attrs, "embedded-element");
            if (!StringUtils.isWhitespace(embElemStr)) {
                collmd.setEmbeddedElement(Boolean.valueOf(embElemStr));
            }
            String serElemStr = getAttr(attrs, "serialized-element");
            if (!StringUtils.isWhitespace(serElemStr)) {
                collmd.setSerializedElement(Boolean.valueOf(serElemStr));
            }
            String depElemStr = getAttr(attrs, "dependent-element");
            if (!StringUtils.isWhitespace(depElemStr)) {
                collmd.setDependentElement(Boolean.valueOf(depElemStr));
            }
            pushStack(collmd);
        } else if (localName.equals("column")) {
            MetaData md = getStack();
            ColumnMetaData colmd = new ColumnMetaData();
            colmd.setName(getAttr(attrs, "name"));
            colmd.setTarget(getAttr(attrs, "target"));
            colmd.setTargetMember(getAttr(attrs, "target-field"));
            colmd.setJdbcType(getAttr(attrs, "jdbc-type"));
            colmd.setSqlType(getAttr(attrs, "sql-type"));
            colmd.setLength(getAttr(attrs, "length"));
            colmd.setScale(getAttr(attrs, "scale"));
            colmd.setAllowsNull(getAttr(attrs, "allows-null"));
            colmd.setDefaultValue(getAttr(attrs, "default-value"));
            colmd.setInsertValue(getAttr(attrs, "insert-value"));
            // JDO 3.1+
            String pos = getAttr(attrs, "position");
            if (pos != null) {
                colmd.setPosition(pos);
            }
            if (md instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) md;
                fmd.addColumn(colmd);
            } else if (md instanceof AbstractElementMetaData) {
                AbstractElementMetaData elemd = (AbstractElementMetaData) md;
                elemd.addColumn(colmd);
            } else if (md instanceof JoinMetaData) {
                JoinMetaData jnmd = (JoinMetaData) md;
                jnmd.addColumn(colmd);
            } else if (md instanceof IdentityMetaData) {
                IdentityMetaData idmd = (IdentityMetaData) md;
                idmd.setColumnMetaData(colmd);
            } else if (md instanceof ForeignKeyMetaData) {
                ForeignKeyMetaData fkmd = (ForeignKeyMetaData) md;
                fkmd.addColumn(colmd);
            } else if (md instanceof IndexMetaData) {
                IndexMetaData idxmd = (IndexMetaData) md;
                idxmd.addColumn(colmd.getName());
            } else if (md instanceof UniqueMetaData) {
                UniqueMetaData unimd = (UniqueMetaData) md;
                unimd.addColumn(colmd.getName());
            } else if (md instanceof OrderMetaData) {
                OrderMetaData ormd = (OrderMetaData) md;
                ormd.addColumn(colmd);
            } else if (md instanceof DiscriminatorMetaData) {
                DiscriminatorMetaData dismd = (DiscriminatorMetaData) md;
                dismd.setColumnMetaData(colmd);
            } else if (md instanceof VersionMetaData) {
                VersionMetaData vermd = (VersionMetaData) md;
                vermd.setColumnMetaData(colmd);
            } else if (md instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) md;
                cmd.addUnmappedColumn(colmd);
            } else if (md instanceof PrimaryKeyMetaData) {
                PrimaryKeyMetaData pkmd = (PrimaryKeyMetaData) md;
                pkmd.addColumn(colmd);
            }
            pushStack(colmd);
        } else if (localName.equals("element")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            ElementMetaData elemmd = new ElementMetaData();
            elemmd.setTable(getAttr(attrs, "table"));
            elemmd.setColumnName(getAttr(attrs, "column"));
            elemmd.setDeleteAction(getAttr(attrs, "delete-action"));
            elemmd.setUpdateAction(getAttr(attrs, "update-action"));
            elemmd.setIndexed(IndexedValue.getIndexedValue(getAttr(attrs, "indexed")));
            elemmd.setUnique(MetaDataUtils.getBooleanForString(getAttr(attrs, "unique"), false));
            String mappedBy = getAttr(attrs, "mapped-by");
            elemmd.setMappedBy(mappedBy);
            if (!StringUtils.isWhitespace(mappedBy) && fmd.getMappedBy() == null) {
                // With collection/array this is the same as mapped-by on the field
                fmd.setMappedBy(mappedBy);
            }
            String converterAttr = getAttr(attrs, "converter");
            String disableConverterAttr = getAttr(attrs, "use-default-conversion");
            if (disableConverterAttr != null && Boolean.getBoolean(disableConverterAttr)) {
            // TODO Disable on the element?
            } else if (!StringUtils.isWhitespace(converterAttr)) {
                TypeManager typeMgr = mmgr.getNucleusContext().getTypeManager();
                ClassLoaderResolver clr = mmgr.getNucleusContext().getClassLoaderResolver(null);
                Class converterCls = clr.classForName(converterAttr);
                if (typeMgr.getTypeConverterForName(converterCls.getName()) == null) {
                    // Not yet cached an instance of this converter so create one
                    AttributeConverter conv = JDOTypeConverterUtils.createAttributeConverter((PersistenceNucleusContext) mmgr.getNucleusContext(), converterCls);
                    // TODO element type
                    Class attrType = JDOTypeConverterUtils.getAttributeTypeForAttributeConverter(converterCls, null);
                    Class dbType = JDOTypeConverterUtils.getDatastoreTypeForAttributeConverter(converterCls, attrType, null);
                    // Register the TypeConverter under the name of the AttributeConverter class
                    JDOTypeConverter typeConv = new JDOTypeConverter(conv);
                    typeMgr.registerConverter(converterAttr, typeConv, attrType, dbType, false, null);
                }
                elemmd.addExtension(MetaData.EXTENSION_MEMBER_TYPE_CONVERTER_NAME, converterAttr);
            }
            fmd.setElementMetaData(elemmd);
            pushStack(elemmd);
        } else if (localName.equals("key")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            KeyMetaData keymd = new KeyMetaData();
            keymd.setTable(getAttr(attrs, "table"));
            keymd.setColumnName(getAttr(attrs, "column"));
            keymd.setDeleteAction(getAttr(attrs, "delete-action"));
            keymd.setUpdateAction(getAttr(attrs, "update-action"));
            keymd.setIndexed(IndexedValue.getIndexedValue(getAttr(attrs, "indexed")));
            keymd.setUnique(MetaDataUtils.getBooleanForString(getAttr(attrs, "unique"), false));
            keymd.setMappedBy(getAttr(attrs, "mapped-by"));
            String converterAttr = getAttr(attrs, "converter");
            String disableConverterAttr = getAttr(attrs, "use-default-conversion");
            if (disableConverterAttr != null && Boolean.getBoolean(disableConverterAttr)) {
            // TODO Disable on the key?
            } else if (!StringUtils.isWhitespace(converterAttr)) {
                TypeManager typeMgr = mmgr.getNucleusContext().getTypeManager();
                ClassLoaderResolver clr = mmgr.getNucleusContext().getClassLoaderResolver(null);
                Class converterCls = clr.classForName(converterAttr);
                if (typeMgr.getTypeConverterForName(converterCls.getName()) == null) {
                    // Not yet cached an instance of this converter so create one
                    AttributeConverter conv = JDOTypeConverterUtils.createAttributeConverter((PersistenceNucleusContext) mmgr.getNucleusContext(), converterCls);
                    // TODO key type
                    Class attrType = JDOTypeConverterUtils.getAttributeTypeForAttributeConverter(converterCls, null);
                    Class dbType = JDOTypeConverterUtils.getDatastoreTypeForAttributeConverter(converterCls, attrType, null);
                    // Register the TypeConverter under the name of the AttributeConverter class
                    JDOTypeConverter typeConv = new JDOTypeConverter(conv);
                    typeMgr.registerConverter(converterAttr, typeConv, attrType, dbType, false, null);
                }
                keymd.addExtension(MetaData.EXTENSION_MEMBER_TYPE_CONVERTER_NAME, converterAttr);
            }
            fmd.setKeyMetaData(keymd);
            pushStack(keymd);
        } else // New value
        if (localName.equals("value")) {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            ValueMetaData valuemd = new ValueMetaData();
            valuemd.setTable(getAttr(attrs, "table"));
            valuemd.setColumnName(getAttr(attrs, "column"));
            valuemd.setDeleteAction(getAttr(attrs, "delete-action"));
            valuemd.setUpdateAction(getAttr(attrs, "update-action"));
            valuemd.setIndexed(IndexedValue.getIndexedValue(getAttr(attrs, "indexed")));
            valuemd.setUnique(MetaDataUtils.getBooleanForString(getAttr(attrs, "unique"), false));
            valuemd.setMappedBy(getAttr(attrs, "mapped-by"));
            String converterAttr = getAttr(attrs, "converter");
            String disableConverterAttr = getAttr(attrs, "use-default-conversion");
            if (disableConverterAttr != null && Boolean.getBoolean(disableConverterAttr)) {
            // TODO Disable on the value?
            } else if (!StringUtils.isWhitespace(converterAttr)) {
                TypeManager typeMgr = mmgr.getNucleusContext().getTypeManager();
                ClassLoaderResolver clr = mmgr.getNucleusContext().getClassLoaderResolver(null);
                Class converterCls = clr.classForName(converterAttr);
                if (typeMgr.getTypeConverterForName(converterCls.getName()) == null) {
                    // Not yet cached an instance of this converter so create one
                    AttributeConverter conv = JDOTypeConverterUtils.createAttributeConverter((PersistenceNucleusContext) mmgr.getNucleusContext(), converterCls);
                    // TODO value type
                    Class attrType = JDOTypeConverterUtils.getAttributeTypeForAttributeConverter(converterCls, null);
                    Class dbType = JDOTypeConverterUtils.getDatastoreTypeForAttributeConverter(converterCls, attrType, null);
                    // Register the TypeConverter under the name of the AttributeConverter class
                    JDOTypeConverter typeConv = new JDOTypeConverter(conv);
                    typeMgr.registerConverter(converterAttr, typeConv, attrType, dbType, false, null);
                }
                valuemd.addExtension(MetaData.EXTENSION_MEMBER_TYPE_CONVERTER_NAME, converterAttr);
            }
            fmd.setValueMetaData(valuemd);
            pushStack(valuemd);
        } else // New fetch-group
        if (localName.equals("fetch-group")) {
            MetaData md = getStack();
            FetchGroupMetaData fgmd = new FetchGroupMetaData(getAttr(attrs, "name"));
            String postLoadStr = getAttr(attrs, "post-load");
            if (!StringUtils.isWhitespace(postLoadStr)) {
                fgmd.setPostLoad(Boolean.valueOf(postLoadStr));
            }
            if (md instanceof FetchGroupMetaData) {
                FetchGroupMetaData fgmdParent = (FetchGroupMetaData) md;
                fgmdParent.addFetchGroup(fgmd);
            } else if (md instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) md;
                cmd.addFetchGroup(fgmd);
            } else if (md instanceof FetchPlanMetaData) {
                FetchPlanMetaData fpmd = (FetchPlanMetaData) md;
                fpmd.addFetchGroup(fgmd);
            }
            pushStack(fgmd);
        } else if (localName.equals("extension")) {
            MetaData md = getStack();
            String vendorName = getAttr(attrs, "vendor-name");
            if (StringUtils.isWhitespace(vendorName)) {
                throw new InvalidMetaDataException("044160", vendorName, getAttr(attrs, "key"), getAttr(attrs, "value"));
            }
            if (vendorName != null && vendorName.equalsIgnoreCase(MetaData.VENDOR_NAME)) {
                md.addExtension(getAttr(attrs, "key"), getAttr(attrs, "value"));
            }
        } else if (localName.equals("version")) {
            AbstractClassMetaData cmd = (AbstractClassMetaData) getStack();
            VersionMetaData vermd = cmd.newVersionMetadata();
            String strategy = getAttr(attrs, "strategy");
            if (!StringUtils.isWhitespace(strategy)) {
                vermd.setStrategy(strategy);
            }
            vermd.setColumnName(getAttr(attrs, "column"));
            vermd.setIndexed(IndexedValue.getIndexedValue(getAttr(attrs, "indexed")));
            pushStack(vermd);
        } else if (localName.equals("index")) {
            MetaData md = getStack();
            IndexMetaData idxmd = new IndexMetaData();
            idxmd.setName(getAttr(attrs, "name"));
            idxmd.setTable(getAttr(attrs, "table"));
            String uniStr = getAttr(attrs, "unique");
            if (!StringUtils.isWhitespace(uniStr)) {
                idxmd.setUnique(Boolean.valueOf(uniStr));
            }
            if (md instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) md;
                cmd.addIndex(idxmd);
            } else if (md instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) md;
                fmd.setIndexMetaData(idxmd);
            } else if (md instanceof JoinMetaData) {
                JoinMetaData jmd = (JoinMetaData) md;
                jmd.setIndexMetaData(idxmd);
            } else if (md instanceof AbstractElementMetaData) {
                AbstractElementMetaData elmd = (AbstractElementMetaData) md;
                elmd.setIndexMetaData(idxmd);
            } else if (md instanceof OrderMetaData) {
                OrderMetaData omd = (OrderMetaData) md;
                omd.setIndexMetaData(idxmd);
            } else if (md instanceof VersionMetaData) {
                VersionMetaData vermd = (VersionMetaData) md;
                vermd.setIndexMetaData(idxmd);
            } else if (md instanceof DiscriminatorMetaData) {
                DiscriminatorMetaData dismd = (DiscriminatorMetaData) md;
                dismd.setIndexMetaData(idxmd);
            }
            pushStack(idxmd);
        } else if (localName.equals("unique")) {
            MetaData md = getStack();
            UniqueMetaData unimd = new UniqueMetaData();
            unimd.setName(getAttr(attrs, "name"));
            unimd.setTable(getAttr(attrs, "table"));
            String defStr = getAttr(attrs, "deferred");
            if (!StringUtils.isWhitespace(defStr)) {
                unimd.setDeferred(Boolean.valueOf(defStr));
            }
            if (md instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) md;
                cmd.addUniqueConstraint(unimd);
            } else if (md instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) md;
                fmd.setUniqueMetaData(unimd);
            } else if (md instanceof JoinMetaData) {
                JoinMetaData jmd = (JoinMetaData) md;
                jmd.setUniqueMetaData(unimd);
            } else if (md instanceof AbstractElementMetaData) {
                AbstractElementMetaData elmd = (AbstractElementMetaData) md;
                elmd.setUniqueMetaData(unimd);
            }
            pushStack(unimd);
        } else if (localName.equals("foreign-key")) {
            MetaData md = getStack();
            ForeignKeyMetaData fkmd = new ForeignKeyMetaData();
            fkmd.setName(getAttr(attrs, "name"));
            fkmd.setTable(getAttr(attrs, "table"));
            fkmd.setUnique(getAttr(attrs, "unique"));
            fkmd.setDeferred(getAttr(attrs, "deferred"));
            fkmd.setDeleteAction(ForeignKeyAction.getForeignKeyAction(getAttr(attrs, "delete-action")));
            fkmd.setUpdateAction(ForeignKeyAction.getForeignKeyAction(getAttr(attrs, "update-action")));
            if (md instanceof AbstractClassMetaData) {
                AbstractClassMetaData cmd = (AbstractClassMetaData) md;
                cmd.addForeignKey(fkmd);
            } else if (md instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) md;
                fmd.setForeignKeyMetaData(fkmd);
            } else if (md instanceof JoinMetaData) {
                JoinMetaData jmd = (JoinMetaData) md;
                jmd.setForeignKeyMetaData(fkmd);
            } else if (md instanceof AbstractElementMetaData) {
                AbstractElementMetaData elmd = (AbstractElementMetaData) md;
                elmd.setForeignKeyMetaData(fkmd);
            }
            pushStack(fkmd);
        } else if (localName.equals("order")) {
            OrderMetaData ordmd = new OrderMetaData();
            ordmd.setIndexed(IndexedValue.getIndexedValue(getAttr(attrs, "indexed")));
            ordmd.setColumnName(getAttr(attrs, "column"));
            ordmd.setMappedBy(getAttr(attrs, "mapped-by"));
            AbstractMemberMetaData fmd = (AbstractMemberMetaData) getStack();
            fmd.setOrderMetaData(ordmd);
            pushStack(ordmd);
        } else if (localName.equals("embedded")) {
            MetaData md = getStack();
            EmbeddedMetaData embmd = new EmbeddedMetaData();
            embmd.setOwnerMember(getAttr(attrs, "owner-field"));
            embmd.setNullIndicatorColumn(getAttr(attrs, "null-indicator-column"));
            embmd.setNullIndicatorValue(getAttr(attrs, "null-indicator-value"));
            if (md instanceof AbstractMemberMetaData) {
                AbstractMemberMetaData fmd = (AbstractMemberMetaData) md;
                fmd.setEmbeddedMetaData(embmd);
            } else if (md instanceof KeyMetaData) {
                KeyMetaData kmd = (KeyMetaData) md;
                kmd.setEmbeddedMetaData(embmd);
            } else if (md instanceof ValueMetaData) {
                ValueMetaData vmd = (ValueMetaData) md;
                vmd.setEmbeddedMetaData(embmd);
            } else if (md instanceof ElementMetaData) {
                ElementMetaData elmd = (ElementMetaData) md;
                elmd.setEmbeddedMetaData(embmd);
            }
            pushStack(embmd);
        } else {
            String message = Localiser.msg("044037", qName);
            NucleusLogger.METADATA.error(message);
            throw new RuntimeException(message);
        }
    } catch (RuntimeException ex) {
        NucleusLogger.METADATA.error(Localiser.msg("044042", qName, getStack(), uri), ex);
        throw ex;
    }
}
Also used : InvalidMetaDataException(org.datanucleus.metadata.InvalidMetaDataException) VersionMetaData(org.datanucleus.metadata.VersionMetaData) ElementMetaData(org.datanucleus.metadata.ElementMetaData) AbstractElementMetaData(org.datanucleus.metadata.AbstractElementMetaData) JDOTypeConverter(org.datanucleus.api.jdo.JDOTypeConverter) FetchPlanMetaData(org.datanucleus.metadata.FetchPlanMetaData) CollectionMetaData(org.datanucleus.metadata.CollectionMetaData) ImplementsMetaData(org.datanucleus.metadata.ImplementsMetaData) IdentityMetaData(org.datanucleus.metadata.IdentityMetaData) InheritanceMetaData(org.datanucleus.metadata.InheritanceMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData) OrderMetaData(org.datanucleus.metadata.OrderMetaData) AttributeConverter(javax.jdo.AttributeConverter) InvalidClassMetaDataException(org.datanucleus.metadata.InvalidClassMetaDataException) FieldMetaData(org.datanucleus.metadata.FieldMetaData) CollectionMetaData(org.datanucleus.metadata.CollectionMetaData) ElementMetaData(org.datanucleus.metadata.ElementMetaData) FetchPlanMetaData(org.datanucleus.metadata.FetchPlanMetaData) IdentityMetaData(org.datanucleus.metadata.IdentityMetaData) JoinMetaData(org.datanucleus.metadata.JoinMetaData) MetaData(org.datanucleus.metadata.MetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) UniqueMetaData(org.datanucleus.metadata.UniqueMetaData) KeyMetaData(org.datanucleus.metadata.KeyMetaData) PrimaryKeyMetaData(org.datanucleus.metadata.PrimaryKeyMetaData) FetchGroupMetaData(org.datanucleus.metadata.FetchGroupMetaData) InterfaceMetaData(org.datanucleus.metadata.InterfaceMetaData) PackageMetaData(org.datanucleus.metadata.PackageMetaData) EmbeddedMetaData(org.datanucleus.metadata.EmbeddedMetaData) InheritanceMetaData(org.datanucleus.metadata.InheritanceMetaData) OrderMetaData(org.datanucleus.metadata.OrderMetaData) FetchGroupMemberMetaData(org.datanucleus.metadata.FetchGroupMemberMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData) FieldMetaData(org.datanucleus.metadata.FieldMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) ImplementsMetaData(org.datanucleus.metadata.ImplementsMetaData) VersionMetaData(org.datanucleus.metadata.VersionMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData) QueryMetaData(org.datanucleus.metadata.QueryMetaData) AbstractElementMetaData(org.datanucleus.metadata.AbstractElementMetaData) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) ArrayMetaData(org.datanucleus.metadata.ArrayMetaData) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) MapMetaData(org.datanucleus.metadata.MapMetaData) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) PropertyMetaData(org.datanucleus.metadata.PropertyMetaData) IndexMetaData(org.datanucleus.metadata.IndexMetaData) ForeignKeyMetaData(org.datanucleus.metadata.ForeignKeyMetaData) ValueMetaData(org.datanucleus.metadata.ValueMetaData) ValueMetaData(org.datanucleus.metadata.ValueMetaData) ForeignKeyMetaData(org.datanucleus.metadata.ForeignKeyMetaData) AbstractElementMetaData(org.datanucleus.metadata.AbstractElementMetaData) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) KeyMetaData(org.datanucleus.metadata.KeyMetaData) PrimaryKeyMetaData(org.datanucleus.metadata.PrimaryKeyMetaData) ForeignKeyMetaData(org.datanucleus.metadata.ForeignKeyMetaData) PackageMetaData(org.datanucleus.metadata.PackageMetaData) FetchGroupMemberMetaData(org.datanucleus.metadata.FetchGroupMemberMetaData) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) EmbeddedMetaData(org.datanucleus.metadata.EmbeddedMetaData) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) PropertyMetaData(org.datanucleus.metadata.PropertyMetaData) UniqueMetaData(org.datanucleus.metadata.UniqueMetaData) MapMetaData(org.datanucleus.metadata.MapMetaData) PrimaryKeyMetaData(org.datanucleus.metadata.PrimaryKeyMetaData) IndexedValue(org.datanucleus.metadata.IndexedValue) IndexMetaData(org.datanucleus.metadata.IndexMetaData) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) QueryMetaData(org.datanucleus.metadata.QueryMetaData) ArrayMetaData(org.datanucleus.metadata.ArrayMetaData) PersistenceNucleusContext(org.datanucleus.PersistenceNucleusContext) TypeManager(org.datanucleus.store.types.TypeManager) InterfaceMetaData(org.datanucleus.metadata.InterfaceMetaData) JoinMetaData(org.datanucleus.metadata.JoinMetaData) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) FetchGroupMetaData(org.datanucleus.metadata.FetchGroupMetaData)

Example 22 with TypeManager

use of org.datanucleus.store.types.TypeManager in project datanucleus-core by datanucleus.

the class AbstractMemberMetaData method populate.

/**
 * Method to provide the details of the field being represented by this MetaData hence populating
 * certain parts of the MetaData. This is used to firstly provide defaults for attributes that aren't
 * specified in the MetaData, and secondly to report any errors with attributes that have been specifed
 * that are inconsistent with the field being represented.
 * Either a field or a method should be passed in (one or the other) depending on what is being represented
 * by this "member".
 * @param clr ClassLoaderResolver to use for any class loading
 * @param field Field that we are representing (if it's a field)
 * @param method Method(property) that we are representing (if it's a method).
 * @param primary the primary ClassLoader to use (or null)
 * @param mmgr MetaData manager
 */
public synchronized void populate(ClassLoaderResolver clr, Field field, Method method, ClassLoader primary, MetaDataManager mmgr) {
    if (isPopulated() || isInitialised()) {
        return;
    }
    // Set defaults for cascading when not yet set
    ApiAdapter apiAdapter = mmgr.getNucleusContext().getApiAdapter();
    if (cascadePersist == null) {
        cascadePersist = apiAdapter.getDefaultCascadePersistForField();
    }
    if (cascadeUpdate == null) {
        cascadeUpdate = apiAdapter.getDefaultCascadeUpdateForField();
    }
    if (cascadeDelete == null) {
        cascadeDelete = apiAdapter.getDefaultCascadeDeleteForField();
    }
    if (cascadeDetach == null) {
        cascadeDetach = apiAdapter.getDefaultCascadeDetachForField();
    }
    if (cascadeRefresh == null) {
        cascadeRefresh = apiAdapter.getDefaultCascadeRefreshForField();
    }
    if (field == null && method == null) {
        NucleusLogger.METADATA.error(Localiser.msg("044106", getClassName(), getName()));
        throw new InvalidMemberMetaDataException("044106", getClassName(), getName());
    }
    // No class loader, so use System
    if (clr == null) {
        NucleusLogger.METADATA.warn(Localiser.msg("044067", name, getClassName(true)));
        clr = mmgr.getNucleusContext().getClassLoaderResolver(null);
    }
    memberRepresented = field != null ? field : method;
    if (type == null) {
        // Type not yet set so set from field/method (will only be set if we are imposing the type due to Java generics TypeVariable usage)
        if (field != null) {
            this.type = field.getType();
        } else if (method != null) {
            this.type = method.getReturnType();
        }
    }
    if (className != null) {
        // Property is overriding a superclass property, so check that it is valid
        Class thisClass = null;
        if (parent instanceof EmbeddedMetaData) {
            // <embedded> is contained in a <field>, <element>, <key>, <value>
            // but could be multiple levels deep so adopt a generic strategy for finding the parent class
            MetaData superMd = parent.getParent();
            thisClass = ((AbstractMemberMetaData) superMd).getType();
        } else {
            // Overriding field in a superclass of this class
            try {
                thisClass = clr.classForName(getAbstractClassMetaData().getPackageName() + "." + getAbstractClassMetaData().getName());
            } catch (ClassNotResolvedException cnre) {
            // Do nothing
            }
        }
        Class fieldClass = null;
        try {
            fieldClass = clr.classForName(className);
        } catch (ClassNotResolvedException cnre) {
            try {
                fieldClass = clr.classForName(getAbstractClassMetaData().getPackageName() + "." + className);
                className = getAbstractClassMetaData().getPackageName() + "." + className;
            } catch (ClassNotResolvedException cnre2) {
                NucleusLogger.METADATA.error(Localiser.msg("044113", getClassName(), getName(), className));
                NucleusException ne = new InvalidMemberMetaDataException("044113", getClassName(), getName(), className);
                ne.setNestedException(cnre);
                throw ne;
            }
        }
        if (fieldClass != null && !fieldClass.isAssignableFrom(thisClass)) {
            // TODO We could also check if persistable, but won't work when enhancing
            NucleusLogger.METADATA.error(Localiser.msg("044114", getClassName(), getName(), className));
            throw new InvalidMemberMetaDataException("044114", getClassName(), getName(), className);
        }
    }
    if (primaryKey == null) {
        // Primary key not set by user so initialise it to false
        primaryKey = Boolean.FALSE;
    }
    // Update "embedded" based on type
    if (primaryKey == Boolean.FALSE && embedded == null) {
        Class element_type = getType();
        if (element_type.isArray()) {
            element_type = element_type.getComponentType();
            if (mmgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(element_type)) {
                embedded = Boolean.TRUE;
            }
        } else if (mmgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(element_type)) {
            embedded = Boolean.TRUE;
        }
    }
    if (embedded == null) {
        embedded = Boolean.FALSE;
    }
    // Update "persistence-modifier" according to type etc
    if (FieldPersistenceModifier.DEFAULT.equals(persistenceModifier)) {
        if (getTypeConverterName() != null) {
            // Explicitly set a converter, so assume it is persistent
            persistenceModifier = FieldPersistenceModifier.PERSISTENT;
        } else {
            boolean isPcClass = getType().isArray() ? isFieldArrayTypePersistable(mmgr) : mmgr.isFieldTypePersistable(type);
            if (!isPcClass) {
                if (getType().isArray() && getType().getComponentType().isInterface()) {
                    isPcClass = mmgr.getMetaDataForClassInternal(getType().getComponentType(), clr) != null;
                } else if (getType().isInterface()) {
                    isPcClass = mmgr.getMetaDataForClassInternal(getType(), clr) != null;
                }
            }
            persistenceModifier = getDefaultFieldPersistenceModifier(getType(), memberRepresented.getModifiers(), isPcClass, mmgr);
        }
    }
    // TODO If this field is NONE in superclass, make it NONE here too
    // If type is a container, load create the metadata. The field will be handled as a container if it
    // has a ContainerHandler registered against it.
    TypeManager typeMgr = mmgr.getNucleusContext().getTypeManager();
    ContainerHandler containerHandler = typeMgr.getContainerHandler(type);
    if (containerHandler == null) {
        // No container handler registered for this type
        if (hasContainer()) {
            // Container metadata specified on a type that is not a valid or supported container
            NucleusLogger.METADATA.error(Localiser.msg("044212", getClassName(), getName(), type));
            NucleusException ne = new InvalidMemberMetaDataException("044212", getClassName(), getName(), type);
            throw ne;
        }
    } else {
        // Field is a container type
        if (!hasContainer()) {
            // No container metadata has not been specified yet, create a default empty one
            setContainer(containerHandler.newMetaData());
        }
        containerHandler.populateMetaData(clr, primary, this);
    }
    // Update "default-fetch-group" according to type
    if (defaultFetchGroup == null && persistenceModifier.equals(FieldPersistenceModifier.NONE)) {
        defaultFetchGroup = Boolean.FALSE;
    } else if (defaultFetchGroup == null && persistenceModifier.equals(FieldPersistenceModifier.TRANSACTIONAL)) {
        defaultFetchGroup = Boolean.FALSE;
    } else if (defaultFetchGroup == null) {
        defaultFetchGroup = Boolean.FALSE;
        if (!primaryKey.equals(Boolean.TRUE)) {
            if (hasContainer() && containerHandler != null) {
                defaultFetchGroup = containerHandler.isDefaultFetchGroup(clr, typeMgr, this);
            } else if (typeMgr.isDefaultFetchGroup(getType())) {
                // If still not determined rely on the type
                defaultFetchGroup = Boolean.TRUE;
            }
        }
    }
    // Field is not specified as "persistent" yet has DFG or primary-key !
    if (persistenceModifier.equals(FieldPersistenceModifier.TRANSACTIONAL) || persistenceModifier.equals(FieldPersistenceModifier.NONE)) {
        if (defaultFetchGroup == Boolean.TRUE || primaryKey == Boolean.TRUE) {
            throw new InvalidMemberMetaDataException("044109", getClassName(), name, this.getType().getName(), persistenceModifier.toString());
        }
    }
    if (storeInLob) {
        // Set up the jdbcType/serialized settings according to the field type in line with JPA
        boolean useClob = false;
        if (type == String.class || (type.isArray() && type.getComponentType() == Character.class) || (type.isArray() && type.getComponentType() == char.class)) {
            useClob = true;
            if (columns == null || columns.isEmpty()) {
                // Create a CLOB column. What if the RDBMS doesn't support CLOB ?
                ColumnMetaData colmd = new ColumnMetaData();
                colmd.setName(column);
                colmd.setJdbcType("CLOB");
                addColumn(colmd);
            } else {
                ColumnMetaData colmd = columns.get(0);
                colmd.setJdbcType("CLOB");
            }
        }
        if (!useClob) {
            serialized = Boolean.TRUE;
        }
    }
    if (!mmgr.isDefaultNullable() && !hasContainer()) {
        // Find column metadata definition, creating one if not specified
        ColumnMetaData colMmd;
        if (columns == null || columns.isEmpty()) {
            newColumnMetaData();
        }
        colMmd = getColumnMetaData()[0];
        // Set column not-null by default
        if (colMmd.getAllowsNull() == null) {
            colMmd.setAllowsNull(Boolean.FALSE);
        }
    }
    if (this.containerMetaData != null && this.dependent != null) {
        // Check for invalid dependent field specifications
        NucleusLogger.METADATA.error(Localiser.msg("044110", getClassName(), getName(), ((ClassMetaData) this.parent).getName()));
        throw new InvalidMemberMetaDataException("044110", getClassName(), getName(), ((ClassMetaData) this.parent).getName());
    }
    if (embedded == Boolean.TRUE && embeddedMetaData == null) {
        // User specified "embedded" on the member, yet no embedded definition so add one TODO Omit this, since we should only use when provided
        AbstractClassMetaData memberCmd = mmgr.getMetaDataForClassInternal(getType(), clr);
        if (memberCmd != null) {
            embeddedMetaData = new EmbeddedMetaData();
            embeddedMetaData.setParent(this);
        }
    }
    if (embeddedMetaData != null) {
        // Update with any extensions (for lack of features in JPA)
        if (hasExtension("null-indicator-column")) {
            embeddedMetaData.setNullIndicatorColumn(getValueForExtension("null-indicator-column"));
            if (hasExtension("null-indicator-value")) {
                embeddedMetaData.setNullIndicatorValue(getValueForExtension("null-indicator-value"));
            }
        }
        // Populate any embedded object
        embeddedMetaData.populate(clr, primary);
        embedded = Boolean.TRUE;
    }
    if (containerMetaData != null && persistenceModifier == FieldPersistenceModifier.PERSISTENT) {
        // Populate any container
        if (containerMetaData instanceof CollectionMetaData) {
        // if (cascadeDelete)
        // {
        // // User has set cascade-delete (JPA) so set the element as dependent
        // getCollection().element.dependent = Boolean.TRUE;
        // }
        // getCollection().populate(clr, primary, mmgr);
        } else if (containerMetaData instanceof MapMetaData) {
        // String keyCascadeVal = getValueForExtension("cascade-delete-key");
        // if (cascadeDelete)
        // {
        // // User has set cascade-delete (JPA) so set the value as dependent
        // getMap().key.dependent = Boolean.FALSE; // JPA spec doesn't define what this should be
        // getMap().value.dependent = Boolean.TRUE;
        // }
        // if (keyCascadeVal != null)
        // {
        // if (keyCascadeVal.equalsIgnoreCase("true"))
        // {
        // getMap().key.dependent = Boolean.TRUE;
        // }
        // else
        // {
        // getMap().key.dependent = Boolean.FALSE;
        // }
        // }
        // getMap().populate(clr, primary, mmgr);
        } else if (containerMetaData instanceof ArrayMetaData) {
        // if (cascadeDelete)
        // {
        // // User has set cascade-delete (JPA) so set the element as dependent
        // getArray().element.dependent = Boolean.TRUE;
        // }
        // getArray().populate(clr, primary, mmgr);
        }
    }
    if (mmgr.isFieldTypePersistable(type) && cascadeDelete) {
        setDependent(true);
    }
    if (hasExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES)) {
        // Check the validity of the implementation-classes and qualify them where required.
        StringBuilder str = new StringBuilder();
        String[] implTypes = getValuesForExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES);
        for (int i = 0; i < implTypes.length; i++) {
            String implTypeName = ClassUtils.createFullClassName(getAbstractClassMetaData().getPackageName(), implTypes[i]);
            if (i > 0) {
                str.append(",");
            }
            try {
                clr.classForName(implTypeName);
                str.append(implTypeName);
            } catch (ClassNotResolvedException cnre) {
                try {
                    // Maybe the user specified a java.lang class without fully-qualifying it
                    // This is beyond the scope of the JDO spec which expects java.lang cases to be fully-qualified
                    String langClassName = ClassUtils.getJavaLangClassForType(implTypeName);
                    clr.classForName(langClassName);
                    str.append(langClassName);
                } catch (ClassNotResolvedException cnre2) {
                    // Implementation type not found
                    throw new InvalidMemberMetaDataException("044116", getClassName(), getName(), implTypes[i]);
                }
            }
        }
        // Replace with this new value
        addExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES, str.toString());
    }
    // Set up persistence flags for enhancement process
    byte serializable = 0;
    if (Serializable.class.isAssignableFrom(getType()) || getType().isPrimitive()) {
        serializable = Persistable.SERIALIZABLE;
    }
    if (FieldPersistenceModifier.NONE.equals(persistenceModifier)) {
        persistenceFlags = 0;
    } else if (FieldPersistenceModifier.TRANSACTIONAL.equals(persistenceModifier) && Modifier.isTransient(memberRepresented.getModifiers())) {
        persistenceFlags = (byte) (Persistable.CHECK_WRITE | serializable);
    } else if (primaryKey.booleanValue()) {
        persistenceFlags = (byte) (Persistable.MEDIATE_WRITE | serializable);
    } else if (defaultFetchGroup.booleanValue()) {
        persistenceFlags = (byte) (Persistable.CHECK_READ | Persistable.CHECK_WRITE | serializable);
    } else if (!defaultFetchGroup.booleanValue()) {
        persistenceFlags = (byte) (Persistable.MEDIATE_READ | Persistable.MEDIATE_WRITE | serializable);
    } else {
        persistenceFlags = 0;
    }
    // Set fields that are not relations
    if (persistenceModifier != FieldPersistenceModifier.PERSISTENT) {
        // Not a relation field so set relation information
        relationType = RelationType.NONE;
    } else if (containerMetaData == null && !mmgr.isFieldTypePersistable(type)) {
        if (!type.getName().equals(ClassNameConstants.Object) && !type.isInterface()) {
            // Not a container field, not a persistable type, nor a reference type so not a relation field
            relationType = RelationType.NONE;
        }
    }
    if (serialized == Boolean.TRUE && hasExtension(MetaData.EXTENSION_MEMBER_TYPE_CONVERTER_NAME)) {
        NucleusLogger.METADATA.warn(Localiser.msg("044127", getClassName(), getName(), getValueForExtension(MetaData.EXTENSION_MEMBER_TYPE_CONVERTER_NAME)));
        serialized = Boolean.FALSE;
    }
    setPopulated();
}
Also used : Serializable(java.io.Serializable) ApiAdapter(org.datanucleus.api.ApiAdapter) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) ContainerHandler(org.datanucleus.store.types.ContainerHandler) TypeManager(org.datanucleus.store.types.TypeManager) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 23 with TypeManager

use of org.datanucleus.store.types.TypeManager in project datanucleus-core by datanucleus.

the class L2CachePopulateFieldManager method processContainer.

private void processContainer(int fieldNumber, Object container, AbstractMemberMetaData mmd) {
    Object unwrappedContainer = container;
    if (container instanceof SCOContainer) {
        if (!((SCOContainer) container).isLoaded()) {
            // Contents not loaded so just mark as unloaded
            cachedPC.setLoadedField(fieldNumber, false);
            return;
        }
        unwrappedContainer = ((SCO) container).getValue();
    }
    TypeManager typeManager = op.getExecutionContext().getTypeManager();
    if (mmd.hasMap()) {
        MapHandler mapHandler = typeManager.getContainerHandler(mmd.getType());
        processMapContainer(fieldNumber, unwrappedContainer, mmd, mapHandler);
    } else {
        ElementContainerHandler elementContainerHandler = typeManager.getContainerHandler(mmd.getType());
        processElementContainer(fieldNumber, unwrappedContainer, mmd, elementContainerHandler);
    }
}
Also used : SCOContainer(org.datanucleus.store.types.SCOContainer) MapHandler(org.datanucleus.store.types.containers.MapHandler) TypeManager(org.datanucleus.store.types.TypeManager) ElementContainerHandler(org.datanucleus.store.types.ElementContainerHandler)

Example 24 with TypeManager

use of org.datanucleus.store.types.TypeManager in project datanucleus-core by datanucleus.

the class DetachFieldManager method processContainer.

private Object processContainer(int fieldNumber, Object container, AbstractMemberMetaData mmd) {
    Object detachedContainer;
    TypeManager typeManager = op.getExecutionContext().getTypeManager();
    ContainerHandler containerHandler = typeManager.getContainerHandler(mmd.getType());
    if (mmd.hasMap()) {
        detachedContainer = processMapContainer(fieldNumber, container, mmd, containerHandler);
    } else {
        detachedContainer = processElementContainer(fieldNumber, container, mmd, containerHandler);
    }
    if (!mmd.hasArray()) {
        // Need to unset owner for mutable SCOs
        Object wrappedContainer;
        if (SCOUtils.detachAsWrapped(op)) {
            // Try to wrap the field, if possible, replacing it since it will be returned as wrapped
            wrappedContainer = SCOUtils.wrapSCOField(op, fieldNumber, detachedContainer, true);
            // Return the wrapped, if mutable, otherwise just the immutable value
            detachedContainer = wrappedContainer;
        } else {
            // Try to wrap the field, if possible, just to be able to unset the owner, so don't
            // replace it
            wrappedContainer = SCOUtils.wrapSCOField(op, fieldNumber, detachedContainer, false);
            // The container can be already an SCO so unwrap it if necessary
            if (detachedContainer instanceof SCO) {
                detachedContainer = SCOUtils.unwrapSCOField(op, fieldNumber, (SCO) detachedContainer);
            }
        }
        // It still can be an immutable collection or map, so must check if has been wrapped
        if (wrappedContainer instanceof SCO) {
            ((SCO) wrappedContainer).unsetOwner();
        }
    }
    return detachedContainer;
}
Also used : ContainerHandler(org.datanucleus.store.types.ContainerHandler) TypeManager(org.datanucleus.store.types.TypeManager) SCO(org.datanucleus.store.types.SCO)

Example 25 with TypeManager

use of org.datanucleus.store.types.TypeManager in project datanucleus-rdbms by datanucleus.

the class MappingManagerImpl method getMappingType.

/**
 * Accessor for the JavaTypeMapping class for the supplied java type.
 * @param javaTypeName The java type name
 * @return The Java mapping type
 */
@Override
public Class<? extends JavaTypeMapping> getMappingType(String javaTypeName) {
    if (javaTypeName == null) {
        return null;
    }
    MappedType type = mappedTypes.get(javaTypeName);
    if (type != null) {
        return type.javaMappingType;
    }
    // No explicit <java_mapping> so check for a default TypeConverter against the basic <java-type>
    TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager();
    TypeConverter defaultTypeConv = typeMgr.getDefaultTypeConverterForType(clr.classForName(javaTypeName));
    if (defaultTypeConv != null) {
        // We have no explicit mapping and there is a defined default TypeConverter so return and that will be picked
        return null;
    }
    // Check if this is a SCO wrapper
    Class cls = typeMgr.getTypeForSecondClassWrapper(javaTypeName);
    if (cls != null) {
        // Supplied class is a SCO wrapper, so return the java type mapping for the underlying java type
        type = mappedTypes.get(cls.getName());
        if (type != null) {
            return type.javaMappingType;
        }
    }
    // Not SCO wrapper so find a type
    try {
        cls = clr.classForName(javaTypeName);
        type = findMappedTypeForClass(cls);
        return type.javaMappingType;
    } catch (Exception e) {
        return null;
    }
}
Also used : TypeConverter(org.datanucleus.store.types.converters.TypeConverter) TypeManager(org.datanucleus.store.types.TypeManager) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException) NoTableManagedException(org.datanucleus.store.rdbms.exceptions.NoTableManagedException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException)

Aggregations

TypeManager (org.datanucleus.store.types.TypeManager)26 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)10 JDOTypeConverter (org.datanucleus.api.jdo.JDOTypeConverter)8 ApiAdapter (org.datanucleus.api.ApiAdapter)6 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)5 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)5 RelationType (org.datanucleus.metadata.RelationType)5 ContainerHandler (org.datanucleus.store.types.ContainerHandler)5 AttributeConverter (javax.jdo.AttributeConverter)4 PersistenceNucleusContext (org.datanucleus.PersistenceNucleusContext)4 ExecutionContext (org.datanucleus.ExecutionContext)3 NucleusException (org.datanucleus.exceptions.NucleusException)3 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)3 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)3 EmbeddedMetaData (org.datanucleus.metadata.EmbeddedMetaData)3 FieldMetaData (org.datanucleus.metadata.FieldMetaData)3 FieldPersistenceModifier (org.datanucleus.metadata.FieldPersistenceModifier)3 ObjectProvider (org.datanucleus.state.ObjectProvider)3 MultiColumnConverter (org.datanucleus.store.types.converters.MultiColumnConverter)3 TypeConverter (org.datanucleus.store.types.converters.TypeConverter)3