Search in sources :

Example 1 with SequenceMetaData

use of org.datanucleus.metadata.SequenceMetaData in project datanucleus-rdbms by datanucleus.

the class RDBMSStoreManager method addSequenceForMetaData.

protected void addSequenceForMetaData(MetaData md, String seq, ClassLoaderResolver clr, Set<String> sequencesGenerated, FileWriter ddlWriter) {
    String seqName = seq;
    Integer min = null;
    Integer max = null;
    Integer start = null;
    Integer increment = null;
    Integer cacheSize = null;
    SequenceMetaData seqmd = getMetaDataManager().getMetaDataForSequence(clr, seq);
    if (seqmd != null) {
        seqName = seqmd.getDatastoreSequence();
        if (seqmd.getAllocationSize() > 0) {
            increment = Integer.valueOf(seqmd.getAllocationSize());
        }
        if (seqmd.getInitialValue() >= 0) {
            start = Integer.valueOf(seqmd.getInitialValue());
        }
        md = seqmd;
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_MIN_VALUE)) {
        min = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_MIN_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_MAX_VALUE)) {
        max = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_MAX_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_CACHE_SIZE)) {
        increment = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_CACHE_SIZE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE)) {
        start = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE)) {
        cacheSize = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE));
    }
    if (!sequencesGenerated.contains(seqName)) {
        String stmt = getDatastoreAdapter().getSequenceCreateStmt(seqName, min, max, start, increment, cacheSize);
        if (ddlWriter != null) {
            try {
                ddlWriter.write(stmt + ";\n");
            } catch (IOException ioe) {
            }
        } else {
            PreparedStatement ps = null;
            ManagedConnection mconn = connectionMgr.getConnection(TransactionIsolation.NONE);
            try {
                ps = sqlController.getStatementForUpdate(mconn, stmt, false);
                sqlController.executeStatementUpdate(null, mconn, stmt, ps, true);
            } catch (SQLException e) {
            } finally {
                try {
                    if (ps != null) {
                        sqlController.closeStatement(mconn, ps);
                    }
                } catch (SQLException e) {
                }
                mconn.release();
            }
        }
        sequencesGenerated.add(seqName);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) MacroString(org.datanucleus.util.MacroString) IOException(java.io.IOException) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData)

Example 2 with SequenceMetaData

use of org.datanucleus.metadata.SequenceMetaData in project datanucleus-core by datanucleus.

the class AbstractStoreManager method getValueGeneratorForMember.

