Example usage for org.hibernate.cfg Configuration addProperties

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

Introduction

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

Prototype

public Configuration addProperties(Properties properties) 

Source Link

Document

Add the given properties to ours.

Usage

From source file:com.vecna.maven.hibernate.HibernateSchemaMojo.java

License:Apache License

/**
 * Create mapping metadata from provided Hibernate configuration
 * @return mapping metadata//from  ww w. jav  a  2  s  . c o  m
 * @throws MojoExecutionException if a mapping class cannot be resolved or if the naming strategy cannot be instantiated
 */
protected Configuration createMappings() throws MojoExecutionException {
    Configuration configuration = new AnnotationConfiguration();

    if (configFiles != null) {
        for (String configFile : configFiles) {
            if (configFile != null && !configFile.equals("")) {
                configuration.configure(getURL(configFile));
            }
        }
    }

    if (additionalClasses != null) {
        for (String additionalClass : additionalClasses) {
            try {
                configuration.addClass(Class.forName(additionalClass));
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException("coudn't add additional classes", e);
            }
        }
    }

    if (additionalMappings != null) {
        for (String mapping : additionalMappings) {
            configuration.addURL(getURL(mapping));
        }
    }

    if (propertyFiles != null) {
        for (String propertyFile : propertyFiles) {
            URL url = getURL(propertyFile);
            Properties properties = PropertyUtils.loadProperties(url);
            configuration.addProperties(properties);
        }
    }

    if (properties != null) {
        configuration.addProperties(properties);
    }

    if (namingStrategy != null) {
        try {
            @SuppressWarnings("unchecked")
            Class nsClass = Thread.currentThread().getContextClassLoader().loadClass(namingStrategy);
            configuration.setNamingStrategy((NamingStrategy) nsClass.newInstance());
        } catch (Exception e) {
            throw new MojoExecutionException(namingStrategy + " is not a valid naming strategy", e);
        }
    }

    configuration.buildMappings();

    if (!disableEnvers) {
        if (tryEnableEnvers(configuration)) {
            getLog().info("Detected Envers");
        }
    }

    return configuration;
}

From source file:com.wavemaker.tools.data.ExportDB.java

License:Open Source License

