Search in sources :

Example 1 with FileMetaData

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

the class DataNucleusEnhancer method validate.

/**
 * Method to validate all classes defined by addClass, addClasses, addJar, addPersistenceUnit, addFiles.
 * @return Number of classes validated
 */
public int validate() {
    if (componentsToEnhance.isEmpty()) {
        // Nothing to validate
        return 0;
    }
    // Load the meta-data for the registered components to enhance.
    long startTime = System.currentTimeMillis();
    Collection<FileMetaData> fileMetaData = getFileMetadataForInput();
    // Validate the classes implied by the FileMetaData
    long inputTime = System.currentTimeMillis();
    Set<String> classNames = new HashSet<String>();
    Iterator<FileMetaData> filemdIter = fileMetaData.iterator();
    while (filemdIter.hasNext()) {
        FileMetaData filemd = filemdIter.next();
        for (int packagenum = 0; packagenum < filemd.getNoOfPackages(); packagenum++) {
            PackageMetaData pmd = filemd.getPackage(packagenum);
            for (int classnum = 0; classnum < pmd.getNoOfClasses(); classnum++) {
                ClassMetaData cmd = pmd.getClass(classnum);
                if (classNames.contains(cmd.getFullClassName())) {
                    // Already processed, maybe via annotations and this is MetaData
                    continue;
                }
                classNames.add(cmd.getFullClassName());
                byte[] bytes = bytesForClassesToEnhanceByClassName != null ? bytesForClassesToEnhanceByClassName.get(cmd.getFullClassName()) : null;
                ClassEnhancer classEnhancer = getClassEnhancer(cmd, bytes);
                validateClass(cmd, classEnhancer);
            }
        }
    }
    // Log info about timings
    long enhanceTime = System.currentTimeMillis();
    String msg = null;
    if (verbose) {
        msg = Localiser.msg("005004", classNames.size(), "" + (inputTime - startTime), "" + (enhanceTime - inputTime), "" + (enhanceTime - startTime));
    } else {
        msg = Localiser.msg("005005", classNames.size());
    }
    addMessage(msg, false);
    // Remove the input specification
    if (bytesForClassesToEnhanceByClassName != null) {
        bytesForClassesToEnhanceByClassName.clear();
        bytesForClassesToEnhanceByClassName = null;
    }
    componentsToEnhance.clear();
    return classNames.size();
}
Also used : PackageMetaData(org.datanucleus.metadata.PackageMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) HashSet(java.util.HashSet)

Example 2 with FileMetaData

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

the class SchemaTool method main.

/**
 * Entry method when invoked from the command line.
 * @param args List of options for processing by the available methods in this class.
 * @throws Exception If an error occurs in operation
 */