protected synchronized ValueGenerator getValueGeneratorForMember(ClassLoaderResolver clr, AbstractClassMetaData cmd, int absoluteFieldNumber) {
    String memberKey = valueGenerationMgr.getMemberKey(cmd, absoluteFieldNumber);
    // Check if we have a ValueGenerator already created for this member
    ValueGenerator generator = valueGenerationMgr.getValueGeneratorForMemberKey(memberKey);
    if (generator != null) {
        // Return the ValueGenerator already registered against this member "key"
        return generator;
    }
    // No ValueGenerator registered for this memberKey, so need to determine which to use and create it as required.
    String fieldName = null;
    ValueGenerationStrategy strategy = null;
    String sequence = null;
    String valueGeneratorName = null;
    if (absoluteFieldNumber >= 0) {
        // real field
        AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(absoluteFieldNumber);
        fieldName = mmd.getFullFieldName();
        strategy = mmd.getValueStrategy();
        sequence = mmd.getSequence();
        valueGeneratorName = mmd.getValueGeneratorName();
    } else {
        // datastore-identity surrogate field
        fieldName = cmd.getFullClassName() + " (datastore id)";
        strategy = cmd.getIdentityMetaData().getValueStrategy();
        sequence = cmd.getIdentityMetaData().getSequence();
        valueGeneratorName = cmd.getIdentityMetaData().getValueGeneratorName();
    }
    String strategyName = strategy.toString();
    if (strategy.equals(ValueGenerationStrategy.CUSTOM)) {
        // Using a "custom" generator
        strategyName = strategy.getCustomName();
    } else if (strategy.equals(ValueGenerationStrategy.NATIVE)) {
        strategyName = getValueGenerationStrategyForNative(cmd, absoluteFieldNumber);
        strategy = ValueGenerationStrategy.getIdentityStrategy(strategyName);
    }
    // Check for this strategy being a "unique" ValueGenerator, and created if not yet present
    generator = valueGenerationMgr.getUniqueValueGeneratorByName(strategyName);
    if (generator != null) {
        // "unique" ValueGenerator already defined for this strategy, so register it against the member
        valueGenerationMgr.registerValueGeneratorForMemberKey(memberKey, generator);
        return generator;
    }
    // Must be "datastore" specific generator so use plugin mechanism to create one and register against this member "key"
    // Set up the default properties available for all value generators
    // Extract any metadata-based generation information keyed by the "valueGeneratorName"
    TableGeneratorMetaData tableGeneratorMetaData = null;
    SequenceMetaData sequenceMetaData = null;
    if (valueGeneratorName != null) {
        if (strategy == ValueGenerationStrategy.INCREMENT) {
            tableGeneratorMetaData = getMetaDataManager().getMetaDataForTableGenerator(clr, valueGeneratorName);
            if (tableGeneratorMetaData == null) {
                throw new NucleusUserException(Localiser.msg("038005", fieldName, valueGeneratorName));
            }
        } else if (strategy == ValueGenerationStrategy.SEQUENCE) {
            sequenceMetaData = getMetaDataManager().getMetaDataForSequence(clr, valueGeneratorName);
            if (sequenceMetaData == null) {
                throw new NucleusUserException(Localiser.msg("038006", fieldName, valueGeneratorName));
            }
        }
    } else if (strategy == ValueGenerationStrategy.SEQUENCE && sequence != null) {
        // TODO Allow for package name of this class prefix for the sequence name
        sequenceMetaData = getMetaDataManager().getMetaDataForSequence(clr, sequence);
        if (sequenceMetaData == null) {
            // No <sequence> defining the datastore sequence name, so fallback to this name directly in the datastore
            NucleusLogger.VALUEGENERATION.info("Member " + fieldName + " has been specified to use sequence '" + sequence + "' but there is no <sequence> specified in the MetaData. Falling back to use a sequence in the datastore with this name directly.");
        }
    }
    Properties props = getPropertiesForValueGenerator(cmd, absoluteFieldNumber, clr, sequenceMetaData, tableGeneratorMetaData);
    return valueGenerationMgr.createAndRegisterValueGenerator(memberKey, strategyName, props);
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ValueGenerator(org.datanucleus.store.valuegenerator.ValueGenerator) ValueGenerationStrategy(org.datanucleus.metadata.ValueGenerationStrategy) TableGeneratorMetaData(org.datanucleus.metadata.TableGeneratorMetaData) Properties(java.util.Properties) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData)

Example 3 with SequenceMetaData

use of org.datanucleus.metadata.SequenceMetaData in project datanucleus-api-jdo by datanucleus.

the class JDOAnnotationReader method processClassAnnotations.

/**
 * Method to process the "class" level annotations and create the outline ClassMetaData object.
 * Supports classes annotated with @PersistenceCapable, classes annotated with @PersistenceAware, and classes which have neither of those but have @Queries or @Query.
 * @param pmd Parent PackageMetaData
 * @param cls The class
 * @param annotations Annotations for this class
 * @param clr ClassLoader resolver
 * @return The ClassMetaData/InterfaceMetaData (or null if no annotations)
 */
