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:at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider.java

License:EUPL

/**
 * Load the configuration data from XML file with the given name and build
 * the internal data structures representing the MOA ID configuration.
 * //from   www  .  j  a v a 2 s  .c  om
 * @param fileName The name of the XML file to load.
 * @throws ConfigurationException The MOA configuration could not be
 * read/built.
 */
private void load(String fileName) throws ConfigurationException {

    try {
        //Initial Hibernate Framework
        Logger.trace("Initializing Hibernate framework.");

        //Load MOAID-2.0 properties file
        File propertiesFile = new File(fileName);
        FileInputStream fis = null;
        props = new Properties();

        // determine the directory of the root config file
        rootConfigFileDir = new File(fileName).getParent();

        try {
            rootConfigFileDir = new File(rootConfigFileDir).toURL().toString();

        } catch (MalformedURLException t) {
            throw new ConfigurationException("config.03", null, t);
        }

        try {
            fis = new FileInputStream(propertiesFile);
            props.load(fis);

            // read MOAID Session Hibernate properties
            Properties moaSessionProp = new Properties();
            for (Object key : props.keySet()) {
                String propPrefix = "moasession.";
                if (key.toString().startsWith(propPrefix + "hibernate")) {
                    String propertyName = key.toString().substring(propPrefix.length());
                    moaSessionProp.put(propertyName, props.get(key.toString()));
                }
            }

            // read Config Hibernate properties
            Properties configProp = new Properties();
            for (Object key : props.keySet()) {
                String propPrefix = "configuration.";
                if (key.toString().startsWith(propPrefix + "hibernate")) {
                    String propertyName = key.toString().substring(propPrefix.length());
                    configProp.put(propertyName, props.get(key.toString()));
                }
            }

            // read advanced logging properties
            Properties statisticProps = new Properties();
            for (Object key : props.keySet()) {
                String propPrefix = "advancedlogging.";
                if (key.toString().startsWith(propPrefix + "hibernate")) {
                    String propertyName = key.toString().substring(propPrefix.length());
                    statisticProps.put(propertyName, props.get(key.toString()));
                }
            }

            // initialize hibernate
            synchronized (AuthConfigurationProvider.class) {

                //Initial config Database
                ConfigurationDBUtils.initHibernate(configProp);

                //initial MOAID Session Database
                Configuration config = new Configuration();
                config.addAnnotatedClass(AssertionStore.class);
                config.addAnnotatedClass(AuthenticatedSessionStore.class);
                config.addAnnotatedClass(OASessionStore.class);
                config.addAnnotatedClass(OldSSOSessionIDStore.class);
                config.addAnnotatedClass(ExceptionStore.class);
                config.addAnnotatedClass(InterfederationSessionStore.class);
                config.addAnnotatedClass(ProcessInstanceStore.class);
                config.addProperties(moaSessionProp);
                MOASessionDBUtils.initHibernate(config, moaSessionProp);

                //initial advanced logging
                if (isAdvancedLoggingActive()) {
                    Logger.info("Advanced statistic log is activated, starting initialization process ...");
                    Configuration statisticconfig = new Configuration();
                    statisticconfig.addAnnotatedClass(StatisticLog.class);
                    statisticconfig.addProperties(statisticProps);
                    StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps);
                    Logger.info("Advanced statistic log is initialized.");
                }

            }
            Logger.trace("Hibernate initialization finished.");

        } catch (FileNotFoundException e) {
            throw new ConfigurationException("config.03", null, e);

        } catch (IOException e) {
            throw new ConfigurationException("config.03", null, e);

        } catch (ExceptionInInitializerError e) {
            throw new ConfigurationException("config.17", null, e);

        } finally {
            if (fis != null)
                fis.close();

        }

        //Initialize OpenSAML for STORK
        Logger.info("Starting initialization of OpenSAML...");
        MOADefaultBootstrap.bootstrap();
        //DefaultBootstrap.bootstrap();
        Logger.debug("OpenSAML successfully initialized");

        String legacyconfig = props.getProperty("configuration.xml.legacy");
        String xmlconfig = props.getProperty("configuration.xml");
        //      String xmlconfigout = props.getProperty("configuration.xml.out");

        //configure eGovUtils client implementations

        //read eGovUtils client configuration
        Properties eGovUtilsConfigProp = new Properties();
        for (Object key : props.keySet()) {
            String propPrefix = "service.";
            if (key.toString().startsWith(propPrefix + "egovutil")) {
                String propertyName = key.toString().substring(propPrefix.length());
                eGovUtilsConfigProp.put(propertyName, props.get(key.toString()));
            }
        }
        if (!eGovUtilsConfigProp.isEmpty()) {
            Logger.info("Start eGovUtils client implementation configuration ...");
            eGovUtilsConfig = new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir);
        }

        //check if XML config should be used
        if (MiscUtil.isNotEmpty(legacyconfig) || MiscUtil.isNotEmpty(xmlconfig)) {
            Logger.warn(
                    "WARNING! MOA-ID 2.0 is started with XML configuration. This setup overstrike the actual configuration in the Database!");
            moaidconfig = ConfigurationDBRead.getMOAIDConfiguration();
            if (moaidconfig != null)
                ConfigurationDBUtils.delete(moaidconfig);

            List<OnlineApplication> oas = ConfigurationDBRead.getAllOnlineApplications();
            if (oas != null && oas.size() > 0) {
                for (OnlineApplication oa : oas)
                    ConfigurationDBUtils.delete(oa);
            }
        }

        //load legacy config if it is configured
        if (MiscUtil.isNotEmpty(legacyconfig)) {
            Logger.warn(
                    "WARNING! MOA-ID 2.0 is started with legacy configuration. This setup is not recommended!");

            MOAIDConfiguration moaconfig = BuildFromLegacyConfig.build(new File(legacyconfig),
                    rootConfigFileDir, null);

            List<OnlineApplication> oas = moaconfig.getOnlineApplication();
            for (OnlineApplication oa : oas)
                ConfigurationDBUtils.save(oa);

            moaconfig.setOnlineApplication(null);
            ConfigurationDBUtils.save(moaconfig);

            Logger.info("Legacy Configuration load is completed.");

        }

        //load MOA-ID 2.x config from XML
        if (MiscUtil.isNotEmpty(xmlconfig)) {
            Logger.warn("Load configuration from MOA-ID 2.x XML configuration");

            try {
                JAXBContext jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config");
                Unmarshaller m = jc.createUnmarshaller();
                File file = new File(xmlconfig);
                MOAIDConfiguration moaconfig = (MOAIDConfiguration) m.unmarshal(file);
                //ConfigurationDBUtils.save(moaconfig);

                List<OnlineApplication> importoas = moaconfig.getOnlineApplication();
                for (OnlineApplication importoa : importoas) {
                    ConfigurationDBUtils.saveOrUpdate(importoa);
                }

                moaconfig.setOnlineApplication(null);
                ConfigurationDBUtils.saveOrUpdate(moaconfig);

            } catch (Exception e) {
                Logger.warn("MOA-ID XML configuration can not be loaded from File.", e);
                throw new ConfigurationException("config.02", null);
            }
            Logger.info("XML Configuration load is completed.");
        }

        reloadDataBaseConfig();

    } catch (Throwable t) {
        throw new ConfigurationException("config.02", null, t);
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Use default configuration and add properties from Properties.
 * Build session factory from combined configuration.
 * @param config/*from ww  w . j  a v  a2  s .  com*/
 */
public void setConfiguration(Properties extraProperties) {
    try {
        Configuration config = new AnnotationConfiguration();
        config.configure(getConfigurationFileName());
        config.addProperties(extraProperties);
        sessionFactory = config.buildSessionFactory();
        configuration = config;
    } catch (Throwable ex) {
        // We have to catch Throwable, otherwise we will miss
        // NoClassDefFoundError and other subclasses of Error
        logger.log(Level.SEVERE, "Building SessionFactory failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.flipkart.flux.guice.module.HibernateModule.java

License:Apache License

private Configuration getConfiguration(YamlConfiguration yamlConfiguration, String prefix) {
    Configuration configuration = new Configuration();
    addAnnotatedClassesAndTypes(configuration);
    org.apache.commons.configuration.Configuration hibernateConfig = yamlConfiguration.subset(prefix);
    Iterator<String> propertyKeys = hibernateConfig.getKeys();
    Properties configProperties = new Properties();
    while (propertyKeys.hasNext()) {
        String propertyKey = propertyKeys.next();
        Object propertyValue = hibernateConfig.getProperty(propertyKey);
        configProperties.put(propertyKey, propertyValue);
    }//from   w ww .  j  a va  2 s  . co  m
    configuration.addProperties(configProperties);
    return configuration;
}

From source file:com.flipkart.flux.redriver.boot.RedriverModule.java

License:Apache License

/**
 * Creates hibernate configuration from the configuration yaml properties.
 * Since the yaml properties are already flattened in input param <code>yamlConfiguration</code>
 * the method loops over them to selectively pick Hibernate specific properties.
 */// w  w w .ja  v  a 2s .  c o m
@Provides
@Singleton
@Named("redriverHibernateConfiguration")
public Configuration getConfiguration(YamlConfiguration yamlConfiguration) {
    Configuration configuration = new Configuration();
    addAnnotatedClassesAndTypes(configuration);
    org.apache.commons.configuration.Configuration hibernateConfig = yamlConfiguration
            .subset(FLUX_REDRIVER_HIBERNATE_CONFIG_NAME_SPACE);
    Iterator<String> propertyKeys = hibernateConfig.getKeys();
    Properties configProperties = new Properties();
    while (propertyKeys.hasNext()) {
        String propertyKey = propertyKeys.next();
        Object propertyValue = hibernateConfig.getProperty(propertyKey);
        configProperties.put(propertyKey, propertyValue);
    }
    configuration.addProperties(configProperties);
    return configuration;
}

From source file:com.frameworkset.common.poolman.hibernate.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();

    if (dataSource != null) {
        this.configTimeDataSourceHolder.set(dataSource);
    }//from  w  ww.  ja  va2s.  com
    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    try {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(this.beanClassLoader);
        }

        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.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

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

        if (dataSource != null) {
            Class providerClass = LocalDataSourceConnectionProvider.class;

            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

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

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        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 = SimpleStringUtil
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    // method signature declares return type as Configuration on Hibernate 3.6
                    // but as void on Hibernate 3.3 and 3.5
                    Method setCacheConcurrencyStrategy = Configuration.class
                            .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class);
                    ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config,
                            new Object[] { 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 = SimpleStringUtil
                        .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<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) 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.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {

        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
        configTimeDataSourceHolder.set(null);
    }
}

From source file:com.hazelcast.hibernate.HibernateTestSupport.java

License:Open Source License

protected SessionFactory createSessionFactory(Properties props, IHazelcastInstanceLoader customInstanceLoader) {
    Configuration conf = new Configuration();
    URL xml = HibernateTestSupport.class.getClassLoader().getResource("test-hibernate.cfg.xml");
    props.put(CacheEnvironment.EXPLICIT_VERSION_CHECK, "true");
    if (customInstanceLoader != null) {
        props.put("com.hazelcast.hibernate.instance.loader", customInstanceLoader);
        customInstanceLoader.configure(props);
    } else {//from ww  w. j  a  v  a2 s.c  o  m
        props.remove("com.hazelcast.hibernate.instance.loader");
    }
    conf.configure(xml);
    conf.setCacheConcurrencyStrategy(DummyEntity.class.getName(), getCacheStrategy());
    conf.setCacheConcurrencyStrategy(DummyProperty.class.getName(), getCacheStrategy());
    conf.setCollectionCacheConcurrencyStrategy(DummyEntity.class.getName() + ".properties", getCacheStrategy());
    conf.addProperties(props);
    final SessionFactory sf = conf.buildSessionFactory();
    sf.getStatistics().setStatisticsEnabled(true);
    return sf;
}

From source file:com.impetus.client.rdbms.RDBMSPropertyReader.java

License:Apache License

/**
 * Reads property file which is given in persistence unit
 * //from  ww w .j  a  v  a  2 s. c  o m
 * @param pu
 */

public Configuration load(String pu) {
    Configuration conf = new Configuration().addProperties(puMetadata.getProperties());
    String propertyFileName = externalProperties != null
            ? (String) externalProperties.get(PersistenceProperties.KUNDERA_CLIENT_PROPERTY)
            : null;
    if (propertyFileName == null) {
        propertyFileName = puMetadata != null
                ? puMetadata.getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY)
                : null;
    }
    if (propertyFileName != null) {
        PropertyType fileType = PropertyType.value(propertyFileName);

        switch (fileType) {
        case xml:
            conf.configure(propertyFileName);
            break;

        case properties:
            Properties props = new Properties();

            InputStream ioStream = puMetadata.getClassLoader().getResourceAsStream(propertyFileName);
            if (ioStream == null) {
                propertyFileName = KunderaCoreUtils.resolvePath(propertyFileName);
                try {
                    ioStream = new FileInputStream(new File(propertyFileName));
                } catch (FileNotFoundException e) {
                    log.warn("File {} not found, Caused by ", propertyFileName);
                }
            }
            try {
                if (ioStream != null) {
                    props.load(ioStream);
                }
            } catch (IOException e) {
                log.error("Skipping as error occurred while loading property file {}, Cause by : {}.",
                        propertyFileName, e);
            }

            conf.addProperties(props);
            break;

        default:
            log.error("Unsupported type{} for file{}, skipping load of properties.", fileType,
                    propertyFileName);
            break;
        }
    }

    return conf;
}

From source file:com.redhat.rhn.common.hibernate.ConnectionManager.java

License:Open Source License

/**
 * Create a SessionFactory, loading the hbm.xml files from the specified
 * location./*from   w w  w.j  av a 2 s . c o  m*/
 * @param packageNames Package name to be searched.
 */
private void createSessionFactory() {
    if (sessionFactory != null && !sessionFactory.isClosed()) {
        return;
    }

    List<String> hbms = new LinkedList<String>();

    for (Iterator<String> iter = packageNames.iterator(); iter.hasNext();) {
        String pn = iter.next();
        hbms.addAll(FinderFactory.getFinder(pn).find("hbm.xml"));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found: " + hbms);
        }
    }

    try {
        Configuration config = new Configuration();
        /*
         * Let's ask the RHN Config for all properties that begin with
         * hibernate.*
         */
        LOG.info("Adding hibernate properties to hibernate Configuration");
        Properties hibProperties = Config.get().getNamespaceProperties("hibernate");
        hibProperties.put("hibernate.connection.username", Config.get().getString(ConfigDefaults.DB_USER));
        hibProperties.put("hibernate.connection.password", Config.get().getString(ConfigDefaults.DB_PASSWORD));

        hibProperties.put("hibernate.connection.url", ConfigDefaults.get().getJdbcConnectionString());

        config.addProperties(hibProperties);
        // Force the use of our txn factory
        if (config.getProperty(Environment.TRANSACTION_STRATEGY) != null) {
            throw new IllegalArgumentException("The property " + Environment.TRANSACTION_STRATEGY
                    + " can not be set in a configuration file;" + " it is set to a fixed value by the code");
        }

        for (Iterator<String> i = hbms.iterator(); i.hasNext();) {
            String hbmFile = i.next();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding resource " + hbmFile);
            }
            config.addResource(hbmFile);
        }
        if (configurators != null) {
            for (Iterator<Configurator> i = configurators.iterator(); i.hasNext();) {
                Configurator c = i.next();
                c.addConfig(config);
            }
        }

        // add empty varchar warning interceptor
        EmptyVarcharInterceptor interceptor = new EmptyVarcharInterceptor();
        interceptor.setAutoConvert(true);
        config.setInterceptor(interceptor);

        sessionFactory = config.buildSessionFactory();
    } catch (HibernateException e) {
        LOG.error("FATAL ERROR creating HibernateFactory", e);
    }
}

