Search in sources :

Example 1 with StoreManager

use of org.datanucleus.store.StoreManager in project datanucleus-core by datanucleus.

the class NucleusContextHelper method createStoreManagerForProperties.

/**
 * Method to create a StoreManager based on the specified properties passed in.
 * @param props The overall persistence properties
 * @param datastoreProps Persistence properties to apply to the datastore
 * @param clr ClassLoader resolver
 * @param nucCtx NucleusContext
 * @return The StoreManager
 * @throws NucleusUserException if impossible to create the StoreManager (not in CLASSPATH?, invalid definition?)
 */
public static StoreManager createStoreManagerForProperties(Map<String, Object> props, Map<String, Object> datastoreProps, ClassLoaderResolver clr, NucleusContext nucCtx) {
    Extension[] exts = nucCtx.getPluginManager().getExtensionPoint("org.datanucleus.store_manager").getExtensions();
    Class[] ctrArgTypes = new Class[] { ClassConstants.CLASS_LOADER_RESOLVER, ClassConstants.PERSISTENCE_NUCLEUS_CONTEXT, Map.class };
    Object[] ctrArgs = new Object[] { clr, nucCtx, datastoreProps };
    StoreManager storeMgr = null;
    // Try using the URL of the data source
    String url = (String) props.get(PropertyNames.PROPERTY_CONNECTION_URL.toLowerCase());
    if (url != null) {
        int idx = url.indexOf(':');
        if (idx > -1) {
            url = url.substring(0, idx);
        }
        for (int e = 0; storeMgr == null && e < exts.length; e++) {
            ConfigurationElement[] confElm = exts[e].getConfigurationElements();
            for (int c = 0; storeMgr == null && c < confElm.length; c++) {
                String urlKey = confElm[c].getAttribute("url-key");
                if (url == null || urlKey.equalsIgnoreCase(url)) {
                    // Either no URL, or url defined so take this StoreManager
                    try {
                        storeMgr = (StoreManager) nucCtx.getPluginManager().createExecutableExtension("org.datanucleus.store_manager", "url-key", url == null ? urlKey : url, "class-name", ctrArgTypes, ctrArgs);
                    } catch (InvocationTargetException ex) {
                        Throwable t = ex.getTargetException();
                        if (t instanceof RuntimeException) {
                            throw (RuntimeException) t;
                        } else if (t instanceof Error) {
                            throw (Error) t;
                        } else {
                            throw new NucleusException(t.getMessage(), t).setFatal();
                        }
                    } catch (Exception ex) {
                        throw new NucleusException(ex.getMessage(), ex).setFatal();
                    }
                }
            }
        }
    } else {
        // Assumed to be using RDBMS since only that allows ConnectionFactory/ConnectionFactoryName TODO If any other stores start supporting ConnectionFactory then update this
        try {
            storeMgr = (StoreManager) nucCtx.getPluginManager().createExecutableExtension("org.datanucleus.store_manager", "key", "rdbms", "class-name", ctrArgTypes, ctrArgs);
        } catch (InvocationTargetException ex) {
            Throwable t = ex.getTargetException();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else if (t instanceof Error) {
                throw (Error) t;
            } else {
                throw new NucleusException(t.getMessage(), t).setFatal();
            }
        } catch (Exception ex) {
            throw new NucleusException(ex.getMessage(), ex).setFatal();
        }
    }
    if (storeMgr == null) {
        throw new NucleusUserException(Localiser.msg("008004", url)).setFatal();
    }
    return storeMgr;
}
Also used : ConfigurationElement(org.datanucleus.plugin.ConfigurationElement) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) InvocationTargetException(java.lang.reflect.InvocationTargetException) TransactionIsolationNotSupportedException(org.datanucleus.exceptions.TransactionIsolationNotSupportedException) NucleusException(org.datanucleus.exceptions.NucleusException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) InvocationTargetException(java.lang.reflect.InvocationTargetException) StoreManager(org.datanucleus.store.StoreManager) Extension(org.datanucleus.plugin.Extension) NucleusException(org.datanucleus.exceptions.NucleusException) Map(java.util.Map)

Example 2 with StoreManager

use of org.datanucleus.store.StoreManager 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 StoreManager

use of org.datanucleus.store.StoreManager in project datanucleus-core by datanucleus.

the class FederatedPersistenceHandler method locateObject.

/* (non-Javadoc)
     * @see org.datanucleus.store.StorePersistenceHandler#locateObject(org.datanucleus.store.ObjectProvider)
     */
public void locateObject(ObjectProvider op) {
    StoreManager classStoreMgr = storeMgr.getStoreManagerForClass(op.getClassMetaData());
    classStoreMgr.getPersistenceHandler().locateObject(op);
}
Also used : StoreManager(org.datanucleus.store.StoreManager)

Example 4 with StoreManager

use of org.datanucleus.store.StoreManager in project datanucleus-core by datanucleus.

the class FederatedPersistenceHandler method updateObject.

/* (non-Javadoc)
     * @see org.datanucleus.store.StorePersistenceHandler#updateObject(org.datanucleus.store.ObjectProvider, int[])
     */
public void updateObject(ObjectProvider op, int[] fieldNumbers) {
    StoreManager classStoreMgr = storeMgr.getStoreManagerForClass(op.getClassMetaData());
    classStoreMgr.getPersistenceHandler().updateObject(op, fieldNumbers);
}
Also used : StoreManager(org.datanucleus.store.StoreManager)

Example 5 with StoreManager

use of org.datanucleus.store.StoreManager in project datanucleus-core by datanucleus.

the class FederatedPersistenceHandler method deleteObject.

/* (non-Javadoc)
     * @see org.datanucleus.store.StorePersistenceHandler#deleteObject(org.datanucleus.store.ObjectProvider)
     */
public void deleteObject(ObjectProvider op) {
    StoreManager classStoreMgr = storeMgr.getStoreManagerForClass(op.getClassMetaData());
    classStoreMgr.getPersistenceHandler().deleteObject(op);
}
Also used : StoreManager(org.datanucleus.store.StoreManager)

Aggregations

StoreManager (org.datanucleus.store.StoreManager)13 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)4 NucleusException (org.datanucleus.exceptions.NucleusException)3 SchemaAwareStoreManager (org.datanucleus.store.schema.SchemaAwareStoreManager)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)2 FileMetaData (org.datanucleus.metadata.FileMetaData)2 MetaDataManager (org.datanucleus.metadata.MetaDataManager)2 SchemaTool (org.datanucleus.store.schema.SchemaTool)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 HashMap (java.util.HashMap)1 Properties (java.util.Properties)1 StringTokenizer (java.util.StringTokenizer)1 JDOMetadata (javax.jdo.metadata.JDOMetadata)1 PersistenceNucleusContext (org.datanucleus.PersistenceNucleusContext)1 StoreNucleusContext (org.datanucleus.StoreNucleusContext)1 JDOPersistenceManagerFactory (org.datanucleus.api.jdo.JDOPersistenceManagerFactory)1 TransactionIsolationNotSupportedException (org.datanucleus.exceptions.TransactionIsolationNotSupportedException)1 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)1