Java Code Examples for org.hibernate.cfg.AvailableSettings

The following are top voted examples for showing how to use org.hibernate.cfg.AvailableSettings. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: testee.fi   File: PropertyContributor.java   View source code 6 votes vote down vote up
@Override
public void contribute(final Properties properties, final String provider) {
    if (!provider.equals(HIBERNATE_PROVIDER)) {
        return;
    }
    properties.put(
            AvailableSettings.SCANNER_ARCHIVE_INTERPRETER,
            new TestEEfiArchiveDescriptorFactory()
    );
    // TODO find out why eclipselink allows TX access by default while Hibernate doesn't
    properties.put(
            AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS,
            true
    );
    properties.put(
            AvailableSettings.JTA_PLATFORM,
            new TestEEfiJtaPlatform(transactionManager(), transactionServices)
    );
}
 
Example 2
Project: endpoint-health   File: EndPointHealthServletContextListener.java   View source code 6 votes vote down vote up
@Override
protected Injector getInjector() {
    final Properties persistenceUnitProperties = new Properties();

    persistenceUnitProperties.put(AvailableSettings.JPA_JDBC_URL,
        Utils.getDatabaseUrl(endPointHealthConfiguration.databaseFile()));

    persistenceUnitProperties.put(AvailableSettings.JPA_JDBC_USER,
        endPointHealthConfiguration.databaseUser());

    persistenceUnitProperties.put(AvailableSettings.JPA_JDBC_PASSWORD,
        endPointHealthConfiguration.databasePassword());

    return Guice.createInjector(
        new JpaPersistModule(PERSISTENCE_UNIT).properties(persistenceUnitProperties),
        new EndPointHealthServletModule());
}
 
Example 3
Project: lams   File: LocalSessionFactoryBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the {@code SessionFactory}.
 */