@Override
protected void customRun() {

    init();//from   w  w  w  .  jav a2s  .  c  om

    final Configuration cfg = new Configuration();

    // cfg.addDirectory(this.hbmFilesDir);

    this.hbmFilesDir.find().files().performOperation(new ResourceOperation<com.wavemaker.tools.io.File>() {

        @Override
        public void perform(com.wavemaker.tools.io.File file) {
            if (file.getName().endsWith(".hbm.xml")) {
                cfg.addInputStream(file.getContent().asInputStream());
            }
        }
    });

    Properties connectionProperties = getHibernateConnectionProperties();

    cfg.addProperties(connectionProperties);

    SchemaExport export = null;
    SchemaUpdate update = null;
    File ddlFile = null;

    try {
        if (this.overrideTable) {
            Callable<SchemaExport> t = new Callable<SchemaExport>() {

                @Override
                public SchemaExport call() {
                    return new SchemaExport(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    export = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                export = ResourceClassLoaderUtils.runInClassLoaderContext(true, t, this.classesDir);
            }

            ddlFile = File.createTempFile("ddl", ".sql");
            ddlFile.deleteOnExit();

            export.setOutputFile(ddlFile.getAbsolutePath());
            export.setDelimiter(";");
            export.setFormat(true);

            String extraddl = prepareForExport(this.exportToDatabase);

            export.create(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(export.getExceptions());
            this.errors = filterError(this.errors, connectionProperties);

            this.ddl = IOUtils.read(ddlFile);

            if (!ObjectUtils.isNullOrEmpty(extraddl)) {
                this.ddl = extraddl + "\n" + this.ddl;
            }
        } else {
            Callable<SchemaUpdate> t = new Callable<SchemaUpdate>() {

                @Override
                public SchemaUpdate call() {
                    return new SchemaUpdate(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    update = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                update = ResourceClassLoaderUtils.runInClassLoaderContext(t, this.classesDir);
            }

            prepareForExport(this.exportToDatabase);

            Connection conn = JDBCUtils.getConnection(this.connectionUrl.toString(), this.username,
                    this.password, this.driverClassName);

            Dialect dialect = Dialect.getDialect(connectionProperties);

            DatabaseMetadata meta = new DatabaseMetadata(conn, dialect);

            String[] updateSQL = cfg.generateSchemaUpdateScript(dialect, meta);

            update.execute(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(update.getExceptions());
            StringBuilder sb = new StringBuilder();
            for (String line : updateSQL) {
                sb = sb.append(line);
                sb = sb.append("\n");
            }
            this.ddl = sb.toString();

        }
    } catch (IOException ex) {
        throw new DataServiceRuntimeException(ex);
    } catch (SQLException qex) {
        throw new DataServiceRuntimeException(qex);
    } catch (RuntimeException rex) {
        if (rex.getCause() != null && rex.getCause().getMessage().contains(NO_SUITABLE_DRIVER)
                && WMAppContext.getInstance().isCloudFoundry()) {
            String msg = rex.getMessage() + " - " + UNKNOWN_DATABASE;
            throw new DataServiceRuntimeException(msg);
        } else {
            throw new DataServiceRuntimeException(rex);
        }
    } finally {
        try {
            ddlFile.delete();
        } catch (Exception ignore) {
        }
    }
}

From source file:de.nava.informa.impl.hibernate.SessionHandler.java

License:Open Source License

/**
 * Constructor which configures hibernate, in this order:
 * <ol>/*from w  ww.j  a v a  2 s. c  o  m*/
 * <li>Reads hibernate.cfg.xml or hibernate.properties file from the
 * CLASSPATH to retrieve information about how the database can be
 * accessed (JDBC connection properties).</li>
 * <li>Then reads in the definiton files for all related informa hibernate
 * classes (*.hbm.xml)</li>
 * <li>Finally, if supplied, applies a Properties object to do a final
 * override.</li>
 * </ol>
 *
 * @throws HibernateException In case a problem occurred while configuring
 *                            hibernate or creating the session factory.
 */
private SessionHandler(Properties props) throws HibernateException {
    // reads in hibernate.properties implictly for database connection settings
    Configuration cfg = new Configuration();

    // attempt to use standard config file named hibernate.cfg.xml
    try {
        cfg.configure();
    } catch (HibernateException he) {
        logger.info("Can't find \"hibernate.cfg.xml\" in classpath.");
    }

    // add base classes
    cfg.addClass(Channel.class).addClass(Item.class).addClass(ItemGuid.class).addClass(ItemEnclosure.class)
            .addClass(ItemSource.class).addClass(Cloud.class).addClass(Category.class)
            .addClass(ChannelGroup.class).addClass(ChannelSubscription.class).addClass(Image.class)
            .addClass(ItemMetadata.class).addClass(TextInput.class);

    // If Properties were supplied then use them as the final override
    if (props != null)
        cfg.addProperties(props);

    // get session factory (expensive)
    sessFactory = cfg.buildSessionFactory();
}

From source file:de.tudarmstadt.ukp.lmf.hibernate.HibernateConnect.java

License:Apache License

/**
 * Creates Hibernate {@link Configuration} and adds all files from Hibernate mapping folder to
 * the model./*from ww  w .ja v a 2 s.  co  m*/
 *
 * @param dbConfig
 *            database configuration holder
 *
 * @return the created Hibernate Configuration
 */
public static Configuration getConfiguration(DBConfig dbConfig) {
    Configuration cfg = new Configuration();

    cfg.addProperties(getBasicProperties(dbConfig.getJdbc_url(), dbConfig.getJdbc_driver_class(),
            dbConfig.getDb_vendor(), dbConfig.getUser(), dbConfig.getPassword(), dbConfig.isShowSQL()));

    cfg.addProperties(getExtraProperties());

    // load hibernate mappings
    ClassLoader cl = HibernateConnect.class.getClassLoader();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource[] mappings = null;
    try {
        mappings = resolver.getResources("hibernatemap/access/**/*.hbm.xml");
        for (Resource mapping : mappings) {
            cfg.addURL(mapping.getURL());
        }

    } catch (IOException e) {
        logger.error("Hibernate mappings not found!");
        e.printStackTrace();
    }

    return cfg;
}

From source file:de.tudarmstadt.ukp.lmf.hibernate.HibernateConnect.java

License:Apache License

/**
 * Creates Hibernate {@link Configuration} and adds all files from Hibernate mapping folder to
 * the model./*from   w  w w.j  a v  a  2  s  .c om*/
 *
 * @param dbConfig
 *            database configuration holder
 *
 * @return the created Hibernate Configuration
 */
public static Configuration getConfiguration(DBConfig dbConfig, Properties extraProperties) {
    Configuration cfg = new Configuration();

    cfg.addProperties(getBasicProperties(dbConfig.getJdbc_url(), dbConfig.getJdbc_driver_class(),
            dbConfig.getDb_vendor(), dbConfig.getUser(), dbConfig.getPassword(), dbConfig.isShowSQL()));

    cfg.addProperties(getExtraProperties());
    cfg.addProperties(extraProperties);

    // load hibernate mappings
    ClassLoader cl = HibernateConnect.class.getClassLoader();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource[] mappings = null;
    try {
        mappings = resolver.getResources("hibernatemap/access/**/*.hbm.xml");
        for (Resource mapping : mappings) {
            cfg.addURL(mapping.getURL());
        }

    } catch (IOException e) {
        logger.error("Hibernate mappings not found!");
        e.printStackTrace();
    }

    return cfg;
}

From source file:ee.ria.xroad.common.db.HibernateUtil.java

License:Open Source License

private static Configuration getDefaultConfiguration(String name, Interceptor interceptor) throws Exception {
    String databaseProps = SystemProperties.getDatabasePropertiesFile();

    Properties extraProperties = new PrefixedProperties(name + ".");

    try (InputStream in = new FileInputStream(databaseProps)) {
        extraProperties.load(in);/*  w w  w .  j a va2  s .  c o  m*/
    }

    Configuration configuration = new Configuration();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }
    configuration.addProperties(extraProperties);
    return configuration;
}

From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java

License:Open Source License

protected SessionFactory buildSessionFactory() throws Exception {
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN");
    SessionFactory sf = null;//from  w w w  .j  a va  2s. co m

    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource currentDataSource = getCurrentDataSource();
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
            + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource);

    if (currentDataSource == null) {
        throw new IllegalStateException("Null DataSource!");
    }

    // Make given DataSource available for SessionFactory configuration.
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '"
            + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: "
            + currentDataSource);
    CONFIG_TIME_DS_HOLDER.set(currentDataSource);

    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager);
    }

    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler);
    }

    try {
        // Set connection release mode "on_close" as default.
        // This was the case for Hibernate 3.0; Hibernate 3.1 changed
        // it to "auto" (i.e. "after_statement" or "after_transaction").
        // However, for Spring's resource management (in particular for
        // HibernateTransactionManager), "on_close" is the better default.
        config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString());

        if (!isExposeTransactionAwareSessionFactory()) {
            // Not exposing a SessionFactory proxy with transaction-aware
            // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext
            // implementation instead, providing the Spring-managed Session that way.
            // Can be overridden by a custom value for corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,
                    "org.springframework.orm.hibernate3.SpringSessionContext");
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            config.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            config.setNamingStrategy(this.namingStrategy);
        }

        if (this.typeDefinitions != null) {
            // Register specified Hibernate type definitions.
            Mappings mappings = config.createMappings();
            for (int i = 0; i < this.typeDefinitions.length; i++) {
                TypeDefinitionBean typeDef = this.typeDefinitions[i];
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (int i = 0; i < this.filterDefinitions.length; i++) {
                config.addFilterDefinition(this.filterDefinitions[i]);
            }
        }

        if (this.configLocations != null) {
            for (int i = 0; i < this.configLocations.length; i++) {
                // Load Hibernate configuration from given location.
                config.configure(this.configLocations[i].getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            config.addProperties(this.hibernateProperties);
        }

        if (currentDataSource != null) {
            boolean actuallyTransactionAware = (this.useTransactionAwareDataSource
                    || currentDataSource instanceof TransactionAwareDataSourceProxy);
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER,
                    actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName()
                            : RoutingLocalDataSourceConnectionProvider.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (int i = 0; i < this.mappingLocations.length; i++) {
                config.addInputStream(this.mappingLocations[i].getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (int i = 0; i < this.cacheableMappingLocations.length; i++) {
                config.addCacheableFile(this.cacheableMappingLocations[i].getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (int i = 0; i < this.mappingJarLocations.length; i++) {
                Resource resource = this.mappingJarLocations[i];
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (int i = 0; i < this.mappingDirectoryLocations.length; i++) {
                File file = this.mappingDirectoryLocations[i].getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException("Mapping directory location ["
                            + this.mappingDirectoryLocations[i] + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements(); /* */) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements(); /* */) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<?, ?> entry : this.eventListeners.entrySet()) {
                Assert.isTrue(entry.getKey() instanceof String,
                        "Event listener key needs to be of type String");
                String listenerType = (String) entry.getKey();
                Object listenerObject = entry.getValue();

                if (listenerObject instanceof Collection) {
                    Collection<?> listeners = (Collection<?>) listenerObject;
                    EventListeners listenerRegistry = config.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    config.setListeners(listenerType, listenerArray);
                } else {
                    config.setListener(listenerType, listenerObject);
                }
            }
        }

        // Perform custom post-processing in subclasses.
        postProcessConfiguration(config);

        // Build SessionFactory instance.
        logger.debug(
                "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory.");
        this.configuration = config;

        SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy(
                repositoryManager.getDefaultRepository().getId());
        for (Repository repository : repositoryManager.getRepositories()) {
            logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
                    + repository.getId() + "' -- Building SessionFactory...");

            RepositoryManager.setCurrentRepository(repository.getId());
            sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config));
        }
        RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId());
        sf = sessionFactoryProxy;
    } finally {
        if (currentDataSource != null) {
            // Reset DataSource holder.
            CONFIG_TIME_DS_HOLDER.set(null);
        }

        if (this.jtaTransactionManager != null) {
            // Reset TransactionManager holder.
            CONFIG_TIME_TM_HOLDER.set(null);
        }

        if (this.lobHandler != null) {
            // Reset LobHandler holder.
            CONFIG_TIME_LOB_HANDLER_HOLDER.set(null);
        }
    }

    // Execute schema update if requested.
    if (this.schemaUpdate) {
        updateDatabaseSchema();
    }

    return sf;
}

From source file:net.craigstars.app.config.CSHibernateConfigurer.java

License:MIT License

public void configure(Configuration configuration) {
    try {//from   w w w. jav  a 2s .  c o  m
        // Reads an external file in the ~/bootstrap directory
        // This file contains all the hibernate credentials/driver for the current server.
        File cfgFile = new File(System.getProperty("user.home"), "bootstrap/cs.hibernate.cfg.properties");
        PropertiesConfiguration config = new PropertiesConfiguration(cfgFile.getAbsolutePath());
        Properties properties = new Properties();
        properties.put("hibernate.connection.driver_class", config.getProperty("driver"));
        properties.put("hibernate.connection.url", config.getProperty("url"));
        properties.put("hibernate.dialect", config.getProperty("dialect"));
        properties.put("hibernate.connection.username", config.getProperty("username"));
        properties.put("hibernate.connection.password", config.getProperty("password"));
        configuration.addProperties(properties);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to load hibernate properties file", ex);
    }
}

From source file:net.craigstars.app.config.CSTestHibernateConfigurer.java

License:MIT License

public void configure(Configuration configuration) {
    log.info("Using TEST Hibernate Configuration");
    try {//from  ww w.j  a v a  2  s  .com
        Properties properties = new Properties();
        properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
        properties.put("hibernate.connection.url", "jdbc:hsqldb:mem:DAOTest");
        properties.put("hibernate.dialect", HSQLDialect.class.getName());
        properties.put("hibernate.connection.username", "sa");
        properties.put("hibernate.connection.password", "");
        properties.put("hibernate.cache.use_second_level_cache", "false");
        properties.put("hibernate.cache.use_query_cache", "false");
        configuration.addProperties(properties);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to load hibernate properties file", ex);
    }
}

From source file:org.bedework.calcore.hibernate.CalintfImpl.java

License:Apache License

private SessionFactory getSessionFactory() throws CalFacadeException {
    if (sessionFactory != null) {
        return sessionFactory;
    }/*from w ww  .  j a  va2 s .c o  m*/

    synchronized (this) {
        if (sessionFactory != null) {
            return sessionFactory;
        }

        /** Get a new hibernate session factory. This is configured from an
         * application resource hibernate.cfg.xml together with some run time values
         */
        try {
            DbConfig dbConf = CoreConfigurations.getConfigs().getDbConfig();
            Configuration conf = new Configuration();

            StringBuilder sb = new StringBuilder();

            @SuppressWarnings("unchecked")
            List<String> ps = dbConf.getHibernateProperties();

            for (String p : ps) {
                sb.append(p);
                sb.append("\n");
            }

            Properties hprops = new Properties();
            hprops.load(new StringReader(sb.toString()));

            conf.addProperties(hprops).configure();

            sessionFactory = conf.buildSessionFactory();

            return sessionFactory;
        } catch (Throwable t) {
            // Always bad.
            error(t);
            throw new CalFacadeException(t);
        }
    }
}