public static void main(String[] args) throws Exception {
    SchemaTool tool = new SchemaTool();
    CommandLine cmd = new CommandLine();
    cmd.addOption(OPTION_CREATE_DATABASE, OPTION_CREATE_DATABASE, null, Localiser.msg("014024"));
    cmd.addOption(OPTION_DELETE_DATABASE, OPTION_DELETE_DATABASE, null, Localiser.msg("014025"));
    cmd.addOption(OPTION_CREATE_TABLES_FOR_CLASSES, OPTION_CREATE_TABLES_FOR_CLASSES, null, Localiser.msg("014026"));
    cmd.addOption(OPTION_DELETE_TABLES_FOR_CLASSES, OPTION_DELETE_TABLES_FOR_CLASSES, null, Localiser.msg("014027"));
    cmd.addOption(OPTION_DELETE_CREATE_TABLES_FOR_CLASSES, OPTION_DELETE_CREATE_TABLES_FOR_CLASSES, null, Localiser.msg("014044"));
    cmd.addOption(OPTION_VALIDATE_TABLES_FOR_CLASSES, OPTION_VALIDATE_TABLES_FOR_CLASSES, null, Localiser.msg("014028"));
    cmd.addOption(OPTION_DBINFO, OPTION_DBINFO, null, Localiser.msg("014029"));
    cmd.addOption(OPTION_SCHEMAINFO, OPTION_SCHEMAINFO, null, Localiser.msg("014030"));
    cmd.addOption("help", "help", null, Localiser.msg("014033"));
    cmd.addOption(OPTION_DDL_FILE, OPTION_DDL_FILE, "ddlFile", Localiser.msg("014031"));
    cmd.addOption(OPTION_COMPLETE_DDL, OPTION_COMPLETE_DDL, null, Localiser.msg("014032"));
    cmd.addOption(OPTION_INCLUDE_AUTO_START, OPTION_INCLUDE_AUTO_START, null, "Include Auto-Start Mechanisms");
    cmd.addOption(OPTION_API, OPTION_API, "api", "API Adapter (JDO, JPA, etc)");
    cmd.addOption(OPTION_CATALOG_NAME, OPTION_CATALOG_NAME, "catalog", "CatalogName");
    cmd.addOption(OPTION_SCHEMA_NAME, OPTION_SCHEMA_NAME, "schema", "SchemaName");
    cmd.addOption("v", "verbose", null, "verbose output");
    cmd.addOption("pu", "persistenceUnit", "<persistence-unit>", "name of the persistence unit to handle the schema for");
    cmd.addOption("props", "properties", "props", "path to a properties file");
    cmd.addOption("ignoreMetaDataForMissingClasses", "ignoreMetaDataForMissingClasses", null, "Ignore metadata for classes that are missing?");
    cmd.parse(args);
    // Remaining command line args are filenames (class files, metadata files)
    String[] filenames = cmd.getDefaultArgs();
    if (cmd.hasOption("api")) {
        tool.setApi(cmd.getOptionArg("api"));
    }
    if (cmd.hasOption(OPTION_CATALOG_NAME)) {
        tool.setCatalogName(cmd.getOptionArg(OPTION_CATALOG_NAME));
    }
    if (cmd.hasOption(OPTION_SCHEMA_NAME)) {
        NucleusLogger.GENERAL.info(">> sch input = " + cmd.getOptionArg(OPTION_SCHEMA_NAME));
        tool.setSchemaName(cmd.getOptionArg(OPTION_SCHEMA_NAME));
    }
    // Determine the mode of operation required
    String msg = null;
    Mode mode = Mode.CREATE;
    if (cmd.hasOption(OPTION_CREATE_TABLES_FOR_CLASSES)) {
        mode = Mode.CREATE;
        msg = Localiser.msg("014000");
    } else if (cmd.hasOption(OPTION_DELETE_TABLES_FOR_CLASSES)) {
        mode = Mode.DELETE;
        msg = Localiser.msg("014001");
    } else if (cmd.hasOption(OPTION_DELETE_CREATE_TABLES_FOR_CLASSES)) {
        mode = Mode.DELETE_CREATE;
        msg = Localiser.msg("014045");
    } else if (cmd.hasOption(OPTION_VALIDATE_TABLES_FOR_CLASSES)) {
        mode = Mode.VALIDATE;
        msg = Localiser.msg("014002");
    } else if (cmd.hasOption(OPTION_CREATE_DATABASE)) {
        mode = Mode.CREATE_DATABASE;
        msg = Localiser.msg("014034", tool.getCatalogName(), tool.getSchemaName());
    } else if (cmd.hasOption(OPTION_DELETE_DATABASE)) {
        mode = Mode.DELETE_DATABASE;
        msg = Localiser.msg("014035", tool.getCatalogName(), tool.getSchemaName());
    } else if (cmd.hasOption(OPTION_DBINFO)) {
        mode = Mode.DATABASE_INFO;
        msg = Localiser.msg("014003");
    } else if (cmd.hasOption(OPTION_SCHEMAINFO)) {
        mode = Mode.SCHEMA_INFO;
        msg = Localiser.msg("014004");
    } else if (cmd.hasOption("help")) {
        System.out.println(Localiser.msg("014023", cmd.toString()));
        System.exit(0);
    }
    LOGGER.info(msg);
    System.out.println(msg);
    // Extract the selected options
    String propsFileName = null;
    String persistenceUnitName = null;
    if (cmd.hasOption(OPTION_DDL_FILE)) {
        tool.setDdlFile(cmd.getOptionArg(OPTION_DDL_FILE));
    }
    if (cmd.hasOption(OPTION_COMPLETE_DDL)) {
        tool.setCompleteDdl(true);
    }
    if (cmd.hasOption(OPTION_INCLUDE_AUTO_START)) {
        tool.setIncludeAutoStart(true);
    }
    if (cmd.hasOption("v")) {
        tool.setVerbose(true);
    }
    boolean ignoreMetaDataForMissingClasses = false;
    if (cmd.hasOption("ignoreMetaDataForMissingClasses")) {
        ignoreMetaDataForMissingClasses = true;
    }
    if (cmd.hasOption("pu")) {
        persistenceUnitName = cmd.getOptionArg("pu");
    }
    if (cmd.hasOption("props")) {
        propsFileName = cmd.getOptionArg("props");
    }
    // Classpath
    msg = Localiser.msg("014005");
    LOGGER.info(msg);
    if (tool.isVerbose()) {
        System.out.println(msg);
    }
    StringTokenizer tokeniser = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    while (tokeniser.hasMoreTokens()) {
        msg = Localiser.msg("014006", tokeniser.nextToken());
        LOGGER.info(msg);
        if (tool.isVerbose()) {
            System.out.println(msg);
        }
    }
    if (tool.isVerbose()) {
        System.out.println();
    }
    // DDL file
    String ddlFilename = tool.getDdlFile();
    if (ddlFilename != null) {
        msg = Localiser.msg(tool.getCompleteDdl() ? "014018" : "014019", ddlFilename);
        LOGGER.info(msg);
        if (tool.isVerbose()) {
            System.out.println(msg);
            System.out.println();
        }
    }
    // Create a NucleusContext for use with this mode
    StoreNucleusContext nucleusCtx = null;
    try {
        Properties props = (propsFileName != null) ? PersistenceUtils.setPropertiesUsingFile(propsFileName) : null;
        nucleusCtx = getNucleusContextForMode(mode, tool.getApi(), props, persistenceUnitName, ddlFilename, tool.isVerbose(), ignoreMetaDataForMissingClasses);
    } catch (Exception e) {
        // Unable to create a NucleusContext so likely input errors
        LOGGER.error("Error creating NucleusContext", e);
        System.out.println(Localiser.msg("014008", e.getMessage()));
        System.exit(1);
        return;
    }
    Set<String> classNames = null;
    if (mode != Mode.SCHEMA_INFO && mode != Mode.DATABASE_INFO) {
        // This will load up all MetaData for the specified input and throw exceptions where errors are found
        try {
            MetaDataManager metaDataMgr = nucleusCtx.getMetaDataManager();
            ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null);
            if (filenames == null && persistenceUnitName == null) {
                msg = Localiser.msg("014007");
                LOGGER.error(msg);
                System.out.println(msg);
                throw new NucleusUserException(msg);
            }
            FileMetaData[] filemds = null;
            if (persistenceUnitName != null) {
                // Schema management via "persistence-unit"
                msg = Localiser.msg("014015", persistenceUnitName);
                LOGGER.info(msg);
                if (tool.isVerbose()) {
                    System.out.println(msg);
                    System.out.println();
                }
                // The NucleusContext will have initialised the MetaDataManager with the persistence-unit
                filemds = metaDataMgr.getFileMetaData();
            } else {
                // Schema management via "Input Files" (metadata/class)
                msg = Localiser.msg("014009");
                LOGGER.info(msg);
                if (tool.isVerbose()) {
                    System.out.println(msg);
                }
                for (int i = 0; i < filenames.length; i++) {
                    String entry = Localiser.msg("014010", filenames[i]);
                    LOGGER.info(entry);
                    if (tool.isVerbose()) {
                        System.out.println(entry);
                    }
                }
                if (tool.isVerbose()) {
                    System.out.println();
                }
                LOGGER.debug(Localiser.msg("014011", "" + filenames.length));
                filemds = MetaDataUtils.getFileMetaDataForInputFiles(metaDataMgr, clr, filenames);
                LOGGER.debug(Localiser.msg("014012", "" + filenames.length));
            }
            classNames = new TreeSet<String>();
            if (filemds == null) {
                msg = Localiser.msg("014021");
                LOGGER.error(msg);
                System.out.println(msg);
                System.exit(2);
                return;
            }
            for (int i = 0; i < filemds.length; i++) {
                for (int j = 0; j < filemds[i].getNoOfPackages(); j++) {
                    for (int k = 0; k < filemds[i].getPackage(j).getNoOfClasses(); k++) {
                        String className = filemds[i].getPackage(j).getClass(k).getFullClassName();
                        if (!classNames.contains(className)) {
                            classNames.add(className);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // Exception will have been logged and sent to System.out in "getFileMetaDataForInput()"
            System.exit(2);
            return;
        }
    }
    // Run SchemaTool
    StoreManager storeMgr = nucleusCtx.getStoreManager();
    if (!(storeMgr instanceof SchemaAwareStoreManager)) {
        LOGGER.error("StoreManager of type " + storeMgr.getClass().getName() + " is not schema-aware so cannot be used with SchemaTool");
        System.exit(2);
        return;
    }
    SchemaAwareStoreManager schemaStoreMgr = (SchemaAwareStoreManager) storeMgr;
    try {
        if (mode == Mode.CREATE_DATABASE) {
            tool.createDatabase(schemaStoreMgr, tool.getCatalogName(), tool.getSchemaName());
        } else if (mode == Mode.DELETE_DATABASE) {
            tool.deleteDatabase(schemaStoreMgr, tool.getCatalogName(), tool.getSchemaName());
        } else if (mode == Mode.CREATE) {
            tool.createSchemaForClasses(schemaStoreMgr, classNames);
        } else if (mode == Mode.DELETE) {
            tool.deleteSchemaForClasses(schemaStoreMgr, classNames);
        } else if (mode == Mode.DELETE_CREATE) {
            tool.deleteSchemaForClasses(schemaStoreMgr, classNames);
            tool.createSchemaForClasses(schemaStoreMgr, classNames);
        } else if (mode == Mode.VALIDATE) {
            tool.validateSchemaForClasses(schemaStoreMgr, classNames);
        } else if (mode == Mode.DATABASE_INFO) {
            storeMgr.printInformation("DATASTORE", System.out);
        } else if (mode == Mode.SCHEMA_INFO) {
            storeMgr.printInformation("SCHEMA", System.out);
        }
        msg = Localiser.msg("014043");
        LOGGER.info(msg);
        System.out.println(msg);
    } catch (Exception e) {
        msg = Localiser.msg("014037", e.getMessage());
        System.out.println(msg);
        LOGGER.error(msg, e);
        System.exit(2);
        return;
    } finally {
        storeMgr.close();
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) MetaDataManager(org.datanucleus.metadata.MetaDataManager) Properties(java.util.Properties) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NucleusException(org.datanucleus.exceptions.NucleusException) SchemaAwareStoreManager(org.datanucleus.store.schema.SchemaAwareStoreManager) StoreManager(org.datanucleus.store.StoreManager) SchemaAwareStoreManager(org.datanucleus.store.schema.SchemaAwareStoreManager) CommandLine(org.datanucleus.util.CommandLine) StringTokenizer(java.util.StringTokenizer) StoreNucleusContext(org.datanucleus.StoreNucleusContext) FileMetaData(org.datanucleus.metadata.FileMetaData)

Example 3 with FileMetaData

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

the class MetaDataAutoStarter method getAllClassData.

/**
 * Accessor for all auto start data for this starter.
 * @return The class auto start data. Collection of StoreData elements
 * @throws org.datanucleus.exceptions.DatastoreInitialisationException If an error occurs in datastore init
 */
public Collection<StoreData> getAllClassData() throws DatastoreInitialisationException {
    if (metaDataFiles == null) {
        return Collections.EMPTY_SET;
    }
    Collection<FileMetaData> fileMetaData = storeMgr.getNucleusContext().getMetaDataManager().loadFiles(metaDataFiles.split(","), clr);
    Iterator<FileMetaData> iter = fileMetaData.iterator();
    while (iter.hasNext()) {
        FileMetaData filemd = iter.next();
        for (int i = 0; i < filemd.getNoOfPackages(); i++) {
            PackageMetaData pmd = filemd.getPackage(i);
            for (int j = 0; j < pmd.getNoOfClasses(); j++) {
                ClassMetaData cmd = pmd.getClass(j);
                classes.add(new StoreData(cmd.getFullClassName().trim(), null, StoreData.Type.FCO, null));
            }
        }
    }
    return classes;
}
Also used : PackageMetaData(org.datanucleus.metadata.PackageMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) StoreData(org.datanucleus.store.StoreData)

Example 4 with FileMetaData

use of org.datanucleus.metadata.FileMetaData 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 5 with FileMetaData

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

the class JDOMetaDataManager method getMetaDataForInterface.

// ------------------------------- Persistent Interfaces ---------------------------------------
/**
 * Main accessor for the MetaData for a "persistent-interface".
 * All MetaData returned from this method will be initialised and ready for full use.
 * @param c The interface to find MetaData for
 * @param clr the ClassLoaderResolver
 * @return The InterfaceMetaData for this interface (or null if not found)
 */
public InterfaceMetaData getMetaDataForInterface(Class c, ClassLoaderResolver clr) {
    if (c == null || !c.isInterface()) {
        return null;
    }
    InterfaceMetaData imd = (InterfaceMetaData) getMetaDataForClassInternal(c, clr);
    if (imd != null) {
        // Make sure that anything returned is populated/initialised
        populateAbstractClassMetaData(imd, clr, c.getClassLoader());
        initialiseAbstractClassMetaData(imd, clr);
        if (!utilisedFileMetaData.isEmpty()) {
            // Initialise all FileMetaData that were processed in this call
            Iterator iter = utilisedFileMetaData.iterator();
            while (iter.hasNext()) {
                FileMetaData filemd = (FileMetaData) iter.next();
                initialiseFileMetaData(filemd, clr, c.getClassLoader());
            }
        }
    }
    utilisedFileMetaData.clear();
    return imd;
}
Also used : Iterator(java.util.Iterator) InterfaceMetaData(org.datanucleus.metadata.InterfaceMetaData) FileMetaData(org.datanucleus.metadata.FileMetaData)

Aggregations

FileMetaData (org.datanucleus.metadata.FileMetaData)19 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)10 NucleusException (org.datanucleus.exceptions.NucleusException)6 ClassMetaData (org.datanucleus.metadata.ClassMetaData)6 MetaDataManager (org.datanucleus.metadata.MetaDataManager)6 PackageMetaData (org.datanucleus.metadata.PackageMetaData)6 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 URL (java.net.URL)3 Enumeration (java.util.Enumeration)3 HashSet (java.util.HashSet)3 InterfaceMetaData (org.datanucleus.metadata.InterfaceMetaData)3 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)2 ClassLoaderResolverImpl (org.datanucleus.ClassLoaderResolverImpl)2 NucleusContext (org.datanucleus.NucleusContext)2 JDOMetaDataManager (org.datanucleus.api.jdo.metadata.JDOMetaDataManager)2 JDOMetadataImpl (org.datanucleus.api.jdo.metadata.JDOMetadataImpl)2 EnhancementNucleusContextImpl (org.datanucleus.enhancer.EnhancementNucleusContextImpl)2 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)2 QueryMetaData (org.datanucleus.metadata.QueryMetaData)2