@Override
@SuppressWarnings("deprecation")
public SessionFactory buildSessionFactory() throws HibernateException {
	ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader =
			(appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(appClassLoader);
	}
	try {
		return super.buildSessionFactory();
	}
	finally {
		if (overrideClassLoader) {
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
Example 4
Project: lams   File: SchemaExport.java   View source code 6 votes vote down vote up
public SchemaExport(ServiceRegistry serviceRegistry, Configuration configuration) {
	this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
			serviceRegistry.getService( ConnectionProvider.class )
	);
	this.sqlStatementLogger = serviceRegistry.getService( JdbcServices.class ).getSqlStatementLogger();
	this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
	this.sqlExceptionHelper = serviceRegistry.getService( JdbcServices.class ).getSqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			configuration.getProperties(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect();
	this.dropSQL = configuration.generateDropSchemaScript( dialect );
	this.createSQL = configuration.generateSchemaCreationScript( dialect );
}
 
Example 5
Project: lams   File: SchemaExport.java   View source code 6 votes vote down vote up
public SchemaExport(MetadataImplementor metadata) {
	ServiceRegistry serviceRegistry = metadata.getServiceRegistry();
	this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
			serviceRegistry.getService( ConnectionProvider.class )
	);
       JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
	this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
	this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
	this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			serviceRegistry.getService( ConfigurationService.class ).getSettings(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = jdbcServices.getDialect();
	this.dropSQL = metadata.getDatabase().generateDropSchemaScript( dialect );
	this.createSQL = metadata.getDatabase().generateSchemaCreationScript( dialect );
}
 
Example 6
Project: lams   File: SchemaExport.java   View source code 6 votes vote down vote up
/**
 * Create a schema exporter for the given Configuration, with the given
 * database connection properties.
 *
 * @param configuration The configuration from which to build a schema export.
 * @param properties The properties from which to configure connectivity etc.
 * @throws HibernateException Indicates problem preparing for schema export.
 *
 * @deprecated properties may be specified via the Configuration object
 */
@Deprecated
   public SchemaExport(Configuration configuration, Properties properties) throws HibernateException {
	final Dialect dialect = Dialect.getDialect( properties );

	Properties props = new Properties();
	props.putAll( dialect.getDefaultProperties() );
	props.putAll( properties );
	this.connectionHelper = new ManagedProviderConnectionHelper( props );

	this.sqlStatementLogger = new SqlStatementLogger( false, true );
	this.formatter = FormatStyle.DDL.getFormatter();
	this.sqlExceptionHelper = new SqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			properties,
			DEFAULT_IMPORT_FILE
	);

	this.dropSQL = configuration.generateDropSchemaScript( dialect );
	this.createSQL = configuration.generateSchemaCreationScript( dialect );
}
 
Example 7
Project: lams   File: SchemaExport.java   View source code 6 votes vote down vote up
/**
 * Create a schema exporter for the given Configuration, using the supplied connection for connectivity.
 *
 * @param configuration The configuration to use.
 * @param connection The JDBC connection to use.
 * @throws HibernateException Indicates problem preparing for schema export.
 */
public SchemaExport(Configuration configuration, Connection connection) throws HibernateException {
	this.connectionHelper = new SuppliedConnectionHelper( connection );

	this.sqlStatementLogger = new SqlStatementLogger( false, true );
	this.formatter = FormatStyle.DDL.getFormatter();
	this.sqlExceptionHelper = new SqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			configuration.getProperties(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = Dialect.getDialect( configuration.getProperties() );
	this.dropSQL = configuration.generateDropSchemaScript( dialect );
	this.createSQL = configuration.generateSchemaCreationScript( dialect );
}
 
Example 8
Project: lams   File: JmxServiceImpl.java   View source code 6 votes vote down vote up
@Override
public void registerService(Manageable service, Class<? extends Service> serviceRole) {
	final String domain = service.getManagementDomain() == null
			? AvailableSettings.JMX_DEFAULT_OBJ_NAME_DOMAIN
			: service.getManagementDomain();
	final String serviceType = service.getManagementServiceType() == null
			? service.getClass().getName()
			: service.getManagementServiceType();
	try {
		final ObjectName objectName = new ObjectName(
				String.format(
						OBJ_NAME_TEMPLATE,
						domain,
						sessionFactoryName,
						serviceRole.getName(),
						serviceType
				)
		);
		registerMBean( objectName, service.getManagementBean() );
	}
	catch ( MalformedObjectNameException e ) {
		throw new HibernateException( "Unable to generate service IbjectName", e );
	}
}
 
Example 9
Project: rjb-blog-multitenancy   File: HibernateConfig.java   View source code 6 votes vote down vote up
protected LocalSessionFactoryBean createSessionFactoryBean() {

		LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
		factoryBean.setDataSource(this.dataSourceConfig.dataSource());

		if (StringUtil.isEmpty(this.propertiesConfig.hibernateDialect())) {
			throw new IllegalStateException("hibernateDialect is required");
		}

		factoryBean.getHibernateProperties().setProperty(AvailableSettings.DIALECT,
				this.propertiesConfig.hibernateDialect());

		if (!ArrayUtil.isEmpty(this.propertiesConfig.hibernateMappingLocations())) {
			factoryBean
					.setMappingLocations(this.propertiesConfig.hibernateMappingLocations());
		}

		return factoryBean;

	}
 
Example 10
Project: spring4-understanding   File: LocalSessionFactoryBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the {@code SessionFactory}.
 */
@Override
@SuppressWarnings("deprecation")
public SessionFactory buildSessionFactory() throws HibernateException {
	ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader =
			(appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(appClassLoader);
	}
	try {
		return super.buildSessionFactory();
	}
	finally {
		if (overrideClassLoader) {
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
Example 11
Project: spring4-understanding   File: HibernateTransactionManagerTests.java   View source code 6 votes vote down vote up
@Test
public void testSetJtaTransactionManager() throws Exception {
	DataSource ds = mock(DataSource.class);
	TransactionManager tm = mock(TransactionManager.class);
	UserTransaction ut = mock(UserTransaction.class);
	TransactionSynchronizationRegistry tsr = mock(TransactionSynchronizationRegistry.class);
	JtaTransactionManager jtm = new JtaTransactionManager();
	jtm.setTransactionManager(tm);
	jtm.setUserTransaction(ut);
	jtm.setTransactionSynchronizationRegistry(tsr);
	LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(ds);
	lsfb.setJtaTransactionManager(jtm);
	Object jtaPlatform = lsfb.getProperties().get(AvailableSettings.JTA_PLATFORM);
	assertNotNull(jtaPlatform);
	assertSame(tm, jtaPlatform.getClass().getMethod("retrieveTransactionManager").invoke(jtaPlatform));
	assertSame(ut, jtaPlatform.getClass().getMethod("retrieveUserTransaction").invoke(jtaPlatform));
	assertTrue(lsfb.getProperties().get(AvailableSettings.TRANSACTION_STRATEGY) instanceof CMTTransactionFactory);
}
 
Example 12
Project: HikariCP   File: HikariConfigurationUtil.java   View source code 6 votes vote down vote up
/**
 * Create/load a HikariConfig from Hibernate properties.
 *
 * @param props a map of Hibernate properties
 * @return a HikariConfig
 */
@SuppressWarnings("rawtypes")
public static HikariConfig loadConfiguration(Map props)
{
   Properties hikariProps = new Properties();
   copyProperty(AvailableSettings.ISOLATION, props, "transactionIsolation", hikariProps);
   copyProperty(AvailableSettings.AUTOCOMMIT, props, "autoCommit", hikariProps);
   copyProperty(AvailableSettings.DRIVER, props, "driverClassName", hikariProps);
   copyProperty(AvailableSettings.URL, props, "jdbcUrl", hikariProps);
   copyProperty(AvailableSettings.USER, props, "username", hikariProps);
   copyProperty(AvailableSettings.PASS, props, "password", hikariProps);

   for (Object keyo : props.keySet()) {
      String key = (String) keyo;
      if (key.startsWith(CONFIG_PREFIX)) {
         hikariProps.setProperty(key.substring(CONFIG_PREFIX.length()), (String) props.get(key));
      }
   }

   return new HikariConfig(hikariProps);
}
 
Example 13
Project: appengine-hibernate   File: Hibernate.java   View source code 6 votes vote down vote up
private static EntityManagerFactory newFactory(Map<String, String> extraProperties) {
    
    LOGGER.info("Creating EntityManagerFactory...");
    
    try {

        Map<String, String> properties = new HashMap<>();
        properties.putAll(extraProperties);


        if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
            properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.GoogleDriver");
            properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.url"));
        } else {
            properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
            properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.url.dev"));
        }

        properties.put(org.hibernate.ejb.AvailableSettings.INTERCEPTOR, TimingInterceptor.class.getName());

        return Persistence.createEntityManagerFactory("Demo", properties);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failed to create EntityManagerFactory", e);
        throw e;
    }
}
 
Example 14
Project: cosmo   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <STAMP_TYPE extends Stamp> STAMP_TYPE findStampByInternalItemUid(String internalItemUid,
        Class<STAMP_TYPE> clazz) {
    try (StatelessSession session = this.openStatelessSession()){

        List<Stamp> stamps = (List<Stamp>) session.createNamedQuery("item.stamps.by.uid")
                .setParameter("uid", internalItemUid)
                .setHint(AvailableSettings.JPA_SHARED_CACHE_STORE_MODE, null)
                .setHint(AvailableSettings.JPA_SHARED_CACHE_RETRIEVE_MODE, null)
                .getResultList();
        for (Stamp stamp : stamps) {
            if (clazz.isInstance(stamp)) {
                return clazz.cast(stamp);
            }
        }
    } catch (HibernateException e) {
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
    return null;
}
 
Example 15
Project: hibernate-hdb-demo   File: TestEmployee.java   View source code 6 votes vote down vote up
/**
 */
@Before
public void setUp() {
    final DataSource ds = new DriverManagerDataSource(System.getProperty("jdbc.url", "jdbc:sap://localhost:30115"),
            System.getProperty("jdbc.user", "hibernate"), System.getProperty("jdbc.password", "hibernate"));

    final LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(ds);
    builder.setProperty(AvailableSettings.DIALECT,
            System.getProperty("hibernate.dialect", HANAColumnStoreDialect.class.getName()));
    builder.setProperty(AvailableSettings.HBM2DDL_AUTO, "create-drop");
    builder.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");

    builder.addAnnotatedClass(Employee.class);

    this.sessionFactory = builder.buildSessionFactory();

    final HibernateTemplate ht = new HibernateTemplate();
    ht.setSessionFactory(this.sessionFactory);

    ht.afterPropertiesSet();

    this.template = ht;

    final HibernateTransactionManager txnMgr = new HibernateTransactionManager();
    txnMgr.setDataSource(ds);
    txnMgr.setSessionFactory(this.sessionFactory);
    txnMgr.afterPropertiesSet();

    this.transactionTemplate = new TransactionTemplate(txnMgr);
}
 
Example 16
Project: class-guard   File: LocalSessionFactoryBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the {@code SessionFactory}.
 */
@Override
@SuppressWarnings("deprecation")
public SessionFactory buildSessionFactory() throws HibernateException {
	ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader =
			(appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(appClassLoader);
	}
	try {
		return super.buildSessionFactory();
	}
	finally {
		if (overrideClassLoader) {
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
Example 17
Project: org.fastnate   File: HibernateProvider.java   View source code 6 votes vote down vote up
private static Class<? extends GeneratorDialect> getGeneratorDialectFromConnectionDriver(
		final Properties settings) {
	final String connectionDriver = settings.getProperty(AvailableSettings.DRIVER);
	if (connectionDriver != null) {
		if (connectionDriver.contains("postgresql")) {
			return PostgresDialect.class;
		}
		if (connectionDriver.contains("mysql")) {
			return MySqlDialect.class;
		}
		if (connectionDriver.contains("sqlserver")) {
			return MsSqlDialect.class;
		}
		if (connectionDriver.contains(".h2.")) {
			return H2Dialect.class;
		}
		if (connectionDriver.contains("oracle")) {
			return OracleDialect.class;
		}
	}
	return null;
}
 
Example 18
Project: org.fastnate   File: HibernateProvider.java   View source code 6 votes vote down vote up
private static Class<? extends GeneratorDialect> getGeneratorDialectFromConnectionUrl(final Properties settings) {
	final String connectionUrl = settings.getProperty(AvailableSettings.URL);
	if (connectionUrl != null) {
		if (connectionUrl.contains(":oracle:")) {
			return OracleDialect.class;
		}
		if (connectionUrl.contains(":postgresql:")) {
			return PostgresDialect.class;
		}
		if (connectionUrl.contains(":mysql:")) {
			return MySqlDialect.class;
		}
		if (connectionUrl.contains(":sqlserver:")) {
			return MsSqlDialect.class;
		}
		if (connectionUrl.contains(":h2:")) {
			return H2Dialect.class;
		}
	}
	return null;
}
 
Example 19
Project: org.fastnate   File: HibernateProvider.java   View source code 6 votes vote down vote up
private static Class<? extends GeneratorDialect> getGeneratorDialectFromHibernateDialect(
		final Properties settings) {
	final String hibernateDialect = settings.getProperty(AvailableSettings.DIALECT);
	if (hibernateDialect != null) {
		if (hibernateDialect.contains("Oracle")) {
			return OracleDialect.class;
		}
		if (hibernateDialect.contains("PostgreSQL")) {
			return PostgresDialect.class;
		}
		if (hibernateDialect.contains("MySQL")) {
			return MySqlDialect.class;
		}
		if (hibernateDialect.contains("SQLServer")) {
			return MsSqlDialect.class;
		}
		if (hibernateDialect.contains("H2Dialect")) {
			return H2Dialect.class;
		}
	}
	return null;
}
 
Example 20
Project: hibernate4-memcached   File: EntityTestUtils.java   View source code 6 votes vote down vote up
public static void init() {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(AvailableSettings.USE_SECOND_LEVEL_CACHE, true);
    props.put(AvailableSettings.USE_QUERY_CACHE, true);
    props.put(AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, CacheConcurrencyStrategy.NONSTRICT_READ_WRITE);
    props.put(AvailableSettings.CACHE_REGION_FACTORY, Hibernate4MemcachedRegionFactory.class.getName());
    props.put(AvailableSettings.CACHE_REGION_PREFIX, "cachetest");
    props.put(AvailableSettings.CACHE_PROVIDER_CONFIG, "META-INF/h4m-properties.xml");
    props.put(AvailableSettings.HBM2DDL_AUTO, "create");
    props.put(AvailableSettings.USE_STRUCTURED_CACHE, "false");
    props.put(Hibernate4MemcachedRegionFactory.MEMCACHED_ADAPTER_CLASS_PROPERTY_KEY,
            SpyMemcachedAdapter.class.getName());
    props.put(SpyMemcachedAdapter.HOST_PROPERTY_KEY, "localhost:11211");
    props.put(SpyMemcachedAdapter.HASH_ALGORITHM_PROPERTY_KEY, DefaultHashAlgorithm.KETAMA_HASH.name());
    props.put(SpyMemcachedAdapter.OPERATION_TIMEOUT_MILLIS_PROPERTY_KEY, "5000");
    props.put(SpyMemcachedAdapter.TRANSCODER_PROPERTY_KEY, KryoTranscoder.class.getName());
    props.put(SpyMemcachedAdapter.CACHE_KEY_PREFIX_PROPERTY_KEY, "h4m");
    props.put(KryoTranscoder.COMPRESSION_THREASHOLD_PROPERTY_KEY, "20000");

    emf = Persistence.createEntityManagerFactory("cachetest", props);
}
 
Example 21
Project: osgi-hibernate   File: HibernatePersistenceProvider.java   View source code 6 votes vote down vote up
protected Map<?, ?> generateExtendedSettings(final Map<?, ?> map) {
    Map<Object, Object> result = null;
    if (map == null) {
        result = new ConcurrentHashMap<Object, Object>();
    } else {
        result = new ConcurrentHashMap<Object, Object>(map);
    }
    result.put("javax.persistence.validation.factory", getValidatorFactory());
    result.put(AvailableSettings.JTA_CACHE_TM, false);
    result.put(AvailableSettings.JTA_CACHE_UT, false);

    OsgiJtaPlatform osgiJtaPlatform = new OsgiJtaPlatform(transactionManagerTracker, userTransactionTracker);
    osgiJtaPlatform.configure(result);
    result.put(AvailableSettings.JTA_PLATFORM, osgiJtaPlatform);
    return result;
}
 
Example 22
Project: dropwizard-routing   File: RoutingSessionFactoryFactory.java   View source code 6 votes vote down vote up
/**
 * Builds a {@link SessionFactory}
 * @param bundle
 *            the bundle
 * @param dbConfig
 *            the dbconfig
 * @param connectionProvider
 *            the connection provider
 * @param properties
 *            the hibernate properties
 * @param entities
 *            the persistent entities
 * @return {@link SessionFactory}
 */
private SessionFactory buildSessionFactory(RoutingHibernateBundle<?> bundle, DataSourceFactory dbConfig,
        ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) {
    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
    configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS,
            Boolean.toString(dbConfig.isAutoCommentsEnabled()));
    configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true");
    configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
    configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true");
    configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true");
    configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true");
    configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
    for (Map.Entry<String, String> property : properties.entrySet()) {
        configuration.setProperty(property.getKey(), property.getValue());
    }

    addAnnotatedClasses(configuration, entities);
    bundle.configure(configuration);

    final ServiceRegistry registry = new StandardServiceRegistryBuilder()
            .addService(ConnectionProvider.class, connectionProvider).applySettings(properties).build();

    return configuration.buildSessionFactory(registry);
}
 
Example 23
Project: jipijapa   File: InfinispanRegionFactory.java   View source code 6 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
    // Find a suitable service name to represent this session factory instance
    String name = properties.getProperty(AvailableSettings.SESSION_FACTORY_NAME);
    String container = properties.getProperty(CACHE_CONTAINER, DEFAULT_CACHE_CONTAINER);
    HibernateSecondLevelCache.addSecondLevelCacheDependencies(properties, null);

    Properties cacheSettings = new Properties();
    cacheSettings.put(HibernateSecondLevelCache.CACHE_TYPE,CACHE_PRIVATE);
    cacheSettings.put(HibernateSecondLevelCache.CONTAINER, container);
    if (name != null) {
        cacheSettings.put(HibernateSecondLevelCache.NAME, name);
    }

    try {
        // start a private cache for non-JPA use and return the started cache.
        wrapper = Notification.startCache(Classification.INFINISPAN, cacheSettings);
        return (EmbeddedCacheManager)wrapper.getValue();
    } catch (Exception e) {
        throw new CacheException(e);
    }
}
 
Example 24
Project: jipijapa   File: InfinispanRegionFactory.java   View source code 6 votes vote down vote up
@Override
protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
    // Find a suitable service name to represent this session factory instance
    String name = properties.getProperty(AvailableSettings.SESSION_FACTORY_NAME);
    String container = properties.getProperty(CACHE_CONTAINER, DEFAULT_CACHE_CONTAINER);
    HibernateSecondLevelCache.addSecondLevelCacheDependencies(properties, null);

    Properties cacheSettings = new Properties();
    cacheSettings.put(HibernateSecondLevelCache.CACHE_TYPE,CACHE_PRIVATE);
    cacheSettings.put(HibernateSecondLevelCache.CONTAINER, container);
    if (name != null) {
        cacheSettings.put(HibernateSecondLevelCache.NAME, name);
    }


    try {
        // start a private cache for non-JPA use and return the started cache.
        wrapper = Notification.startCache(Classification.INFINISPAN, cacheSettings);
        return (EmbeddedCacheManager)wrapper.getValue();
    } catch (Exception e) {
        throw new CacheException(e);
    }
}
 
Example 25
Project: ToDoApp-Spring   File: HibernateConfig.java   View source code 5 votes vote down vote up
Properties getHibernateProperties() {
    return new Properties() {
        {
            setProperty(AvailableSettings.DIALECT, env.getRequiredProperty("hibernate.dialect"));
            setProperty(AvailableSettings.SHOW_SQL, env.getRequiredProperty("hibernate.show_sql"));
            setProperty(AvailableSettings.HBM2DDL_AUTO, env.getRequiredProperty("hibernate.hbm2ddl.auto"));
            setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, env.getRequiredProperty("hibernate.batch.size"));
            setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, env.getRequiredProperty("hibernate.current.session.context.class"));
        }
    };
}
 
Example 26
Project: lams   File: LocalSessionFactoryBuilder.java   View source code 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 */
@SuppressWarnings("deprecation")  // to be able to build against Hibernate 4.3
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
	getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(Environment.DATASOURCE, dataSource);
	}
	// APP_CLASSLOADER is deprecated as of Hibernate 4.3 but we need to remain compatible with 4.0+
	getProperties().put(AvailableSettings.APP_CLASSLOADER, resourceLoader.getClassLoader());
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example 27
Project: lams   File: LocalSessionFactoryBuilder.java   View source code 5 votes vote down vote up
/**
 * Set the Spring {@link JtaTransactionManager} or the JTA {@link TransactionManager}
 * to be used with Hibernate, if any. Allows for using a Spring-managed transaction
 * manager for Hibernate 4's session and cache synchronization, with the
 * "hibernate.transaction.jta.platform" automatically set to it. Also sets
 * "hibernate.transaction.factory_class" to {@link CMTTransactionFactory},
 * instructing Hibernate to interact with externally managed transactions.
 * <p>A passed-in Spring {@link JtaTransactionManager} needs to contain a JTA
 * {@link TransactionManager} reference to be usable here, except for the WebSphere
 * case where we'll automatically set {@code WebSphereExtendedJtaPlatform} accordingly.
 * <p>Note: If this is set, the Hibernate settings should not contain a JTA platform
 * setting to avoid meaningless double configuration.
 */
public LocalSessionFactoryBuilder setJtaTransactionManager(Object jtaTransactionManager) {
	Assert.notNull(jtaTransactionManager, "Transaction manager reference must not be null");
	if (jtaTransactionManager instanceof JtaTransactionManager) {
		boolean webspherePresent = ClassUtils.isPresent("com.ibm.wsspi.uow.UOWManager", getClass().getClassLoader());
		if (webspherePresent) {
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					ConfigurableJtaPlatform.getJtaPlatformBasePackage() + "internal.WebSphereExtendedJtaPlatform");
		}
		else {
			JtaTransactionManager jtaTm = (JtaTransactionManager) jtaTransactionManager;
			if (jtaTm.getTransactionManager() == null) {
				throw new IllegalArgumentException(
						"Can only apply JtaTransactionManager which has a TransactionManager reference set");
			}
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					new ConfigurableJtaPlatform(jtaTm.getTransactionManager(), jtaTm.getUserTransaction(),
							jtaTm.getTransactionSynchronizationRegistry()).getJtaPlatformProxy());
		}
	}
	else if (jtaTransactionManager instanceof TransactionManager) {
		getProperties().put(AvailableSettings.JTA_PLATFORM,
				new ConfigurableJtaPlatform((TransactionManager) jtaTransactionManager, null, null).getJtaPlatformProxy());
	}
	else {
		throw new IllegalArgumentException(
				"Unknown transaction manager type: " + jtaTransactionManager.getClass().getName());
	}
	getProperties().put(AvailableSettings.TRANSACTION_STRATEGY, new CMTTransactionFactory());
	return this;
}
 
Example 28
Project: lams   File: IdentifierGeneratorResolver.java   View source code 5 votes vote down vote up
@SuppressWarnings( {"unchecked"} )
void resolve() {
	for ( EntityBinding entityBinding : metadata.getEntityBindings() ) {
		if ( entityBinding.isRoot() ) {
			Properties properties = new Properties( );
			properties.putAll(
					metadata.getServiceRegistry()
							.getService( ConfigurationService.class )
							.getSettings()
			);
			//TODO: where should these be added???
			if ( ! properties.contains( AvailableSettings.PREFER_POOLED_VALUES_LO ) ) {
				properties.put( AvailableSettings.PREFER_POOLED_VALUES_LO, "false" );
			}
			if ( ! properties.contains( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER ) ) {
				properties.put(
						PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
						new ObjectNameNormalizerImpl( metadata )
				);
			}
			entityBinding.getHierarchyDetails().getEntityIdentifier().createIdentifierGenerator(
					metadata.getIdentifierGeneratorFactory(),
					properties
			);
		}
	}
}
 
Example 29
Project: lams   File: DatabaseMetadata.java   View source code 5 votes vote down vote up
public DatabaseMetadata(Connection connection, Dialect dialect, Configuration config, boolean extras)
		throws SQLException {
	sqlExceptionConverter = dialect.buildSQLExceptionConverter();
	meta = connection.getMetaData();
	this.extras = extras;
	initSequences( connection, dialect );
	if ( config != null
			&& ConfigurationHelper.getBoolean( AvailableSettings.ENABLE_SYNONYMS, config.getProperties(), false ) ) {
		types = new String[] { "TABLE", "VIEW", "SYNONYM" };
	}
	else {
		types = new String[] { "TABLE", "VIEW" };
	}
}
 
Example 30
Project: lams   File: JmxServiceImpl.java   View source code 5 votes vote down vote up
public JmxServiceImpl(Map configValues) {
	usePlatformServer = ConfigurationHelper.getBoolean( AvailableSettings.JMX_PLATFORM_SERVER, configValues );
	agentId = (String) configValues.get( AvailableSettings.JMX_AGENT_ID );
	defaultDomain = (String) configValues.get( AvailableSettings.JMX_DOMAIN_NAME );
	sessionFactoryName = ConfigurationHelper.getString(
			AvailableSettings.JMX_SF_NAME,
			configValues,
			ConfigurationHelper.getString( Environment.SESSION_FACTORY_NAME, configValues )
	);
}
 
Example 31
Project: lams   File: JtaPlatformResolverInitiator.java   View source code 5 votes vote down vote up
@Override
public JtaPlatformResolver initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object setting = configurationValues.get( AvailableSettings.JTA_PLATFORM_RESOLVER );
	final JtaPlatformResolver resolver = registry.getService( StrategySelector.class )
			.resolveStrategy( JtaPlatformResolver.class, setting );
	if ( resolver == null ) {
		log.debugf( "No JtaPlatformResolver was specified, using default [%s]", StandardJtaPlatformResolver.class.getName() );
		return StandardJtaPlatformResolver.INSTANCE;
	}
	return resolver;
}
 
