Search in sources :

Example 16 with FileMetaData

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

the class PersistenceNucleusContextImpl method initialiseSchema.

/**
 * Method to handle generation (create, drop, drop+create) of a schema at initialisation.
 * Will generate the schema for all classes that have had their metadata loaded at this point, which
 * typically means the persistence-unit.
 * @param generateModeStr Generate "mode"
 * @param generateScripts Whether to generate
 */
protected void initialiseSchema(String generateModeStr, boolean generateScripts) {
    Mode mode = null;
    if (generateModeStr.equalsIgnoreCase("create")) {
        mode = Mode.CREATE;
    } else if (generateModeStr.equalsIgnoreCase("drop")) {
        mode = Mode.DELETE;
    } else if (generateModeStr.equalsIgnoreCase("drop-and-create")) {
        mode = Mode.DELETE_CREATE;
    }
    if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
        if (mode == Mode.CREATE) {
            NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("014000"));
        } else if (mode == Mode.DELETE) {
            NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("014001"));
        } else if (mode == Mode.DELETE_CREATE) {
            NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("014045"));
        }
    }
    // Extract the classes that have metadata loaded (e.g persistence-unit)
    Set<String> schemaClassNames = null;
    MetaDataManager metaDataMgr = getMetaDataManager();
    FileMetaData[] filemds = metaDataMgr.getFileMetaData();
    schemaClassNames = new TreeSet<String>();
    if (filemds == null) {
        throw new NucleusUserException("No classes to process in generateSchema");
    }
    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 (!schemaClassNames.contains(className)) {
                    schemaClassNames.add(className);
                }
            }
        }
    }
    StoreManager storeMgr = getStoreManager();
    if (storeMgr instanceof SchemaAwareStoreManager) {
        SchemaAwareStoreManager schemaStoreMgr = (SchemaAwareStoreManager) storeMgr;
        SchemaTool schemaTool = new SchemaTool();
        if (mode == Mode.CREATE) {
            if (generateScripts) {
                // Generate the required script
                schemaTool.setDdlFile(config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_CREATE_TARGET));
                schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
            } else {
                // Process the required metadata/script
                String createOrder = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_CREATE_ORDER);
                String createScript = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_CREATE_SOURCE);
                if (StringUtils.isWhitespace(createScript)) {
                    createScript = null;
                }
                if (StringUtils.isWhitespace(createOrder)) {
                    createOrder = (createScript != null) ? "script" : "metadata";
                } else {
                    if (createOrder.equals("script") || createOrder.equals("metadata-then-script") || createOrder.equals("script-the-metadata")) {
                        if (createScript == null) {
                            NucleusLogger.DATASTORE_SCHEMA.warn("create order set to " + createOrder + " but no script defined, so using metadata instead");
                            createOrder = "metadata";
                        }
                    }
                }
                if (createOrder.equals("script")) {
                    processDatastoreScript(createScript);
                } else if (createOrder.equals("script-then-metadata")) {
                    processDatastoreScript(createScript);
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                } else if (createOrder.equals("metadata-then-script")) {
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                    processDatastoreScript(createScript);
                } else {
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                }
            }
        } else if (mode == Mode.DELETE) {
            if (generateScripts) {
                // Generate the required script
                schemaTool.setDdlFile(config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_DROP_TARGET));
                schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
            } else {
                // Process the required metadata/script
                String dropOrder = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_DROP_ORDER);
                String dropScript = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_DROP_SOURCE);
                if (StringUtils.isWhitespace(dropScript)) {
                    dropScript = null;
                }
                if (StringUtils.isWhitespace(dropOrder)) {
                    dropOrder = (dropScript != null) ? "script" : "metadata";
                } else {
                    if (dropOrder.equals("script") || dropOrder.equals("metadata-then-script") || dropOrder.equals("script-the-metadata")) {
                        if (dropScript == null) {
                            NucleusLogger.DATASTORE_SCHEMA.warn("drop order set to " + dropOrder + " but no script defined, so using metadata instead");
                            dropOrder = "metadata";
                        }
                    }
                }
                if (dropOrder.equals("script")) {
                    processDatastoreScript(dropScript);
                } else if (dropOrder.equals("script-then-metadata")) {
                    processDatastoreScript(dropScript);
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                } else if (dropOrder.equals("metadata-then-script")) {
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                    processDatastoreScript(dropScript);
                } else {
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                }
            }
        } else if (mode == Mode.DELETE_CREATE) {
            if (generateScripts) {
                // Generate the required scripts
                schemaTool.setDdlFile(config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_DROP_TARGET));
                schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                schemaTool.setDdlFile(config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_CREATE_TARGET));
                schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
            } else {
                // Process the required metadata/scripts
                String dropOrder = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_DROP_ORDER);
                String dropScript = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_DROP_SOURCE);
                if (StringUtils.isWhitespace(dropScript)) {
                    dropScript = null;
                }
                if (StringUtils.isWhitespace(dropOrder)) {
                    dropOrder = (dropScript != null) ? "script" : "metadata";
                } else {
                    if (dropOrder.equals("script") || dropOrder.equals("metadata-then-script") || dropOrder.equals("script-the-metadata")) {
                        if (dropScript == null) {
                            NucleusLogger.DATASTORE_SCHEMA.warn("drop order set to " + dropOrder + " but no script defined, so using metadata instead");
                            dropOrder = "metadata";
                        }
                    }
                }
                if (dropOrder.equals("script")) {
                    processDatastoreScript(dropScript);
                } else if (dropOrder.equals("script-then-metadata")) {
                    processDatastoreScript(dropScript);
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                } else if (dropOrder.equals("metadata-then-script")) {
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                    processDatastoreScript(dropScript);
                } else {
                    schemaTool.deleteSchemaForClasses(schemaStoreMgr, schemaClassNames);
                }
                String createOrder = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_CREATE_ORDER);
                String createScript = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_CREATE_SOURCE);
                if (StringUtils.isWhitespace(createScript)) {
                    createScript = null;
                }
                if (StringUtils.isWhitespace(createOrder)) {
                    createOrder = (createScript != null) ? "script" : "metadata";
                } else {
                    if (createOrder.equals("script") || createOrder.equals("metadata-then-script") || createOrder.equals("script-the-metadata")) {
                        if (createScript == null) {
                            NucleusLogger.DATASTORE_SCHEMA.warn("create order set to " + createOrder + " but no script defined, so using metadata instead");
                            createOrder = "metadata";
                        }
                    }
                }
                if (createOrder.equals("script")) {
                    processDatastoreScript(createScript);
                } else if (createOrder.equals("script-then-metadata")) {
                    processDatastoreScript(createScript);
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                } else if (createOrder.equals("metadata-then-script")) {
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                    processDatastoreScript(createScript);
                } else {
                    schemaTool.createSchemaForClasses(schemaStoreMgr, schemaClassNames);
                }
            }
        }
        String loadScript = config.getStringProperty(PropertyNames.PROPERTY_SCHEMA_GENERATE_SCRIPTS_LOAD_SOURCE);
        if (!StringUtils.isWhitespace(loadScript)) {
            String scriptContent = getDatastoreScriptForResourceName(loadScript);
            if (storeMgr instanceof SchemaScriptAwareStoreManager && !StringUtils.isWhitespace(scriptContent)) {
                ((SchemaScriptAwareStoreManager) storeMgr).executeScript(scriptContent);
            }
        }
    } else {
        if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
            NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("008016", StringUtils.toJVMIDString(storeMgr)));
        }
    }
    if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
        NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("014043"));
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Mode(org.datanucleus.store.schema.SchemaTool.Mode) MetaDataManager(org.datanucleus.metadata.MetaDataManager) SchemaTool(org.datanucleus.store.schema.SchemaTool) SchemaAwareStoreManager(org.datanucleus.store.schema.SchemaAwareStoreManager) FederatedStoreManager(org.datanucleus.store.federation.FederatedStoreManager) StoreManager(org.datanucleus.store.StoreManager) SchemaScriptAwareStoreManager(org.datanucleus.store.schema.SchemaScriptAwareStoreManager) SchemaAwareStoreManager(org.datanucleus.store.schema.SchemaAwareStoreManager) SchemaScriptAwareStoreManager(org.datanucleus.store.schema.SchemaScriptAwareStoreManager) FileMetaData(org.datanucleus.metadata.FileMetaData)

