Example usage for org.hibernate.cfg Configuration setProperties

List of usage examples for org.hibernate.cfg Configuration setProperties

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration setProperties.

Prototype

public Configuration setProperties(Properties properties) 

Source Link

Document

Specify a completely new set of properties

Usage

From source file:org.dspace.app.cris.util.UpdateSchemaTool.java

private SchemaUpdate getSchemaUpdate(Configuration cfg) throws HibernateException, IOException {
    Properties properties = new Properties();
    properties.putAll(cfg.getProperties());
    if (propertiesFile == null) {
        properties.putAll(getProject().getProperties());
    } else {/*w  w w. java 2s .co m*/
        properties.load(new FileInputStream(propertiesFile));
    }
    cfg.setProperties(properties);
    SchemaUpdate su = new SchemaUpdate(cfg);
    su.setOutputFile(outputFile.getPath());
    su.setDelimiter(delimiter);
    su.setHaltOnError(haltOnError);
    return su;
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStore.java

License:Open Source License

protected void initDataStore() {
    if (TRACER.isEnabled()) {
        TRACER.trace("Initializing Configuration"); //$NON-NLS-1$
    }//from   w ww .j  a  va  2s . com

    InputStream in = null;

    try {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(getRepository().getPackageRegistry());

        cdoDataStore = new CDODataStore();
        hibernateAuditHandler = new HibernateAuditHandler();
        hibernateAuditHandler.setCdoDataStore(cdoDataStore);
        hibernateAuditHandler.setHibernateStore(this);

        cdoDataStore.setResetConfigurationOnInitialization(false);
        cdoDataStore.setName("cdo");
        cdoDataStore.setPackageRegistry(getRepository().getPackageRegistry());
        cdoDataStore.getExtensionManager().registerExtension(EMFInterceptor.class.getName(),
                CDOInterceptor.class.getName());
        cdoDataStore.getExtensionManager().registerExtension(AuditHandler.class.getName(),
                CDOAuditHandler.class.getName());
        cdoDataStore.getExtensionManager().registerExtension(AuditProcessHandler.class.getName(),
                CDOAuditProcessHandler.class.getName());

        // don't do any persistence xml mapping in this datastore
        // make a local copy as it is adapted in the next if-statement
        // and we want to keep the original one untouched, if not
        // subsequent test runs will fail as they use the same
        // properties object
        final Properties props = new Properties();
        props.putAll(getProperties());
        props.remove(PersistenceOptions.PERSISTENCE_XML);

        if (!props.containsKey(PersistenceOptions.HANDLE_UNSET_AS_NULL)) {
            props.setProperty(PersistenceOptions.HANDLE_UNSET_AS_NULL, "true");
        }

        cdoDataStore.setDataStoreProperties(props);
        Configuration hibernateConfiguration = cdoDataStore.getConfiguration();

        if (mappingProvider != null) {
            mappingProvider.setHibernateStore(this);
            mappingXml = mappingProvider.getMapping();
            hibernateConfiguration.addXML(mappingXml);
        }

        if (TRACER.isEnabled()) {
            TRACER.trace("Adding resource.hbm.xml to configuration"); //$NON-NLS-1$
        }

        in = OM.BUNDLE.getInputStream(RESOURCE_HBM_PATH);
        hibernateConfiguration.addInputStream(in);
        // hibernateConfiguration.setInterceptor(new CDOInterceptor());

        hibernateConfiguration.setProperties(props);

        // prevent the drop on close because the sessionfactory is also closed when
        // new packages are written to the db, so only do a real drop at deactivate
        if (hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO) != null
                && hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE)) {
            doDropSchema = true;
            // note that the value create also re-creates the db and drops the old one
            hibernateConfiguration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
            cdoDataStore.getDataStoreProperties().setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
        } else {
            doDropSchema = false;
        }

        final List<EPackage> ePackages = new ArrayList<EPackage>(packageHandler.getEPackages());

        // get rid of the system packages
        for (EPackage ePackage : packageHandler.getEPackages()) {
            if (CDOModelUtil.isSystemPackage(ePackage) && ePackage != EtypesPackage.eINSTANCE) {
                ePackages.remove(ePackage);
            }
        }
        // remove the persistence xml if no epackages as this won't work without
        // epackages
        if (ePackages.size() == 0 && props.getProperty(PersistenceOptions.PERSISTENCE_XML) != null) {
            cdoDataStore.getDataStoreProperties().remove(PersistenceOptions.PERSISTENCE_XML);
        }

        if (isAuditing()) {
            auditEPackages = createAuditEPackages(cdoDataStore);
            final String auditMapping = mapAuditingEPackages(cdoDataStore, auditEPackages);
            // System.err.println(auditMapping);
            hibernateConfiguration.addXML(auditMapping);
            cdoDataStore.setAuditing(true);
        }
        cdoDataStore.setEPackages(ePackages.toArray(new EPackage[0]));
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
        IOUtil.close(in);
    }
}