Example 32
Project: lams   File: JtaPlatformInitiator.java   View source code 5 votes vote down vote up
@Override
@SuppressWarnings( {"unchecked"})
public JtaPlatform initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object setting = configurationValues.get( AvailableSettings.JTA_PLATFORM );
	final JtaPlatform platform = registry.getService( StrategySelector.class ).resolveStrategy( JtaPlatform.class, setting );
	if ( platform == null ) {
		LOG.debugf( "No JtaPlatform was specified, checking resolver" );
		return registry.getService( JtaPlatformResolver.class ).resolveJtaPlatform( configurationValues, registry );
	}
	return platform;
}
 
Example 33
Project: lams   File: AbstractJtaPlatform.java   View source code 5 votes vote down vote up
public void configure(Map configValues) {
	cacheTransactionManager = ConfigurationHelper.getBoolean(
			AvailableSettings.JTA_CACHE_TM,
			configValues,
			canCacheTransactionManagerByDefault()
	);
	cacheUserTransaction = ConfigurationHelper.getBoolean(
			AvailableSettings.JTA_CACHE_UT,
			configValues,
			canCacheUserTransactionByDefault()
	);
}
 
Example 34
Project: lams   File: TransactionFactoryInitiator.java   View source code 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public TransactionFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object strategy = configurationValues.get( AvailableSettings.TRANSACTION_STRATEGY );

	if ( strategy == null ) {
		LOG.usingDefaultTransactionStrategy();
		return new JdbcTransactionFactory();
	}

	return registry.getService( StrategySelector.class ).resolveStrategy( TransactionFactory.class, strategy );
}
 