Example 17 with FileMetaData

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

the class DataNucleusEnhancer method enhance.

/**
 * Method to enhance all classes defined by addClass, addClasses, addJar, addPersistenceUnit, addFiles.
 * @return Number of classes enhanced
 */
public int enhance() {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enhancing classes");
    }
    if (componentsToEnhance.isEmpty()) {
        // Nothing to enhance
        return 0;
    }
    // Load the meta-data for the registered components to enhance.
    long startTime = System.currentTimeMillis();
    Collection<FileMetaData> fileMetaData = getFileMetadataForInput();
    // Enhance the classes implied by the FileMetaData
    long inputTime = System.currentTimeMillis();
    Set<String> classNames = new HashSet<String>();
    Iterator<FileMetaData> filemdIter = fileMetaData.iterator();
    boolean success = true;
    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);
                // Enhance, but don't store if based on input bytes
                boolean clsSuccess = enhanceClass(cmd, classEnhancer, bytes == null);
                if (!clsSuccess) {
                    success = false;
                }
            }
        }
    }
    if (!success) {
        throw new NucleusException("Failure during enhancement of classes - see the log for details");
    }
    // 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) NucleusException(org.datanucleus.exceptions.NucleusException) FileMetaData(org.datanucleus.metadata.FileMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) HashSet(java.util.HashSet)

