List of usage examples for org.hibernate.cfg Configuration getProperty
public String getProperty(String propertyName)
From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java
License:Open Source License
@Override public synchronized void onBootstrap(ApplicationEvent event) { if (event != null) { // Use the application context to load resources rpr = (ApplicationContext) event.getSource(); }/*from w ww .ja va 2s .c o m*/ // do everything in a transaction Session session = getSessionFactory().openSession(); Connection connection = null; try { // make sure that we AUTO-COMMIT connection = dataSource.getConnection(); connection.setAutoCommit(true); LogUtil.info(logger, MSG_DATABASE_USED, connection); Configuration cfg = localSessionFactory.getConfiguration(); // Check and dump the dialect being used checkDialect(this.dialect); // Ensure that our static connection provider is used String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER); cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName()); SchemaBootstrapConnectionProvider.setBootstrapConnection(connection); // Update the schema, if required. if (updateSchema) { // Retries are required here as the DB lock will be applied lazily upon first statement execution. // So if the schema is up to date (no statements executed) then the LockFailException cannot be // thrown. If it is thrown, the the update needs to be rerun as it will probably generate no SQL // statements the second time around. boolean updatedSchema = false; boolean createdSchema = false; for (int i = 0; i < schemaUpdateLockRetryCount; i++) { try { createdSchema = updateSchema(cfg, session, connection); updatedSchema = true; break; } catch (LockFailedException e) { try { this.wait(schemaUpdateLockRetryWaitSeconds * 1000L); } catch (InterruptedException ee) { } } } if (!updatedSchema) { // The retries were exceeded throw new AlfrescoRuntimeException(ERR_PREVIOUS_FAILED_BOOTSTRAP); } // Copy the executed statements to the output file File schemaOutputFile = null; if (schemaOuputFilename != null) { schemaOutputFile = new File(schemaOuputFilename); } else { schemaOutputFile = TempFileProvider.createTempFile( "AlfrescoSchema-" + this.dialect.getClass().getSimpleName() + "-All_Statements-", ".sql"); } StringBuilder executedStatements = executedStatementsThreadLocal.get(); if (executedStatements == null) { LogUtil.info(logger, MSG_NO_CHANGES); } else { FileContentWriter writer = new FileContentWriter(schemaOutputFile); writer.setEncoding("UTF-8"); String executedStatementsStr = executedStatements.toString(); writer.putContent(executedStatementsStr); LogUtil.info(logger, MSG_ALL_STATEMENTS, schemaOutputFile.getPath()); } if (!createdSchema) { // verify that all patches have been applied correctly checkSchemaPatchScripts(cfg, connection, preUpdateScriptPatches, false); // check scripts checkSchemaPatchScripts(cfg, connection, postUpdateScriptPatches, false); // check scripts } if (executedStatements != null) { // Remove the flag indicating a running bootstrap setBootstrapCompleted(connection); } // Report normalized dumps if (executedStatements != null) { // Validate the schema, post-upgrade validateSchema("Alfresco-{0}-Validation-Post-Upgrade-{1}-", null); // 4.0+ schema dump dumpSchema("post-upgrade"); } } else { LogUtil.info(logger, MSG_BYPASSING_SCHEMA_UPDATE); } if (stopAfterSchemaBootstrap) { // 4.0+ schema dump dumpSchema("forced-exit"); LogUtil.error(logger, ERR_FORCED_STOP); throw new BootstrapStopException(); } // Reset the configuration cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass); if (event != null) { // all done successfully ((ApplicationContext) event.getSource()).publishEvent(new SchemaAvailableEvent(this)); } } catch (BootstrapStopException e) { // We just let this out throw e; } catch (Throwable e) { LogUtil.error(logger, e, ERR_UPDATE_FAILED); if (updateSchema) { throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e); } else { throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e); } } finally { try { if (connection != null) { connection.close(); } } catch (Throwable e) { logger.warn("Error closing DB connection: " + e.getMessage()); } try { if (session != null) { session.close(); } } catch (Throwable e) { logger.warn("Error closing Hibernate session: " + e.getMessage()); } // Remove the connection reference from the threadlocal boostrap SchemaBootstrapConnectionProvider.setBootstrapConnection(null); } }
From source file:org.apache.abdera.protocol.server.adapters.hibernate.HibernateCollectionAdapter.java
License:Apache License
private void rebuildSessionFactory(Configuration cfg) { logger.debug("Rebuilding the SessionFactory from given Configuration"); if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close();//from ww w . j av a2 s . co m if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { logger.debug("Managing SessionFactory in JNDI"); cfg.buildSessionFactory(); } else { logger.debug("Holding SessionFactory in static variable"); sessionFactory = cfg.buildSessionFactory(); } hibernateConfig = cfg; }
From source file:org.apache.tapestry5.internal.hibernate.HibernateSessionSourceImplTest.java
License:Apache License
@Test public void get_configuration() { HibernateConfigurer configurer = new HibernateConfigurer() { @Override// ww w. j ava 2 s .c o m public void configure(Configuration configuration) { configuration.setProperty("foo", "bar"); configuration.configure(); } }; HibernateSessionSource source = new HibernateSessionSourceImpl(log, Arrays.asList(configurer)); Configuration config = source.getConfiguration(); Assert.assertNotNull(config); Assert.assertEquals("bar", config.getProperty("foo")); // Configuration was immutable in 5.1, but Hibernate 3.6.0.Final made that impossible }
From source file:org.apereo.portal.hibernate.DelegatingHibernateIntegrator.java
License:Apache License
@Override public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { final String persistenceUnitName = configuration.getProperty("persistenceUnitName"); if (persistenceUnitName == null) { logger.warn("Hibernate Configuration does not have '" + persistenceUnitName + "' set. It will not be considered for injecting into HibernateConfigurationAware beans: " + configuration);/*www. j a va2s . c o m*/ return; } final HibernateConfiguration hibernateConfiguration = new HibernateConfiguration(configuration, sessionFactory, serviceRegistry); synchronized (configurationAwareBeans) { hibernateInfoMap.put(persistenceUnitName, hibernateConfiguration); for (final HibernateConfigurationAwareInjector configurationAwareBean : configurationAwareBeans) { configurationAwareBean.setConfiguration(persistenceUnitName, hibernateConfiguration); } } }
From source file:org.bonitasoft.engine.persistence.AbstractHibernatePersistenceService.java
License:Open Source License
/** * @param name/*from www . ja v a2s. c o m*/ * @param hbmConfigurationProvider * @param likeEscapeCharacter * @param logger * @param sequenceManager * @param datasource * @param enableWordSearch * @param wordSearchExclusionMappings * @throws SPersistenceException * @throws ClassNotFoundException */ public AbstractHibernatePersistenceService(final String name, final HibernateConfigurationProvider hbmConfigurationProvider, final Properties extraHibernateProperties, final String likeEscapeCharacter, final TechnicalLoggerService logger, final SequenceManager sequenceManager, final DataSource datasource, final boolean enableWordSearch, final Set<String> wordSearchExclusionMappings) throws SPersistenceException, ClassNotFoundException { super(name, likeEscapeCharacter, sequenceManager, datasource, enableWordSearch, wordSearchExclusionMappings, logger); orderByCheckingMode = getOrderByCheckingMode(); Configuration configuration; try { configuration = hbmConfigurationProvider.getConfiguration(); if (extraHibernateProperties != null) { configuration.addProperties(extraHibernateProperties); } } catch (final ConfigurationException e) { throw new SPersistenceException(e); } final String dialect = configuration.getProperty("hibernate.dialect"); if (dialect != null) { if (dialect.contains("PostgreSQL")) { configuration.setInterceptor(new PostgresInterceptor()); } else if (dialect.contains("SQLServer")) { configuration.setInterceptor(new SQLServerInterceptor()); } } final String className = configuration.getProperty("hibernate.interceptor"); if (className != null && !className.isEmpty()) { try { final Interceptor interceptor = (Interceptor) Class.forName(className).newInstance(); configuration.setInterceptor(interceptor); } catch (final ClassNotFoundException cnfe) { throw new SPersistenceException(cnfe); } catch (final InstantiationException e) { throw new SPersistenceException(e); } catch (final IllegalAccessException e) { throw new SPersistenceException(e); } } sessionFactory = configuration.buildSessionFactory(); statistics = sessionFactory.getStatistics(); final Iterator<PersistentClass> classMappingsIterator = configuration.getClassMappings(); classMapping = new ArrayList<Class<? extends PersistentObject>>(); while (classMappingsIterator.hasNext()) { classMapping.add(classMappingsIterator.next().getMappedClass()); } classAliasMappings = hbmConfigurationProvider.getClassAliasMappings(); interfaceToClassMapping = hbmConfigurationProvider.getInterfaceToClassMapping(); mappingExclusions = hbmConfigurationProvider.getMappingExclusions(); cacheQueries = hbmConfigurationProvider.getCacheQueries(); }
From source file:org.compass.gps.device.hibernate.embedded.CompassEventListener.java
License:Apache License
private CompassHolder initCompassHolder(Configuration cfg) { Properties compassProperties = new Properties(); //noinspection unchecked Properties props = cfg.getProperties(); for (Map.Entry entry : props.entrySet()) { String key = (String) entry.getKey(); if (key.startsWith(COMPASS_PREFIX)) { compassProperties.put(entry.getKey(), entry.getValue()); }/*from ww w . j a v a2 s.c o m*/ if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) { compassProperties.put(entry.getKey(), entry.getValue()); } } if (compassProperties.isEmpty()) { if (log.isDebugEnabled()) { log.debug("No Compass properties defined, disabling Compass"); } return null; } if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) { if (log.isDebugEnabled()) { log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass"); } return null; } processCollections = compassProperties.getProperty(COMPASS_PROCESS_COLLECTIONS, "true") .equalsIgnoreCase("true"); CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration(); CompassSettings settings = compassConfiguration.getSettings(); settings.addSettings(compassProperties); String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION); if (configLocation != null) { compassConfiguration.configure(configLocation); } boolean atleastOneClassAdded = false; for (Iterator it = cfg.getClassMappings(); it.hasNext();) { PersistentClass clazz = (PersistentClass) it.next(); Class<?> mappedClass = clazz.getMappedClass(); for (Iterator propIt = clazz.getPropertyIterator(); propIt.hasNext();) { Property prop = (Property) propIt.next(); Value value = prop.getValue(); if (value instanceof Component) { Component component = (Component) value; try { atleastOneClassAdded |= compassConfiguration.tryAddClass( ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader())); } catch (ClassNotFoundException e) { log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e); } } } Value idValue = clazz.getIdentifierProperty().getValue(); if (idValue instanceof Component) { Component component = (Component) idValue; try { atleastOneClassAdded |= compassConfiguration.tryAddClass( ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader())); } catch (ClassNotFoundException e) { log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e); } } atleastOneClassAdded |= compassConfiguration.tryAddClass(mappedClass); } if (!atleastOneClassAdded) { if (log.isDebugEnabled()) { log.debug("No searchable class mappings found in Hibernate class mappings, disabling Compass"); } return null; } CompassHolder compassHolder = new CompassHolder(); compassHolder.compassProperties = compassProperties; compassHolder.commitBeforeCompletion = settings .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false); String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY); if (transactionFactory == null) { String hibernateTransactionStrategy = cfg.getProperty(Environment.TRANSACTION_STRATEGY); if (CMTTransactionFactory.class.getName().equals(hibernateTransactionStrategy) || JTATransactionFactory.class.getName().equals(hibernateTransactionStrategy)) { // hibernate is configured with JTA, automatically configure Compass to use its JTASync (by default) compassHolder.hibernateControlledTransaction = false; compassConfiguration.setSetting(CompassEnvironment.Transaction.FACTORY, JTASyncTransactionFactory.class.getName()); } else { // Hibernate JDBC transaction manager, let Compass use the local transaction manager compassHolder.hibernateControlledTransaction = true; // if the settings is configured to use local transaciton, disable thread bound setting since // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals if (settings .getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) { settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true); } } } else if (LocalTransactionFactory.class.getName().equals(transactionFactory)) { compassHolder.hibernateControlledTransaction = true; // if the settings is configured to use local transaciton, disable thread bound setting since // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) { settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true); } } else { // Hibernate is not controlling the transaction (using JTA Sync or XA), don't commit/rollback // with Hibernate transaction listeners compassHolder.hibernateControlledTransaction = false; } compassHolder.indexSettings = new Properties(); for (Map.Entry entry : compassProperties.entrySet()) { String key = (String) entry.getKey(); if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) { compassHolder.indexSettings.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue()); } } String mirrorFilterClass = compassHolder.compassProperties.getProperty(COMPASS_MIRROR_FILTER); if (mirrorFilterClass != null) { try { compassHolder.mirrorFilter = (HibernateMirrorFilter) ClassUtils .forName(mirrorFilterClass, compassConfiguration.getSettings().getClassLoader()) .newInstance(); } catch (Exception e) { throw new CompassException("Failed to create mirror filter [" + mirrorFilterClass + "]", e); } } compassHolder.compass = compassConfiguration.buildCompass(); return compassHolder; }
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$ }/*w w w . j a v a2 s. c om*/ 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.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java
License:Apache License
protected void configureGrailsJdbcTransactionFactory(Configuration config) { String configuredStrategy = config.getProperty(Environment.TRANSACTION_STRATEGY); if (configuredStrategy == null || "jdbc".equals(configuredStrategy)) { config.setProperty(Environment.TRANSACTION_STRATEGY, GrailsJdbcTransactionFactory.class.getName()); }//from w w w. j a v a 2 s.co m }
From source file:org.grouter.common.hibernate.HibernateUtilContextAware.java
License:Apache License
/** * Create session factories and configurations and store in hibernateConfigMap. On * completion we enter INITIALISED state. *//*from ww w. j ava 2s . c o m*/ private static void createSessionFactoriesFromConfigMap() { // read in all config and create session factories Iterator iter = hibernateConfigMap.keySet().iterator(); while (iter.hasNext()) { SessionFactory sessionFactory; String key = (String) iter.next(); HibernateConfigItem hibernateConfigItem = hibernateConfigMap.get(key); String file = hibernateConfigItem.getConfigFile(); Configuration configuration; if (file == null) { log.info("Loading properties config and not from file "); configuration = hibernateConfigItem.getConfiguration(); } else { log.info("Loading properties from : " + file); configuration = new Configuration(); configuration = configuration.configure(file); } try { String sessionFactoryName = configuration.getProperty(Environment.SESSION_FACTORY_NAME); if (sessionFactoryName != null) { log.debug("Looking up SessionFactory in JNDI with name : " + sessionFactoryName); try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, configuration.getProperty(Environment.JNDI_CLASS)); env.put(Context.URL_PKG_PREFIXES, configuration.getProperty(Environment.JNDI_PREFIX)); env.put(Context.PROVIDER_URL, configuration.getProperty(Environment.JNDI_URL)); Context context = new InitialContext(env); JNDIUtils.printJNDI(context, log); sessionFactory = (SessionFactory) context.lookup(sessionFactoryName); if (sessionFactory == null) { throw new IllegalStateException( "SessionFactory from JNDI lookup returned a null implemenation using file : " + file); } } catch (NamingException ex) { log.error("Failed looking up sessinfactory : " + sessionFactoryName, ex); throw new RuntimeException(ex); } } else { sessionFactory = configuration.buildSessionFactory(); if (sessionFactory == null) { throw new IllegalStateException( "SessionFactory could not be createed from the configuration using file : " + file); } } hibernateConfigItem.setConfiguration(configuration); hibernateConfigItem.setSessionFactory(sessionFactory); // We need to have a default sessionfactory / configuration if (hibernateConfigItem.isDeafult()) { hibernateConfigItemDefault = hibernateConfigItem; } // setInterceptor(configuration, null); // hibernateConfigMap.put(key) } catch (Throwable ex) { log.error("Failed initializing from configuration.", ex); throw new ExceptionInInitializerError(ex); } } currentState = STATE.INITIALISED; log.info("Entered state : " + currentState); }
From source file:org.inheritsource.taskform.engine.persistence.HibernateUtil.java
License:Open Source License
/** * Override properties in a Hibernate configuration if an environment * variable is set. No exceptions are propagated, this step is just omitted * in such case. SIDE EFFECT: Properties are set in the configuration, * possibly overriding those already set. *//*from www .j a va 2 s . c o m*/ public static void overrideProperties(Configuration cfg) { try { Properties props = ConfigUtil.getConfigProperties(); Properties hibernateProps = new Properties(); for (Object key : props.keySet()) { if (key instanceof String && ((String) key).startsWith("dataSource.")) { Object val = props.get(key); String hibernateKey = "hibernate.connection." + ((String) key).substring(11); hibernateProps.put(hibernateKey, val); } } cfg.addProperties(hibernateProps); } catch (Exception exc) { // Warn and ignore log.warn("Db default connect params (got " + exc.getClass().getName() + ")"); } String url = cfg.getProperty("hibernate.connection.url"); log.info("Db connect url: " + ((url != null) ? url : "*NO URL*")); }