Example 35
Project: lams   File: DriverManagerConnectionProviderImpl.java   View source code 5 votes vote down vote up
private ConnectionCreator buildCreator(Map configurationValues) {
	final ConnectionCreatorBuilder connectionCreatorBuilder = new ConnectionCreatorBuilder( serviceRegistry );

	final String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER );
	connectionCreatorBuilder.setDriver( loadDriverIfPossible( driverClassName ) );

	final String url = (String) configurationValues.get( AvailableSettings.URL );
	if ( url == null ) {
		final String msg = log.jdbcUrlNotSpecified( AvailableSettings.URL );
		log.error( msg );
		throw new HibernateException( msg );
	}
	connectionCreatorBuilder.setUrl( url );

	log.usingDriver( driverClassName, url );

	final Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( configurationValues );

	// if debug level is enabled, then log the password, otherwise mask it
	if ( log.isDebugEnabled() ) {
		log.connectionProperties( connectionProps );
	}
	else {
		log.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) );
	}
	connectionCreatorBuilder.setConnectionProps( connectionProps );

	final boolean autoCommit = ConfigurationHelper.getBoolean( AvailableSettings.AUTOCOMMIT, configurationValues, false );
	log.autoCommitMode( autoCommit );
	connectionCreatorBuilder.setAutoCommit( autoCommit );

	final Integer isolation = ConfigurationHelper.getInteger( AvailableSettings.ISOLATION, configurationValues );
	if ( isolation != null ) {
		log.jdbcIsolationLevel( Environment.isolationLevelToString( isolation ) );
	}
	connectionCreatorBuilder.setIsolation( isolation );

	return connectionCreatorBuilder.build();
}
 