From source file:org.gluewine.persistence_jpa_hibernate.impl.SessionAspectProvider.java

License:Apache License

@Override
public void codeSourceAdded(List<CodeSource> sources) {
    if (!hasEntities(sources))
        return;/*from   ww w.  j a  v  a2  s  .  c  o  m*/

    synchronized (factoryLocker) {
        try {
            Configuration config = new Configuration();
            config.setProperties(properties);
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
                    .buildServiceRegistry();

            for (CodeSource source : sources) {
                logger.debug("Processing CodesSource: " + source.getDisplayName());

                for (String entity : source.getEntities()) {
                    Class<?> clazz = source.getSourceClassLoader().loadClass(entity);
                    entities.add(clazz);
                    logger.debug("Adding Hibernate Entity: " + entity);
                }

                if (source.loadSQL() && source instanceof JarCodeSource) {
                    JarInputStream jar = null;
                    BufferedReader reader = null;
                    try {
                        jar = new JarInputStream(((JarCodeSource) source).getURLs()[0].openStream());
                        JarEntry entry = jar.getNextJarEntry();
                        while (entry != null) {
                            String name = entry.getName().toLowerCase(Locale.getDefault());
                            if (name.endsWith(".sql")) {
                                logger.debug("Checking SQL File : " + name);
                                List<String> content = new ArrayList<String>();
                                reader = new BufferedReader(new InputStreamReader(jar, "UTF-8"));
                                String line;
                                while ((line = reader.readLine()) != null)
                                    content.add(line);

                                List<SQLStatement> stmts = new ArrayList<SQLStatement>();

                                if (statements.containsKey(source)) {
                                    Map<String, List<SQLStatement>> m = statements.get(source);
                                    m.put(name, stmts);
                                } else {
                                    Map<String, List<SQLStatement>> m = new TreeMap<String, List<SQLStatement>>();
                                    statements.put(source, m);
                                    m.put(name, stmts);
                                }

                                updateSQLStatements(content, stmts);
                            }
                            entry = jar.getNextJarEntry();
                        }
                    } finally {
                        try {
                            if (jar != null)
                                jar.close();
                        } finally {
                            if (reader != null)
                                reader.close();
                        }
                    }
                }
            }

            for (Class<?> cl : entities)
                config.addAnnotatedClass(cl);

            configuration = config;
            factory = config.buildSessionFactory(serviceRegistry);
            checkStatements();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

From source file:org.gluewine.persistence_jpa_hibernate.impl.SessionAspectProvider.java

License:Apache License

@Override
public void codeSourceRemoved(List<CodeSource> sources) {
    if (!hasEntities(sources))
        return;//  ww w . ja  va2  s.  c  o  m

    synchronized (factoryLocker) {
        try {
            Configuration config = new Configuration();

            ClassLoader loader = config.getClass().getClassLoader();
            GluewineLoader gw = null;
            if (loader instanceof GluewineLoader)
                gw = (GluewineLoader) loader;

            config.setProperties(properties);
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
                    .buildServiceRegistry();

            for (CodeSource source : sources) {
                Iterator<Class<?>> iter = entities.iterator();
                while (iter.hasNext()) {
                    if (iter.next().getClassLoader() == source.getSourceClassLoader())
                        iter.remove();
                }

                if (gw != null)
                    gw.removeReference(source.getSourceClassLoader());
            }

            for (Class<?> cl : entities)
                config.addAnnotatedClass(cl);

            configuration = config;
            factory = config.buildSessionFactory(serviceRegistry);
            checkStatements();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

From source file:org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStore.java

License:Open Source License

/**
 * Initializes store./*from  w  ww .  j  ava  2  s . c  o m*/
 *
 * @throws GridException If failed to initialize.
 */
private void init() throws GridException {
    if (initGuard.compareAndSet(false, true)) {
        if (log.isDebugEnabled())
            log.debug("Initializing cache store.");

        try {
            if (sesFactory != null)
                // Session factory has been provided - nothing to do.
                return;

            if (!F.isEmpty(hibernateCfgPath)) {
                try {
                    URL url = new URL(hibernateCfgPath);

                    sesFactory = new Configuration().configure(url).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using URL: " + url);

                    // Session factory has been successfully initialized.
                    return;
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Caught malformed URL exception: " + e.getMessage());
                }

                // Provided path is not a valid URL. File?
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists()) {
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using file: " + hibernateCfgPath);

                    // Session factory has been successfully initialized.
                    return;
                }

                // Provided path is not a file. Classpath resource?
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
            } else {
                if (hibernateProps == null) {
                    U.warn(log, "No Hibernate configuration has been provided for store (will use default).");

                    hibernateProps = new Properties();

                    hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
                    hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
                    hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
                }

                Configuration cfg = new Configuration();

                cfg.setProperties(hibernateProps);

                assert resourceAvailable(MAPPING_RESOURCE) : MAPPING_RESOURCE;

                cfg.addResource(MAPPING_RESOURCE);

                sesFactory = cfg.buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using properties: " + hibernateProps);
            }
        } catch (HibernateException e) {
            throw new GridException("Failed to initialize store.", e);
        } finally {
            initLatch.countDown();
        }
    } else if (initLatch.getCount() > 0)
        U.await(initLatch);

    if (sesFactory == null)
        throw new GridException("Cache store was not properly initialized.");
}

From source file:org.ikasan.connector.basefiletransfer.DataAccessUtil.java

License:BSD License

/**
 * Creates a base <code>Configuration</code> instance incorporating any
 * properties found in the classpath resource ikasan-hibernate.properties.
 * //from w  w  w  . j  a  v a 2  s .  c  o  m
 * A <code>RuntimeException</code> will be thrown if this does not exist, or
 * does not contain a hibernate.dialect setting
 * 
 * @return base Configuration
 */
private static Configuration generateConfiguration() {
    Properties properties = new Properties();
    InputStream resourceAsStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("hibernate.properties");
    try {
        properties.load(resourceAsStream);
    } catch (IOException e) {
        throw new RuntimeException("problem loading hibernate.properties", e);
    }
    if (!properties.containsKey("hibernate.dialect")) {
        throw new RuntimeException(
                "ikasan-hibernate.properties must contain at least hibernate.dialect setting");
    }
    // properties.put("hibernate.transaction.factory_class",
    // "org.hibernate.transaction.JTATransactionFactory");

    Configuration cfg = new Configuration();
    cfg.setProperties(properties);
    return cfg;
}

From source file:org.jboss.tools.hibernate3_6.ConfigurationFactory.java

License:Open Source License

private void changeDatasourceProperties(Configuration localCfg) {
    final Properties invokeProperties = localCfg.getProperties();
    // set this property to null!
    if (invokeProperties.containsKey(Environment.DATASOURCE)) {
        invokeProperties.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, FAKE_TM_LOOKUP);
        invokeProperties.put(Environment.CONNECTION_PROVIDER, DriverManagerConnectionProvider.class.getName());
        invokeProperties.remove(Environment.DATASOURCE);
        localCfg.setProperties(invokeProperties);
    }/*from   w  ww .  j  a  v  a 2  s.  c o  m*/
}

From source file:org.jboss.tools.hibernate3_6.ConfigurationFactory.java

License:Open Source License

private Configuration configureStandardConfiguration(final boolean includeMappings, Configuration localCfg,
        Properties properties) {/*from  w w  w.  j av  a2  s .c om*/
    if (properties != null) {
        localCfg = localCfg.setProperties(properties);
    }
    EntityResolver entityResolver = XMLHelper.DEFAULT_DTD_RESOLVER;
    if (StringHelper.isNotEmpty(prefs.getEntityResolverName())) {
        try {
            entityResolver = (EntityResolver) ReflectHelper.classForName(prefs.getEntityResolverName())
                    .newInstance();
        } catch (Exception c) {
            throw new HibernateConsoleRuntimeException(
                    ConsoleMessages.ConsoleConfiguration_could_not_configure_entity_resolver
                            + prefs.getEntityResolverName(),
                    c);
        }
    }
    localCfg.setEntityResolver(entityResolver);
    if (StringHelper.isNotEmpty(prefs.getNamingStrategy())) {
        try {
            NamingStrategy ns = (NamingStrategy) ReflectHelper.classForName(prefs.getNamingStrategy())
                    .newInstance();
            localCfg.setNamingStrategy(ns);
        } catch (Exception c) {
            throw new HibernateConsoleRuntimeException(
                    ConsoleMessages.ConsoleConfiguration_could_not_configure_naming_strategy
                            + prefs.getNamingStrategy(),
                    c);
        }
    }
    localCfg = loadConfigurationXML(localCfg, includeMappings, entityResolver);
    changeDatasourceProperties(localCfg);
    localCfg = configureConnectionProfile(localCfg);
    // replace dialect if it is set in preferences
    if (StringHelper.isNotEmpty(prefs.getDialectName())) {
        localCfg.setProperty(Environment.DIALECT, prefs.getDialectName());
    }
    if (StringHelper.isEmpty(localCfg.getProperty("javax.persistence.validation.mode"))) {//$NON-NLS-1$
        localCfg.setProperty("javax.persistence.validation.mode", "none"); //$NON-NLS-1$//$NON-NLS-2$
    }
    return localCfg;
}

From source file:org.jboss.tools.hibernate4_0.ConfigurationFactory.java

License:Open Source License

private void changeDatasourceProperties(Configuration localCfg) {
    final Properties invokeProperties = localCfg.getProperties();
    // set this property to null!
    if (invokeProperties.containsKey(Environment.DATASOURCE)) {
        invokeProperties.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, FAKE_TM_LOOKUP);
        //invokeProperties.put(Environment.CONNECTION_PROVIDER, DriverManagerConnectionProvider.class.getName());
        invokeProperties.remove(Environment.DATASOURCE);
        localCfg.setProperties(invokeProperties);
    }//www.  j  a  v a2  s.  c  o m
}

From source file:org.jbpm.ant.AntHelper.java

License:Open Source License

public static Configuration getConfiguration(String hibernateCfgResource, String hibernatePropertiesResource) {
    Object key = getKey(hibernateCfgResource, hibernatePropertiesResource);
    Configuration configuration = (Configuration) configurations.get(key);
    if (configuration == null) {
        log.debug("creating hibernate configuration from cfg '" + hibernateCfgResource + "' and properties '"
                + hibernatePropertiesResource + "'");
        configuration = new Configuration();
        configuration.configure(hibernateCfgResource);
        if (hibernatePropertiesResource != null) {
            try {
                InputStream propertiesInputStream = AntHelper.class.getClassLoader()
                        .getResourceAsStream(hibernatePropertiesResource);
                log.debug("properties input stream: " + propertiesInputStream);
                Properties properties = new Properties();
                properties.load(propertiesInputStream);
                configuration.setProperties(properties);
            } catch (Exception e) {
                throw new JbpmException("couldn't set properties '" + hibernatePropertiesResource + "'", e);
            }//from www  .  j a  v a 2 s .co m
        }
        configurations.put(key, configuration);
    } else {
        log.debug("got hibernate configuration from cfg '" + hibernateCfgResource + "' and properties '"
                + hibernatePropertiesResource + "' from the cache");
    }
    return configuration;
}