protected AbstractClassMetaData processClassAnnotations(PackageMetaData pmd, Class cls, AnnotationObject[] annotations, ClassLoaderResolver clr) {
    if (annotations == null || annotations.length == 0) {
        return null;
    }
    AbstractClassMetaData cmd = null;
    AnnotationObject pcAnnotation = isClassPersistable(annotations);
    if (pcAnnotation != null) {
        // PersistenceCapable class
        cmd = (cls.isInterface()) ? pmd.newInterfaceMetadata(ClassUtils.getClassNameForClass(cls)) : pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
        cmd.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
        // Process all attributes here in case needed for other annotations
        processPersistenceCapableAnnotation(cls, cmd, pcAnnotation.getNameValueMap());
    } else if (isClassPersistenceAware(annotations)) {
        // PersistenceAware class
        cmd = pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
        cmd.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_AWARE);
    } else if (doesClassHaveNamedQueries(annotations)) {
        // Class with named query specified
        cmd = pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
        cmd.setPersistenceModifier(ClassPersistenceModifier.NON_PERSISTENT);
    } else {
        // Not involved in the persistence process
        return null;
    }
    // Cater for named queries being specified on a persistence aware, or other class
    processNamedQueries(cmd, cls, annotations);
    if (cmd.getPersistenceModifier() != ClassPersistenceModifier.PERSISTENCE_CAPABLE) {
        // Not persistable, so no further information needed
        return cmd;
    }
    // Class is persistable so process annotations
    for (AnnotationObject annotation : annotations) {
        String annName = annotation.getName();
        if (annName.equals(JDOAnnotationUtils.PERSISTENCE_CAPABLE)) {
            // @PersistenceCapable is merged and processed above
            continue;
        }
        Map<String, Object> annotationValues = annotation.getNameValueMap();
        if (annName.equals(JDOAnnotationUtils.EMBEDDED_ONLY)) {
            cmd.setEmbeddedOnly(true);
        } else if (annName.equals(JDOAnnotationUtils.VERSION)) {
            VersionStrategy versionStrategy = (VersionStrategy) annotationValues.get("strategy");
            String strategy = JDOAnnotationUtils.getVersionStrategyString(versionStrategy);
            String indexed = (String) annotationValues.get("indexed");
            String column = (String) annotationValues.get("column");
            Column[] columns = (Column[]) annotationValues.get("columns");
            VersionMetaData vermd = new VersionMetaData();
            vermd.setStrategy(strategy);
            vermd.setColumnName(column);
            vermd.setIndexed(IndexedValue.getIndexedValue(indexed));
            if (columns != null && columns.length > 0) {
                // Only use the first column
                ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
                vermd.setColumnMetaData(colmd);
            }
            JDOAnnotationUtils.addExtensionsToMetaData(vermd, (Extension[]) annotationValues.get("extensions"));
            vermd.setParent(cmd);
            cmd.setVersionMetaData(vermd);
        } else if (annName.equals(JDOAnnotationUtils.DATASTORE_IDENTITY)) {
            String strategy = JDOAnnotationUtils.getValueGenerationStrategyString((IdGeneratorStrategy) annotationValues.get("strategy"));
            String customStrategy = (String) annotationValues.get("customStrategy");
            if (!StringUtils.isWhitespace(customStrategy)) {
                // User has provided an extension strategy
                strategy = customStrategy;
            }
            String sequence = (String) annotationValues.get("sequence");
            String column = (String) annotationValues.get("column");
            Column[] columns = (Column[]) annotationValues.get("columns");
            IdentityMetaData idmd = new IdentityMetaData();
            idmd.setColumnName(column);
            idmd.setValueStrategy(ValueGenerationStrategy.getIdentityStrategy(strategy));
            idmd.setSequence(sequence);
            if (columns != null && columns.length > 0) {
                // Only use the first column
                ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
                idmd.setColumnMetaData(colmd);
            }
            JDOAnnotationUtils.addExtensionsToMetaData(idmd, (Extension[]) annotationValues.get("extensions"));
            idmd.setParent(cmd);
            cmd.setIdentityMetaData(idmd);
        } else if (annName.equals(JDOAnnotationUtils.PRIMARY_KEY)) {
            String pkName = (String) annotationValues.get("name");
            String pkColumn = (String) annotationValues.get("column");
            Column[] columns = (Column[]) annotationValues.get("columns");
            PrimaryKeyMetaData pkmd = new PrimaryKeyMetaData();
            pkmd.setName(pkName);
            pkmd.setColumnName(pkColumn);
            if (columns != null && columns.length > 0) {
                for (Column column : columns) {
                    pkmd.addColumn(JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(column));
                }
            }
            JDOAnnotationUtils.addExtensionsToMetaData(pkmd, (Extension[]) annotationValues.get("extensions"));
            pkmd.setParent(cmd);
            cmd.setPrimaryKeyMetaData(pkmd);
        } else if (annName.equals(JDOAnnotationUtils.JOINS)) {
            Join[] js = (Join[]) annotationValues.get("value");
            if (js != null && js.length > 0) {
                for (Join join : js) {
                    JoinMetaData joinmd = cmd.newJoinMetaData();
                    joinmd.setTable(join.table());
                    joinmd.setColumnName(join.column());
                    joinmd.setIndexed(IndexedValue.getIndexedValue(join.indexed()));
                    joinmd.setOuter(MetaDataUtils.getBooleanForString(join.outer(), false));
                    joinmd.setUnique(join.unique());
                    joinmd.setDeleteAction(JDOAnnotationUtils.getForeignKeyActionString(join.deleteAction()));
                    JDOAnnotationUtils.addExtensionsToMetaData(joinmd, join.extensions());
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.JOIN)) {
            JoinMetaData joinmd = cmd.newJoinMetaData();
            joinmd.setTable((String) annotationValues.get("table"));
            joinmd.setColumnName((String) annotationValues.get("column"));
            joinmd.setIndexed(IndexedValue.getIndexedValue((String) annotationValues.get("indexed")));
            joinmd.setOuter(MetaDataUtils.getBooleanForString((String) annotationValues.get("outer"), false));
            joinmd.setUnique((String) annotationValues.get("unique"));
            joinmd.setDeleteAction(((ForeignKeyAction) annotationValues.get("deleteAction")).toString());
            JDOAnnotationUtils.addExtensionsToMetaData(joinmd, (Extension[]) annotationValues.get("extensions"));
        } else if (annName.equals(JDOAnnotationUtils.INHERITANCE)) {
            String strategy = JDOAnnotationUtils.getInheritanceStrategyString((InheritanceStrategy) annotationValues.get("strategy"));
            String customStrategy = (String) annotationValues.get("customStrategy");
            if (!StringUtils.isWhitespace(customStrategy)) {
                // User has provided an extension strategy
                strategy = customStrategy;
            }
            InheritanceMetaData inhmd = cmd.getInheritanceMetaData();
            if (inhmd == null) {
                inhmd = cmd.newInheritanceMetadata();
            }
            inhmd.setStrategy(strategy);
        } else if (annName.equals(JDOAnnotationUtils.DISCRIMINATOR)) {
            DiscriminatorStrategy discriminatorStrategy = (DiscriminatorStrategy) annotationValues.get("strategy");
            String strategy = JDOAnnotationUtils.getDiscriminatorStrategyString(discriminatorStrategy);
            String column = (String) annotationValues.get("column");
            String indexed = (String) annotationValues.get("indexed");
            String value = (String) annotationValues.get("value");
            Column[] columns = (Column[]) annotationValues.get("columns");
            InheritanceMetaData inhmd = cmd.getInheritanceMetaData();
            if (inhmd == null) {
                inhmd = cmd.newInheritanceMetadata();
            }
            DiscriminatorMetaData dismd = inhmd.newDiscriminatorMetadata();
            dismd.setColumnName(column);
            dismd.setValue(value);
            dismd.setStrategy(strategy);
            dismd.setIndexed(indexed);
            if (columns != null && columns.length > 0) {
                // Only use the first column
                ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
                dismd.setColumnMetaData(colmd);
            }
        } else if (annName.equals(JDOAnnotationUtils.FETCHPLANS)) {
            FileMetaData filemd = (FileMetaData) pmd.getParent();
            FetchPlan[] plans = (FetchPlan[]) annotationValues.get("value");
            for (FetchPlan plan : plans) {
                FetchPlanMetaData fpmd = filemd.newFetchPlanMetadata(plan.name());
                fpmd.setFetchSize(plan.fetchSize());
                fpmd.setMaxFetchDepth(plan.maxFetchDepth());
                int numGroups = plan.fetchGroups().length;
                for (int k = 0; k < numGroups; k++) {
                    fpmd.addFetchGroup(new FetchGroupMetaData(plan.fetchGroups()[k]));
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.FETCHPLAN)) {
            FileMetaData filemd = (FileMetaData) pmd.getParent();
            FetchPlanMetaData fpmd = filemd.newFetchPlanMetadata((String) annotationValues.get("name"));
            fpmd.setFetchSize(((Integer) annotationValues.get("fetchSize")).intValue());
            fpmd.setMaxFetchDepth(((Integer) annotationValues.get("maxFetchDepth")).intValue());
            String[] fpFetchGroups = (String[]) annotationValues.get("fetchGroups");
            for (String fpFetchGroup : fpFetchGroups) {
                fpmd.addFetchGroup(new FetchGroupMetaData(fpFetchGroup));
            }
        } else if (annName.equals(JDOAnnotationUtils.FETCHGROUPS)) {
            FetchGroup[] groups = (FetchGroup[]) annotationValues.get("value");
            for (FetchGroup group : groups) {
                FetchGroupMetaData fgmd = cmd.newFetchGroupMetaData(group.name());
                if (!StringUtils.isWhitespace(group.postLoad())) {
                    fgmd.setPostLoad(Boolean.valueOf(group.postLoad()));
                }
                int numFields = group.members().length;
                for (int k = 0; k < numFields; k++) {
                    FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(fgmd, group.members()[k].name());
                    fgmmd.setRecursionDepth(group.members()[k].recursionDepth());
                    fgmd.addMember(fgmmd);
                }
                int numGroups = group.fetchGroups().length;
                for (int k = 0; k < numGroups; k++) {
                    fgmd.addFetchGroup(new FetchGroupMetaData(group.fetchGroups()[k]));
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.FETCHGROUP)) {
            FetchGroupMetaData fgmd = cmd.newFetchGroupMetaData((String) annotationValues.get("name"));
            String postLoadStr = (String) annotationValues.get("postLoad");
            if (!StringUtils.isWhitespace(postLoadStr)) {
                fgmd.setPostLoad(Boolean.valueOf(postLoadStr));
            }
            Persistent[] fields = (Persistent[]) annotationValues.get("members");
            if (fields != null) {
                for (Persistent field : fields) {
                    FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(fgmd, field.name());
                    fgmmd.setRecursionDepth(field.recursionDepth());
                    fgmd.addMember(fgmmd);
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.SEQUENCE)) {
            String seqName = (String) annotationValues.get("name");
            String seqStrategy = JDOAnnotationUtils.getSequenceStrategyString((SequenceStrategy) annotationValues.get("strategy"));
            String seqSeq = (String) annotationValues.get("datastoreSequence");
            Class seqFactory = (Class) annotationValues.get("factoryClass");
            String seqFactoryClassName = null;
            if (seqFactory != null && seqFactory != void.class) {
                seqFactoryClassName = seqFactory.getName();
            }
            Integer seqSize = (Integer) annotationValues.get("allocationSize");
            Integer seqStart = (Integer) annotationValues.get("initialValue");
            if (StringUtils.isWhitespace(seqName)) {
                throw new InvalidClassMetaDataException("044155", cmd.getFullClassName());
            }
            SequenceMetaData seqmd = new SequenceMetaData(seqName, seqStrategy);
            seqmd.setFactoryClass(seqFactoryClassName);
            seqmd.setDatastoreSequence(seqSeq);
            if (seqSize != null) {
                seqmd.setAllocationSize(seqSize);
            }
            if (seqStart != null) {
                seqmd.setInitialValue(seqStart);
            }
            JDOAnnotationUtils.addExtensionsToMetaData(seqmd, (Extension[]) annotationValues.get("extensions"));
            // Sequence - currently only allowing 1 per class (should really be on the package)
            cmd.getPackageMetaData().addSequence(seqmd);
        } else if (annName.equals(JDOAnnotationUtils.INDICES)) {
            // Multiple Indices for the class
            Index[] values = (Index[]) annotationValues.get("value");
            if (values != null && values.length > 0) {
                for (Index idx : values) {
                    IndexMetaData idxmd = JDOAnnotationUtils.getIndexMetaData(idx.name(), idx.table(), "" + idx.unique(), idx.members(), idx.columns());
                    if (idxmd.getNumberOfColumns() == 0 && idxmd.getNumberOfMembers() == 0) {
                        NucleusLogger.METADATA.warn(Localiser.msg("044204", cls.getName()));
                    } else {
                        cmd.addIndex(idxmd);
                        idxmd.setParent(cmd);
                    }
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.INDEX)) {
            // Single Index for the class
            String name = (String) annotationValues.get("name");
            String table = (String) annotationValues.get("table");
            String unique = (String) annotationValues.get("unique");
            String[] members = (String[]) annotationValues.get("members");
            Column[] columns = (Column[]) annotationValues.get("columns");
            IndexMetaData idxmd = JDOAnnotationUtils.getIndexMetaData(name, table, unique, members, columns);
            JDOAnnotationUtils.addExtensionsToMetaData(idxmd, (Extension[]) annotationValues.get("extensions"));
            if (idxmd.getNumberOfColumns() == 0 && idxmd.getNumberOfMembers() == 0) {
                NucleusLogger.METADATA.warn(Localiser.msg("044204", cls.getName()));
            } else {
                cmd.addIndex(idxmd);
                idxmd.setParent(cmd);
            }
        } else if (annName.equals(JDOAnnotationUtils.UNIQUES)) {
            // Multiple Unique Constraints for the class
            Unique[] values = (Unique[]) annotationValues.get("value");
            if (values != null && values.length > 0) {
                for (Unique uni : values) {
                    UniqueMetaData unimd = JDOAnnotationUtils.getUniqueMetaData(uni.name(), uni.table(), "" + uni.deferred(), uni.members(), uni.columns());
                    if (unimd.getNumberOfColumns() == 0 && unimd.getNumberOfMembers() == 0) {
                        NucleusLogger.METADATA.warn(Localiser.msg("044205", cls.getName()));
                    } else {
                        cmd.addUniqueConstraint(unimd);
                        unimd.setParent(cmd);
                    }
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.UNIQUE)) {
            // Single Unique constraint for the class
            String name = (String) annotationValues.get("name");
            String table = (String) annotationValues.get("table");
            String deferred = (String) annotationValues.get("deferred");
            String[] members = (String[]) annotationValues.get("members");
            Column[] columns = (Column[]) annotationValues.get("columns");
            UniqueMetaData unimd = JDOAnnotationUtils.getUniqueMetaData(name, table, deferred, members, columns);
            JDOAnnotationUtils.addExtensionsToMetaData(unimd, (Extension[]) annotationValues.get("extensions"));
            if (unimd.getNumberOfColumns() == 0 && unimd.getNumberOfMembers() == 0) {
                NucleusLogger.METADATA.warn(Localiser.msg("044205", cls.getName()));
            } else {
                cmd.addUniqueConstraint(unimd);
                unimd.setParent(cmd);
            }
        } else if (annName.equals(JDOAnnotationUtils.FOREIGNKEYS)) {
            // Multiple FKs for the class
            ForeignKey[] values = (ForeignKey[]) annotationValues.get("value");
            if (values != null && values.length > 0) {
                for (ForeignKey fk : values) {
                    String deleteAction = JDOAnnotationUtils.getForeignKeyActionString(fk.deleteAction());
                    String updateAction = JDOAnnotationUtils.getForeignKeyActionString(fk.updateAction());
                    ForeignKeyMetaData fkmd = JDOAnnotationUtils.getFKMetaData(fk.name(), fk.table(), fk.unique(), "" + fk.deferred(), deleteAction, updateAction, fk.members(), fk.columns());
                    if (fkmd.getNumberOfColumns() == 0 && fkmd.getNumberOfMembers() == 0) {
                        NucleusLogger.METADATA.warn(Localiser.msg("044206", cls.getName()));
                    } else {
                        cmd.addForeignKey(fkmd);
                        fkmd.setParent(cmd);
                    }
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.FOREIGNKEY)) {
            // Single FK constraint for the class
            String name = (String) annotationValues.get("name");
            String table = (String) annotationValues.get("table");
            String unique = (String) annotationValues.get("unique");
            String deferred = (String) annotationValues.get("deferred");
            String deleteAction = JDOAnnotationUtils.getForeignKeyActionString((ForeignKeyAction) annotationValues.get("deleteAction"));
            String updateAction = JDOAnnotationUtils.getForeignKeyActionString((ForeignKeyAction) annotationValues.get("updateAction"));
            String[] members = (String[]) annotationValues.get("members");
            Column[] columns = (Column[]) annotationValues.get("columns");
            ForeignKeyMetaData fkmd = JDOAnnotationUtils.getFKMetaData(name, table, unique, deferred, deleteAction, updateAction, members, columns);
            JDOAnnotationUtils.addExtensionsToMetaData(fkmd, (Extension[]) annotationValues.get("extensions"));
            if (fkmd.getNumberOfColumns() == 0 && fkmd.getNumberOfMembers() == 0) {
                NucleusLogger.METADATA.warn(Localiser.msg("044206", cls.getName()));
            } else {
                cmd.addForeignKey(fkmd);
                fkmd.setParent(cmd);
            }
        } else if (annName.equals(JDOAnnotationUtils.COLUMNS)) {
            // Unmapped column specification
            Column[] cols = (Column[]) annotationValues.get("value");
            if (cols != null && cols.length > 0) {
                for (Column col : cols) {
                    ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(col);
                    JDOAnnotationUtils.addExtensionsToMetaData(colmd, col.extensions());
                    colmd.setParent(cmd);
                    cmd.addUnmappedColumn(colmd);
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.CACHEABLE)) {
            String cache = (String) annotationValues.get("value");
            if (cache != null && cache.equalsIgnoreCase("false")) {
                cmd.setCacheable(false);
            }
        } else if (annName.equals(JDOAnnotationUtils.EXTENSIONS)) {
            Extension[] values = (Extension[]) annotationValues.get("value");
            if (values != null && values.length > 0) {
                for (Extension ext : values) {
                    String vendorName = ext.vendorName();
                    if (StringUtils.isWhitespace(vendorName)) {
                        throw new InvalidMetaDataException("044160", vendorName, ext.key().toString(), ext.value().toString());
                    } else if (vendorName.equalsIgnoreCase(MetaData.VENDOR_NAME)) {
                        cmd.addExtension(ext.key().toString(), ext.value().toString());
                    }
                }
            }
        } else if (annName.equals(JDOAnnotationUtils.EXTENSION)) {
            String vendorName = (String) annotationValues.get("vendorName");
            if (StringUtils.isWhitespace(vendorName)) {
                throw new InvalidMetaDataException("044160", vendorName, annotationValues.get("key"), annotationValues.get("value"));
            } else if (vendorName.equalsIgnoreCase(MetaData.VENDOR_NAME)) {
                cmd.addExtension((String) annotationValues.get("key"), (String) annotationValues.get("value"));
            }
        } else {
            if (!annName.equals(JDOAnnotationUtils.PERSISTENCE_AWARE) && !annName.equals(JDOAnnotationUtils.QUERIES) && !annName.equals(JDOAnnotationUtils.QUERY)) {
                NucleusLogger.METADATA.debug(Localiser.msg("044203", cls.getName(), annotation.getName()));
            }
        }
    }
    NucleusLogger.METADATA.debug(Localiser.msg("044200", cls.getName(), "JDO"));
    return cmd;
}
Also used : DiscriminatorStrategy(javax.jdo.annotations.DiscriminatorStrategy) InvalidMetaDataException(org.datanucleus.metadata.InvalidMetaDataException) VersionMetaData(org.datanucleus.metadata.VersionMetaData) Index(javax.jdo.annotations.Index) AnnotationObject(org.datanucleus.metadata.annotations.AnnotationObject) FetchPlan(javax.jdo.annotations.FetchPlan) FetchPlanMetaData(org.datanucleus.metadata.FetchPlanMetaData) IdentityMetaData(org.datanucleus.metadata.IdentityMetaData) InheritanceMetaData(org.datanucleus.metadata.InheritanceMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData) InvalidClassMetaDataException(org.datanucleus.metadata.InvalidClassMetaDataException) Column(javax.jdo.annotations.Column) ForeignKeyAction(javax.jdo.annotations.ForeignKeyAction) VersionStrategy(javax.jdo.annotations.VersionStrategy) ForeignKeyMetaData(org.datanucleus.metadata.ForeignKeyMetaData) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData) FetchGroupMemberMetaData(org.datanucleus.metadata.FetchGroupMemberMetaData) Join(javax.jdo.annotations.Join) Persistent(javax.jdo.annotations.Persistent) UniqueMetaData(org.datanucleus.metadata.UniqueMetaData) ForeignKey(javax.jdo.annotations.ForeignKey) PrimaryKeyMetaData(org.datanucleus.metadata.PrimaryKeyMetaData) IndexMetaData(org.datanucleus.metadata.IndexMetaData) Extension(javax.jdo.annotations.Extension) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) FetchGroup(javax.jdo.annotations.FetchGroup) AnnotationObject(org.datanucleus.metadata.annotations.AnnotationObject) JoinMetaData(org.datanucleus.metadata.JoinMetaData) Unique(javax.jdo.annotations.Unique) FetchGroupMetaData(org.datanucleus.metadata.FetchGroupMetaData)

Example 4 with SequenceMetaData

use of org.datanucleus.metadata.SequenceMetaData in project datanucleus-api-jdo by datanucleus.

the class JDOMetaDataManager method getMetaDataForSequence.

/**
 * Accessor for the MetaData for a Sequence in a package.
 * If the sequence is not yet known will search the valid locations for the passed name.
 * @param clr the ClassLoaderResolver
 * @param packageSequenceName Fully qualified name of the sequence (inc package name)
 * @return The SequenceMetaData for this named sequence
 */
public SequenceMetaData getMetaDataForSequence(ClassLoaderResolver clr, String packageSequenceName) {
    SequenceMetaData seqmd = super.getMetaDataForSequence(clr, packageSequenceName);
    if (seqmd != null) {
        return seqmd;
    }
    // MetaData not found so maybe just not yet loaded
    String packageName = packageSequenceName;
    if (packageSequenceName.lastIndexOf('.') >= 0) {
        packageName = packageSequenceName.substring(0, packageSequenceName.lastIndexOf('.'));
    }
    // Search valid JDO file locations ("jdo" and "orm" files for the specified package)
    List<String> locations = new ArrayList<>();
    locations.addAll(getValidMetaDataLocationsForItem(getJDOFileSuffix(), null, packageName, false));
    locations.addAll(getValidMetaDataLocationsForItem(getORMFileSuffix(), getORMMappingName(), packageName, false));
    for (String location : locations) {
        // Process all resources for this location
        Enumeration resources;
        try {
            resources = clr.getResources(location, null);
        } catch (IOException e) {
            throw new NucleusException("Error loading resource", e).setFatal();
        }
        while (resources.hasMoreElements()) {
            URL fileURL = (URL) resources.nextElement();
            if (fileMetaDataByURLString.get(fileURL.toString()) == null) {
                // File hasn't been loaded so load it
                FileMetaData filemd = parseFile(fileURL);
                registerFile(fileURL.toString(), filemd, clr);
            // Populate all classes in this file we've just parsed
            // TODO Populate the classes found in this file
            }
        }
        if (sequenceMetaDataByPackageSequence != null) {
            // Try lookup using package name
            seqmd = sequenceMetaDataByPackageSequence.get(packageSequenceName);
        }
        if (seqmd != null) {
            if (NucleusLogger.METADATA.isDebugEnabled()) {
                NucleusLogger.METADATA.debug(Localiser.msg("044053", packageSequenceName, location));
            }
            return seqmd;
        }
        if (NucleusLogger.METADATA.isDebugEnabled()) {
            NucleusLogger.METADATA.debug(Localiser.msg("044051", packageSequenceName, location));
        }
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NucleusException(org.datanucleus.exceptions.NucleusException) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData) URL(java.net.URL) FileMetaData(org.datanucleus.metadata.FileMetaData)

Example 5 with SequenceMetaData

use of org.datanucleus.metadata.SequenceMetaData in project datanucleus-api-jdo by datanucleus.

the class JDOMetaDataHelper method getXMLForMetaData.

public String getXMLForMetaData(PackageMetaData pmd, String prefix, String indent) {
    StringBuilder str = new StringBuilder();
    str.append(prefix).append("<package name=\"" + pmd.getName() + "\"");
    if (pmd.getCatalog() != null) {
        str.append(" catalog=\"" + pmd.getCatalog() + "\"");
    }
    if (pmd.getSchema() != null) {
        str.append(" schema=\"" + pmd.getSchema() + "\"");
    }
    str.append(">\n");
    // Add interfaces
    if (pmd.getNoOfInterfaces() > 0) {
        for (int i = 0; i < pmd.getNoOfInterfaces(); i++) {
            InterfaceMetaData imd = pmd.getInterface(i);
            str.append(getXMLForMetaData(imd, prefix + indent, indent));
        }
    }
    // Add classes
    if (pmd.getNoOfClasses() > 0) {
        for (int i = 0; i < pmd.getNoOfClasses(); i++) {
            ClassMetaData cmd = pmd.getClass(i);
            str.append(getXMLForMetaData(cmd, prefix + indent, indent));
        }
    }
    // Add sequences
    SequenceMetaData[] seqmds = pmd.getSequences();
    if (seqmds != null) {
        for (SequenceMetaData seqmd : seqmds) {
            str.append(getXMLForMetaData(seqmd, prefix + indent, indent));
        }
    }
    // Add extensions
    processExtensions(pmd.getExtensions(), str, prefix, indent);
    str.append(prefix).append("</package>\n");
    return str.toString();
}
Also used : InterfaceMetaData(org.datanucleus.metadata.InterfaceMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData)

Aggregations

SequenceMetaData (org.datanucleus.metadata.SequenceMetaData)11 ClassMetaData (org.datanucleus.metadata.ClassMetaData)5 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)4 NucleusContext (org.datanucleus.NucleusContext)3 PersistenceNucleusContextImpl (org.datanucleus.PersistenceNucleusContextImpl)3 JPAMetaDataManager (org.datanucleus.api.jpa.metadata.JPAMetaDataManager)3 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)3 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)3 PackageMetaData (org.datanucleus.metadata.PackageMetaData)3 IOException (java.io.IOException)2 NucleusException (org.datanucleus.exceptions.NucleusException)2 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)2 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)2 DiscriminatorMetaData (org.datanucleus.metadata.DiscriminatorMetaData)2 FetchGroupMemberMetaData (org.datanucleus.metadata.FetchGroupMemberMetaData)2 FetchGroupMetaData (org.datanucleus.metadata.FetchGroupMetaData)2 FetchPlanMetaData (org.datanucleus.metadata.FetchPlanMetaData)2 FileMetaData (org.datanucleus.metadata.FileMetaData)2 MetaDataManager (org.datanucleus.metadata.MetaDataManager)2 PersistenceUnitMetaData (org.datanucleus.metadata.PersistenceUnitMetaData)2