Example 36
Project: lams   File: ConnectionProviderInitiator.java   View source code 5 votes vote down vote up
private static boolean c3p0ConfigDefined(Map configValues) {
	for ( Object key : configValues.keySet() ) {
		if ( String.class.isInstance( key )
				&& ( (String) key ).startsWith( AvailableSettings.C3P0_CONFIG_PREFIX ) ) {
			return true;
		}
	}
	return false;
}
 
Example 37
Project: lams   File: ConnectionProviderInitiator.java   View source code 5 votes vote down vote up
private static boolean proxoolConfigDefined(Map configValues) {
	for ( Object key : configValues.keySet() ) {
		if ( String.class.isInstance( key )
				&& ( (String) key ).startsWith( AvailableSettings.PROXOOL_CONFIG_PREFIX ) ) {
			return true;
		}
	}
	return false;
}
 
Example 38
Project: lams   File: DialectFactoryImpl.java   View source code 5 votes vote down vote up
@Override
public Dialect buildDialect(Map configValues, DialectResolutionInfoSource resolutionInfoSource) throws HibernateException {
	final String dialectName = (String) configValues.get( AvailableSettings.DIALECT );
	if ( !StringHelper.isEmpty( dialectName ) ) {
		return constructDialect( dialectName );
	}
	else {
		return determineDialect( resolutionInfoSource );
	}
}
 