Example 18 with FileMetaData

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

the class DataNucleusEnhancer method getFileMetadataForInput.

/**
 * Method that processes the registered components to enhance, and loads the metadata for
 * them into the MetaDataManager, returning the associated FileMetaData.
 * @return The FileMetaData for the registered components.
 */
protected Collection<FileMetaData> getFileMetadataForInput() {
    Iterator<EnhanceComponent> iter = componentsToEnhance.iterator();
    Collection<FileMetaData> fileMetaData = new ArrayList<FileMetaData>();
    while (iter.hasNext()) {
        EnhanceComponent comp = iter.next();
        FileMetaData[] filemds = null;
        switch(comp.getType()) {
            case // Of the form "mydomain.MyClass"
            EnhanceComponent.CLASS:
                if (comp.getValue() instanceof String) {
                    // Single class
                    String className = (String) comp.getValue();
                    if (bytesForClassesToEnhanceByClassName != null && bytesForClassesToEnhanceByClassName.get(className) != null) {
                        // Retrieve the meta-data "file"
                        AbstractClassMetaData cmd = metadataMgr.getMetaDataForClass(className, clr);
                        if (cmd != null) {
                            filemds = new FileMetaData[] { cmd.getPackageMetaData().getFileMetaData() };
                        } else {
                        // No meta-data has been registered for this byte-defined class!
                        }
                    } else {
                        filemds = metadataMgr.loadClasses(new String[] { (String) comp.getValue() }, userClassLoader);
                    }
                } else {
                    // Multiple classes
                    filemds = metadataMgr.loadClasses((String[]) comp.getValue(), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.CLASS_FILE:
                if (comp.getValue() instanceof String) {
                    // Single class file
                    String className = null;
                    String classFilename = (String) comp.getValue();
                    if (!StringUtils.getFileForFilename(classFilename).exists()) {
                        String msg = Localiser.msg("005003", classFilename);
                        addMessage(msg, true);
                    } else {
                        className = ClassEnhancerImpl.getClassNameForFileName(classFilename);
                    }
                    if (className != null) {
                        filemds = metadataMgr.loadClasses(new String[] { className }, userClassLoader);
                    }
                } else {
                    // Multiple class files
                    Collection<String> classNames = new ArrayList<String>();
                    String[] classFilenames = (String[]) comp.getValue();
                    for (int i = 0; i < classFilenames.length; i++) {
                        String className = null;
                        if (!StringUtils.getFileForFilename(classFilenames[i]).exists()) {
                            String msg = Localiser.msg("005003", classFilenames[i]);
                            addMessage(msg, true);
                        } else {
                            className = ClassEnhancerImpl.getClassNameForFileName(classFilenames[i]);
                        }
                        if (className != null) {
                            classNames.add(className);
                        }
                    }
                    filemds = metadataMgr.loadClasses(classNames.toArray(new String[classNames.size()]), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.MAPPING_FILE:
                if (comp.getValue() instanceof String) {
                    // Single mapping file
                    filemds = metadataMgr.loadMetadataFiles(new String[] { (String) comp.getValue() }, userClassLoader);
                } else {
                    // Multiple mapping files
                    filemds = metadataMgr.loadMetadataFiles((String[]) comp.getValue(), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.JAR_FILE:
                if (comp.getValue() instanceof String) {
                    // Single jar file
                    filemds = metadataMgr.loadJar((String) comp.getValue(), userClassLoader);
                } else {
                    // Multiple jar files
                    String[] jarFilenames = (String[]) comp.getValue();
                    Collection<FileMetaData> filemdsColl = new HashSet<FileMetaData>();
                    for (int i = 0; i < jarFilenames.length; i++) {
                        FileMetaData[] fmds = metadataMgr.loadJar(jarFilenames[i], userClassLoader);
                        for (int j = 0; j < fmds.length; j++) {
                            filemdsColl.add(fmds[j]);
                        }
                    }
                    filemds = filemdsColl.toArray(new FileMetaData[filemdsColl.size()]);
                }
                break;
            case EnhanceComponent.PERSISTENCE_UNIT:
                PersistenceUnitMetaData pumd = null;
                try {
                    Object puValue = comp.getValue();
                    if (puValue instanceof String) {
                        // Extract the metadata for the persistence-unit
                        NucleusContext nucleusCtx = metadataMgr.getNucleusContext();
                        String filename = nucleusCtx.getConfiguration().getStringProperty(PropertyNames.PROPERTY_PERSISTENCE_XML_FILENAME);
                        boolean validateXML = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_VALIDATE);
                        boolean supportXMLNamespaces = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_NAMESPACE_AWARE);
                        pumd = MetaDataUtils.getMetaDataForPersistenceUnit(nucleusCtx.getPluginManager(), filename, (String) comp.getValue(), validateXML, supportXMLNamespaces, clr);
                    } else {
                        pumd = (PersistenceUnitMetaData) puValue;
                    }
                } catch (NucleusException ne) {
                    // No "persistence.xml" files found yet they have specified a persistence-unit name!
                    throw new NucleusEnhanceException(Localiser.msg("005008", comp.getValue()));
                }
                if (pumd == null) {
                    throw new NucleusEnhanceException(Localiser.msg("005009", comp.getValue()));
                }
                filemds = metadataMgr.loadPersistenceUnit(pumd, userClassLoader);
                break;
            default:
                break;
        }
        if (filemds != null) {
            for (int i = 0; i < filemds.length; i++) {
                fileMetaData.add(filemds[i]);
            }
        }
    }
    return fileMetaData;
}
Also used : NucleusContext(org.datanucleus.NucleusContext) ArrayList(java.util.ArrayList) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) NucleusException(org.datanucleus.exceptions.NucleusException) FileMetaData(org.datanucleus.metadata.FileMetaData) HashSet(java.util.HashSet)

Example 19 with FileMetaData

use of org.datanucleus.metadata.FileMetaData in project tests by datanucleus.

the class JDOMetadataAPITest method testPackageClassInterface.

/**
 * Simple test that checks the numbers of packages, classes, interfaces contained.
 */
public void testPackageClassInterface() {
    JDOMetadata jdomd = pmf.newMetadata();
    PackageMetadata pmd1 = jdomd.newPackageMetadata("org.datanucleus.test");
    pmd1.newClassMetadata("MyClass1");
    pmd1.newClassMetadata("MyClass2");
    PackageMetadata pmd2 = jdomd.newPackageMetadata("org.datanucleus.test2");
    pmd2.newInterfaceMetadata("org.datanucleus.test3");
    // Check the JDO metadata
    assertEquals("Number of packages in JDO metadata is incorrect", 2, jdomd.getNumberOfPackages());
    assertEquals("Number of classes in JDO package metadata 1 is incorrect", 2, pmd1.getNumberOfClasses());
    assertEquals("Number of interfaces in JDO package metadata 1 is incorrect", 0, pmd1.getNumberOfInterfaces());
    assertEquals("Number of classes in JDO package metadata 2 is incorrect", 0, pmd2.getNumberOfClasses());
    assertEquals("Number of interfaces in JDO package metadata 2 is incorrect", 1, pmd2.getNumberOfInterfaces());
    // Check the internal metadata
    FileMetaData filemd = ((JDOMetadataImpl) jdomd).getInternal();
    assertEquals("Number of packages is incorrect", 2, filemd.getNoOfPackages());
}
Also used : JDOMetadataImpl(org.datanucleus.api.jdo.metadata.JDOMetadataImpl) JDOMetadata(javax.jdo.metadata.JDOMetadata) PackageMetadata(javax.jdo.metadata.PackageMetadata) 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