From source file:com.syncnapsis.utils.data.DataGenerator.java

License:Open Source License

private void initHibernate(Properties additionalProperties) {
    logger.info("initializing hibernate SessionFactory...");

    Configuration configuration = new Configuration().configure();

    additionalProperties.put("hibernate.current_session_context_class", "thread");

    configuration.addProperties(additionalProperties);

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();/*from w  w w  .j a va  2  s  . c om*/

    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    HibernateUtil.getInstance().setSessionFactory(sessionFactory);
}

From source file:com.terp.util.HibernateUtil.java

License:Open Source License

private static SessionFactory buildSessionFactory() {
    try {/*from w  w w .j a va  2s .c  o  m*/
        // Create the SessionFactory from hibernate.cfg.xml
        //Configuration configuration = new Configuration().configure();
        Configuration configuration = new Configuration();
        Properties props = TerpProperties.getInstance().getHibernateProps();

        configuration.addProperties(props).addPackage("com.terp.data.model").addAnnotatedClass(Company.class)
                .addAnnotatedClass(Branch.class).addAnnotatedClass(PluginSource.class)
                .addAnnotatedClass(Employee.class).addAnnotatedClass(EmployeeGroup.class)
                .addAnnotatedClass(MenuSource.class).addAnnotatedClass(MenuTranslations.class)
                .addAnnotatedClass(Item.class);

        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
                .build();

        /*
        serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .buildServiceRegistry();
        */

        return configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}