Example 39
Project: lams   File: SessionFactoryImpl.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
private CurrentTenantIdentifierResolver determineCurrentTenantIdentifierResolver(
		CurrentTenantIdentifierResolver explicitResolver) {
	if ( explicitResolver != null ) {
		return explicitResolver;
	}
	return serviceRegistry.getService( ConfigurationService.class )
			.getSetting(
					AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER,
					CurrentTenantIdentifierResolver.class,
					null
			);

}
 
Example 40
Project: lams   File: JaccIntegrator.java   View source code 5 votes vote down vote up
private void doIntegration(
		Map properties,
		JaccPermissionDeclarations permissionDeclarations,
		SessionFactoryServiceRegistry serviceRegistry) {
	boolean isSecurityEnabled = properties.containsKey( AvailableSettings.JACC_ENABLED );
	if ( ! isSecurityEnabled ) {
		log.debug( "Skipping JACC integration as it was not enabled" );
		return;
	}

	final String contextId = (String) properties.get( AvailableSettings.JACC_CONTEXT_ID );
	if ( contextId == null ) {
		throw new IntegrationException( "JACC context id must be specified" );
	}

	final JaccService jaccService = serviceRegistry.getService( JaccService.class );
	if ( jaccService == null ) {
		throw new IntegrationException( "JaccService was not set up" );
	}

	if ( permissionDeclarations != null ) {
		for ( GrantedPermission declaration : permissionDeclarations.getPermissionDeclarations() ) {
			jaccService.addPermission( declaration );
		}
	}

	final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
	eventListenerRegistry.addDuplicationStrategy( DUPLICATION_STRATEGY );

	eventListenerRegistry.prependListeners( EventType.PRE_DELETE, new JaccPreDeleteEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_INSERT, new JaccPreInsertEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_UPDATE, new JaccPreUpdateEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_LOAD, new JaccPreLoadEventListener() );
}