Java Code Examples for org.hibernate.cfg.Environment

The following are top voted examples for showing how to use org.hibernate.cfg.Environment. 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: alfresco-core   File: DialectFactory.java   View source code 6 votes vote down vote up
/**
 * Determine the appropriate Dialect to use given the database product name
 * and major version.
 *
 * @param databaseName The name of the database product (obtained from metadata).
 * @param databaseMajorVersion The major version of the database product (obtained from metadata).
 *
 * @return An appropriate dialect instance.
 */
public static Dialect determineDialect(String databaseName, int databaseMajorVersion) {
    if ( databaseName == null ) {
        throw new HibernateException( "Hibernate Dialect must be explicitly set" );
    }

    DatabaseDialectMapper mapper = ( DatabaseDialectMapper ) MAPPERS.get( databaseName );
    if ( mapper == null ) {
        throw new HibernateException( "Hibernate Dialect must be explicitly set for database: " + databaseName );
    }

    String dialectName = mapper.getDialectClass( databaseMajorVersion );
    // Push the dialect onto the system properties
    System.setProperty(Environment.DIALECT, dialectName);
    return buildDialect( dialectName );
}
 
Example 2
Project: Equella   File: HibernateServiceImpl.java   View source code 6 votes vote down vote up
protected HibernateFactory getHibernateFactory(String name, boolean system)
{
	Class<?>[] clazzes = hibernateService.getDomainClasses(name);
	DataSourceHolder dataSource;
	if( system )
	{
		dataSource = datasourceService.getSystemDataSource();
	}
	else
	{
		dataSource = new DataSourceHolder(institutionAwareDataSource, datasourceService.getDialect());
	}
	HibernateFactory factory = hibernateService.createConfiguration(dataSource, clazzes);
	factory.setClassLoader(getClass().getClassLoader());
	factory.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
	factory.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	return factory;
}
 
Example 3
Project: lams   File: HibernateJpaVendorAdapter.java   View source code 6 votes vote down vote up
@Override
public Map<String, Object> getJpaPropertyMap() {
	Map<String, Object> jpaProperties = new HashMap<String, Object>();

	if (getDatabasePlatform() != null) {
		jpaProperties.put(Environment.DIALECT, getDatabasePlatform());
	}
	else if (getDatabase() != null) {
		Class<?> databaseDialectClass = determineDatabaseDialectClass(getDatabase());
		if (databaseDialectClass != null) {
			jpaProperties.put(Environment.DIALECT, databaseDialectClass.getName());
		}
	}

	if (isGenerateDdl()) {
		jpaProperties.put(Environment.HBM2DDL_AUTO, "update");
	}
	if (isShowSql()) {
		jpaProperties.put(Environment.SHOW_SQL, "true");
	}

	return jpaProperties;
}
 
Example 4
Project: lams   File: BatchBuilderInitiator.java   View source code 6 votes vote down vote up
@Override
public BatchBuilder initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object builder = configurationValues.get( BUILDER );
	if ( builder == null ) {
		return new BatchBuilderImpl(
				ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, 1 )
		);
	}

	if ( BatchBuilder.class.isInstance( builder ) ) {
		return (BatchBuilder) builder;
	}

	final String builderClassName = builder.toString();
	try {
		return (BatchBuilder) registry.getService( ClassLoaderService.class ).classForName( builderClassName ).newInstance();
	}
	catch (Exception e) {
		throw new ServiceException( "Could not build explicit BatchBuilder [" + builderClassName + "]", e );
	}
}
 
Example 5
Project: lams   File: SQLExceptionConverterFactory.java   View source code 6 votes vote down vote up
/**
 * Build a SQLExceptionConverter instance.
 * <p/>
 * First, looks for a {@link Environment#SQL_EXCEPTION_CONVERTER} property to see
 * if the configuration specified the class of a specific converter to use.  If this
 * property is set, attempt to construct an instance of that class.  If not set, or
 * if construction fails, the converter specific to the dialect will be used.
 *
 * @param dialect    The defined dialect.
 * @param properties The configuration properties.
 * @return An appropriate SQLExceptionConverter instance.
 * @throws HibernateException There was an error building the SQLExceptionConverter.
 */
public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException {
	SQLExceptionConverter converter = null;

	String converterClassName = (String) properties.get( Environment.SQL_EXCEPTION_CONVERTER );
	if ( StringHelper.isNotEmpty( converterClassName ) ) {
		converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() );
	}

	if ( converter == null ) {
		LOG.trace( "Using dialect defined converter" );
		converter = dialect.buildSQLExceptionConverter();
	}

	if ( converter instanceof Configurable ) {
		try {
			( (Configurable) converter ).configure( properties );
		}
		catch (HibernateException e) {
			LOG.unableToConfigureSqlExceptionConverter( e );
			throw e;
		}
	}

	return converter;
}
 
Example 6
Project: lams   File: ConfigHelper.java   View source code 6 votes vote down vote up
public static InputStream getResourceAsStream(String resource) {
	String stripped = resource.startsWith("/") ?
			resource.substring(1) : resource;

	InputStream stream = null;
	ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader();
	if (classLoader!=null) {
		stream = classLoader.getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		stream = Environment.class.getResourceAsStream( resource );
	}
	if ( stream == null ) {
		stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		throw new HibernateException( resource + " not found" );
	}
	return stream;
}
 
Example 7
Project: lams   File: InterbaseDialect.java   View source code 6 votes vote down vote up
/**
 * Constructs a InterbaseDialect
 */
public InterbaseDialect() {
	super();
	registerColumnType( Types.BIT, "smallint" );
	registerColumnType( Types.BIGINT, "numeric(18,0)" );
	registerColumnType( Types.SMALLINT, "smallint" );
	registerColumnType( Types.TINYINT, "smallint" );
	registerColumnType( Types.INTEGER, "integer" );
	registerColumnType( Types.CHAR, "char(1)" );
	registerColumnType( Types.VARCHAR, "varchar($l)" );
	registerColumnType( Types.FLOAT, "float" );
	registerColumnType( Types.DOUBLE, "double precision" );
	registerColumnType( Types.DATE, "date" );
	registerColumnType( Types.TIME, "time" );
	registerColumnType( Types.TIMESTAMP, "timestamp" );
	registerColumnType( Types.VARBINARY, "blob" );
	registerColumnType( Types.NUMERIC, "numeric($p,$s)" );
	registerColumnType( Types.BLOB, "blob" );
	registerColumnType( Types.CLOB, "blob sub_type 1" );
	registerColumnType( Types.BOOLEAN, "smallint" );
	
	registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","||",")" ) );
	registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) );

	getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH );
}
 
Example 8
Project: lams   File: JDataStoreDialect.java   View source code 6 votes vote down vote up
/**
 * Creates new JDataStoreDialect
 */
public JDataStoreDialect() {
	super();

	registerColumnType( Types.BIT, "tinyint" );
	registerColumnType( Types.BIGINT, "bigint" );
	registerColumnType( Types.SMALLINT, "smallint" );
	registerColumnType( Types.TINYINT, "tinyint" );
	registerColumnType( Types.INTEGER, "integer" );
	registerColumnType( Types.CHAR, "char(1)" );
	registerColumnType( Types.VARCHAR, "varchar($l)" );
	registerColumnType( Types.FLOAT, "float" );
	registerColumnType( Types.DOUBLE, "double" );
	registerColumnType( Types.DATE, "date" );
	registerColumnType( Types.TIME, "time" );
	registerColumnType( Types.TIMESTAMP, "timestamp" );
	registerColumnType( Types.VARBINARY, "varbinary($l)" );
	registerColumnType( Types.NUMERIC, "numeric($p, $s)" );

	registerColumnType( Types.BLOB, "varbinary" );
	registerColumnType( Types.CLOB, "varchar" );

	getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
}
 
Example 9
Project: lams   File: StandardServiceRegistryBuilder.java   View source code 6 votes vote down vote up
/**
 * Build the StandardServiceRegistry.
 *
 * @return The StandardServiceRegistry.
 */
@SuppressWarnings("unchecked")
public StandardServiceRegistry build() {
	final Map<?,?> settingsCopy = new HashMap();
	settingsCopy.putAll( settings );
	Environment.verifyProperties( settingsCopy );
	ConfigurationHelper.resolvePlaceHolders( settingsCopy );

	applyServiceContributingIntegrators();
	applyServiceContributors();

	return new StandardServiceRegistryImpl(
			autoCloseRegistry,
			bootstrapServiceRegistry,
			initiators,
			providedServices,
			settingsCopy
	);
}
 
Example 10
Project: lams   File: AbstractStandardBasicType.java   View source code 6 votes vote down vote up
private WrapperOptions getOptions(final SessionImplementor session) {
	return new WrapperOptions() {
		public boolean useStreamForLobBinding() {
			return Environment.useStreamsForBinary()
					|| session.getFactory().getDialect().useInputStreamToInsertBlob();
		}

		public LobCreator getLobCreator() {
			return Hibernate.getLobCreator( session );
		}

		public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
			final SqlTypeDescriptor remapped = sqlTypeDescriptor.canBeRemapped()
					? session.getFactory().getDialect().remapSqlTypeDescriptor( sqlTypeDescriptor )
					: sqlTypeDescriptor;
			return remapped == null ? sqlTypeDescriptor : remapped;
		}
	};
}
 
Example 11
Project: lams   File: CalendarDateTypeDescriptor.java   View source code 6 votes vote down vote up
public <X> Calendar wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( Calendar.class.isInstance( value ) ) {
		return (Calendar) value;
	}

	if ( ! Date.class.isInstance( value ) ) {
		throw unknownWrap( value.getClass() );
	}

	Calendar cal = new GregorianCalendar();
	if ( Environment.jvmHasTimestampBug() ) {
		final long milliseconds = ( (Date) value ).getTime();
		final long nanoseconds = java.sql.Timestamp.class.isInstance( value )
				? ( (java.sql.Timestamp) value ).getNanos()
				: 0;
		cal.setTime( new Date( milliseconds + nanoseconds / 1000000 ) );
	}
	else {
		cal.setTime( (Date) value );
	}
	return cal;
}
 
Example 12
Project: lams   File: CalendarTimeTypeDescriptor.java   View source code 6 votes vote down vote up
public <X> Calendar wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( Calendar.class.isInstance( value ) ) {
		return (Calendar) value;
	}

	if ( ! Date.class.isInstance( value ) ) {
		throw unknownWrap( value.getClass() );
	}

	Calendar cal = new GregorianCalendar();
	if ( Environment.jvmHasTimestampBug() ) {
		final long milliseconds = ( (Date) value ).getTime();
		final long nanoseconds = java.sql.Timestamp.class.isInstance( value )
				? ( (java.sql.Timestamp) value ).getNanos()
				: 0;
		cal.setTime( new Date( milliseconds + nanoseconds / 1000000 ) );
	}
	else {
		cal.setTime( (Date) value );
	}
	return cal;
}
 
Example 13
Project: lams   File: CalendarTypeDescriptor.java   View source code 6 votes vote down vote up
public <X> Calendar wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( Calendar.class.isInstance( value ) ) {
		return (Calendar) value;
	}

	if ( ! java.util.Date.class.isInstance( value ) ) {
		throw unknownWrap( value.getClass() );
	}

	Calendar cal = new GregorianCalendar();
	if ( Environment.jvmHasTimestampBug() ) {
		final long milliseconds = ( (java.util.Date) value ).getTime();
		final long nanoseconds = java.sql.Timestamp.class.isInstance( value )
				? ( (java.sql.Timestamp) value ).getNanos()
				: 0;
		cal.setTime( new Date( milliseconds + nanoseconds / 1000000 ) );
	}
	else {
		cal.setTime( (java.util.Date) value );
	}
	return cal;
}
 
Example 14
Project: cloud-s4-sdk-examples   File: HibernateConfig.java   View source code 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, MultiTenantConnectionProvider multiTenantConnectionProvider,
                                                                   CurrentTenantIdentifierResolver tenantIdentifierResolver) {
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan("com.mycompany.models");

    em.setJpaVendorAdapter(this.jpaVendorAdapter());

    final Map<String, Object> jpaProperties = new HashMap<>();
    jpaProperties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    jpaProperties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
    jpaProperties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantIdentifierResolver);
    jpaProperties.put(Environment.FORMAT_SQL, true);

    em.setJpaPropertyMap(jpaProperties);
    return em;
}
 
Example 15
Project: spring4-understanding   File: HibernateJpaVendorAdapter.java   View source code 6 votes vote down vote up
@Override
public Map<String, Object> getJpaPropertyMap() {
	Map<String, Object> jpaProperties = new HashMap<String, Object>();

	if (getDatabasePlatform() != null) {
		jpaProperties.put(Environment.DIALECT, getDatabasePlatform());
	}
	else if (getDatabase() != null) {
		Class<?> databaseDialectClass = determineDatabaseDialectClass(getDatabase());
		if (databaseDialectClass != null) {
			jpaProperties.put(Environment.DIALECT, databaseDialectClass.getName());
		}
	}

	if (isGenerateDdl()) {
		jpaProperties.put(Environment.HBM2DDL_AUTO, "update");
	}
	if (isShowSql()) {
		jpaProperties.put(Environment.SHOW_SQL, "true");
	}

	return jpaProperties;
}
 
Example 16
Project: spring4-understanding   File: LocalSessionFactoryBeanTests.java   View source code 6 votes vote down vote up
@Test
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
	final Set invocations = new HashSet();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(UserSuppliedConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals("myValue", config.getProperty("myProperty"));
			invocations.add("newSessionFactory");
			return null;
		}
	};
	Properties prop = new Properties();
	prop.setProperty(Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProvider.class.getName());
	prop.setProperty("myProperty", "myValue");
	sfb.setHibernateProperties(prop);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertTrue(invocations.contains("newSessionFactory"));
}
 
Example 17
Project: openbravo-brazil   File: SessionFactoryController.java   View source code 6 votes vote down vote up
private Properties getPostgresHbProps(Properties obProps) {
  isPostgresDatabase = true;
  final Properties props = new Properties();
  props.setProperty(Environment.DIALECT, PostgreSQLDialect.class.getName());
  if (isJNDIModeOn(obProps)) {
    setJNDI(obProps, props);
  } else {
    props.setProperty(Environment.DRIVER, "org.postgresql.Driver");
    props.setProperty(Environment.URL,
        obProps.getProperty("bbdd.url") + "/" + obProps.getProperty("bbdd.sid"));

    props.setProperty(Environment.USER, obProps.getProperty("bbdd.user"));
    props.setProperty(Environment.PASS, obProps.getProperty("bbdd.password"));
  }
  return props;
}
 
Example 18
Project: bag-database   File: JpaConfig.java   View source code 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    myLogger.info("entityManagerFactory");
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource());
    entityManagerFactoryBean.setPackagesToScan("com.github.swrirobotics");
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

    Properties jpaProperties = new Properties();
    // Disable HBM2DDL; we use Liquibase to create our database
    jpaProperties.put(Environment.HBM2DDL_AUTO, "");
    // Set a large batch size for better performance over slow network links
    jpaProperties.put(Environment.STATEMENT_BATCH_SIZE, "100");
    jpaProperties.put(Environment.ORDER_INSERTS, "true");
    jpaProperties.put(Environment.ORDER_UPDATES, "true");
    jpaProperties.put(Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
}
 
Example 19
Project: ERDesignerNG   File: HibernateTemplate.java   View source code 6 votes vote down vote up
protected Configuration createConfiguration(Class aHibernateDialectClass) {
    Configuration theConfiguration = new Configuration();
    theConfiguration.addClass(DomainEntity.class);
    theConfiguration.addClass(CustomTypeEntity.class);
    theConfiguration.addClass(TableEntity.class);
    theConfiguration.addClass(AttributeEntity.class);
    theConfiguration.addClass(IndexEntity.class);
    theConfiguration.addClass(RelationEntity.class);
    theConfiguration.addClass(CommentEntity.class);
    theConfiguration.addClass(SubjectAreaEntity.class);
    theConfiguration.addClass(RepositoryEntity.class);
    theConfiguration.addClass(ChangeEntity.class);
    theConfiguration.addClass(ViewEntity.class);
    theConfiguration.setProperty(Environment.DIALECT, aHibernateDialectClass.getName());
    theConfiguration.setProperty(Environment.HBM2DDL_AUTO, "update");
    theConfiguration.setProperty(Environment.CONNECTION_PROVIDER, ThreadbasedConnectionProvider.class.getName());
    return theConfiguration;
}
 
Example 20
Project: hazelcast-hibernate5   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
 
Example 21
Project: hazelcast-hibernate5   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedClient_noInstance() throws Exception {
    exception.expect(ServiceException.class);
    exception.expectCause(allOf(isA(CacheException.class), new BaseMatcher<CacheException>() {
        @Override
        public boolean matches(Object item) {
            return ((CacheException) item).getMessage().contains("No client with name [dev-custom] could be found.");
        }

        @Override
        public void describeTo(Description description) {
        }
    }));

    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true");
    props.setProperty(CacheEnvironment.NATIVE_CLIENT_INSTANCE_NAME, "dev-custom");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    sf.close();
}
 
Example 22
Project: spring-boot-multitenant   File: HibernateConfig.java   View source code 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
    MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
    CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl) {
  Map<String, Object> properties = new HashMap<>();
  properties.putAll(jpaProperties.getHibernateProperties(dataSource));
  properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
  properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
  properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl);

  LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  em.setDataSource(dataSource);
  em.setPackagesToScan("com.srai");
  em.setJpaVendorAdapter(jpaVendorAdapter());
  em.setJpaPropertyMap(properties);
  return em;
}
 
Example 23
Project: communote-server   File: CommunoteSessionFactoryBean.java   View source code 6 votes vote down vote up
@Override
protected void postProcessConfiguration(Configuration config) throws HibernateException {

    ConfigurationManager propsManager = CommunoteRuntime.getInstance()
            .getConfigurationManager();
    // TODO this is ugly. Actually the ConfigurationManager should take care of the
    // factory by itself but due to package structure this won't compile. We need to clean up
    // and move stuff to api package and an impl of ConfigurationManager to core.
    if (databaseConfigFactory == null) {
        propsManager
                .setDatabaseConfigurationFactory(new HibernateDatabaseConfigurationFactory());
    } else {
        propsManager.setDatabaseConfigurationFactory(databaseConfigFactory);
    }
    DatabaseConfiguration databaseConfig = propsManager.getDatabaseConfiguration();
    configConnectionProvider(config, databaseConfig);
    configFulltext(config, databaseConfig);

    String hibernateDialect = propsManager.getStartupProperties().getHibernateDialect();
    if (hibernateDialect != null) {
        // set dialect if available, if not the dialect will be provided by the driver
        config.setProperty(Environment.DIALECT, hibernateDialect);
    }

}
 
Example 24
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
 
Example 25
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedClient_noInstance() throws Exception {
    exception.expect(ServiceException.class);
    exception.expectCause(allOf(isA(CacheException.class), new BaseMatcher<CacheException>() {
        @Override
        public boolean matches(Object item) {
            return ((CacheException) item).getMessage().contains("No client with name [dev-custom] could be found.");
        }

        @Override
        public void describeTo(Description description) {
        }
    }));

    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true");
    props.setProperty(CacheEnvironment.NATIVE_CLIENT_INSTANCE_NAME, "dev-custom");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    sf.close();
}
 
Example 26
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
 
Example 27
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedInstance_noInstance() {
    exception.expect(CacheException.class);
    exception.expectMessage("No instance with name [hibernate] could be found.");

    Config config = new Config();
    config.setInstanceName("hibernate");

    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    sf.close();
}
 
Example 28
Project: hazelcast-hibernate   File: CustomPropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void testNamedClient_noInstance() throws Exception {
    exception.expect(CacheException.class);
    exception.expectMessage("No client with name [dev-custom] could be found.");

    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true");
    props.setProperty(CacheEnvironment.NATIVE_CLIENT_INSTANCE_NAME, "dev-custom");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    sf.close();
}
 
Example 29
Project: cacheonix-core   File: JTATransactionFactory.java   View source code 6 votes vote down vote up
public void configure(Properties props) throws HibernateException {
	try {
		context = NamingHelper.getInitialContext(props);
	}
	catch (NamingException ne) {
		log.error("Could not obtain initial context", ne);
		throw new HibernateException( "Could not obtain initial context", ne );
	}

	utName = props.getProperty(Environment.USER_TRANSACTION);

	if (utName==null) {
		TransactionManagerLookup lookup = TransactionManagerLookupFactory.getTransactionManagerLookup(props);
		if (lookup!=null) utName = lookup.getUserTransactionName();
	}

	if (utName==null) utName = DEFAULT_USER_TRANSACTION_NAME;
}
 
Example 30
Project: cacheonix-core   File: TransactionManagerLookupFactory.java   View source code 6 votes vote down vote up
public static final TransactionManagerLookup getTransactionManagerLookup(Properties props) throws HibernateException {

		String tmLookupClass = props.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY);
		if (tmLookupClass==null) {
			log.info("No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)");
			return null;
		}
		else {

			log.info("instantiating TransactionManagerLookup: " + tmLookupClass);

			try {
				TransactionManagerLookup lookup = (TransactionManagerLookup) ReflectHelper.classForName(tmLookupClass).newInstance();
				log.info("instantiated TransactionManagerLookup");
				return lookup;
			}
			catch (Exception e) {
				log.error("Could not instantiate TransactionManagerLookup", e);
				throw new HibernateException("Could not instantiate TransactionManagerLookup '" + tmLookupClass + "'");
			}
		}
	}
 
Example 31
Project: cacheonix-core   File: HibernateCacheonixCacheProviderTest.java   View source code 6 votes vote down vote up
/**
 * Tests {@link HibernateCacheonixCacheProvider#start(Properties)}
 *
 * @noinspection NestedTryStatement, OverlyBroadCatchBlock, InstanceMethodNamingConvention, ImplicitNumericConversion
 */
public void testStartThrowsExceptionOnMissingConfiguration() {

   try {
      final Properties properties = new Properties();
      properties.setProperty(Environment.CACHE_PROVIDER_CONFIG, NEVER_EXISTED_CACHEONIX_XML);
      final HibernateCacheonixCacheProvider anotherProvider = new HibernateCacheonixCacheProvider();
      try {
         anotherProvider.start(properties);
      } finally {
         anotherProvider.stop();
      }
      fail("Expected exception but it was not thrown");
   } catch (final Exception e) {
      assertTrue("Name of the missing Cacheonix configuration should be mentioned", StringUtils.toString(e).indexOf(NEVER_EXISTED_CACHEONIX_XML) > LONG_ZERO);
   }
}
 
Example 32
Project: cacheonix-core   File: BaseCacheProviderTestCase.java   View source code 6 votes vote down vote up
public void configure(Configuration cfg) {
	super.configure( cfg );
	cfg.setProperty( Environment.CACHE_REGION_PREFIX, "" );
	cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
	cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
	cfg.setProperty( Environment.USE_STRUCTURED_CACHE, "true" );
	cfg.setProperty( Environment.CACHE_PROVIDER, getCacheProvider().getName() );

	if ( getConfigResourceKey() != null ) {
		cfg.setProperty( getConfigResourceKey(), getConfigResourceLocation() );
	}

	if ( useTransactionManager() ) {
		cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() );
		cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() );
	}
	else {
		cfg.setProperty( Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName() );
	}
}
 
Example 33
Project: cacheonix-core   File: SQLExceptionConverterFactory.java   View source code 6 votes vote down vote up
/**
 * Build a SQLExceptionConverter instance.
 * <p/>
 * First, looks for a {@link Environment.SQL_EXCEPTION_CONVERTER} property to see
 * if the configuration specified the class of a specific converter to use.  If this
 * property is set, attempt to construct an instance of that class.  If not set, or
 * if construction fails, the converter specific to the dialect will be used.
 *
 * @param dialect    The defined dialect.
 * @param properties The configuration properties.
 * @return An appropriate SQLExceptionConverter instance.
 * @throws HibernateException There was an error building the SQLExceptionConverter.
 */
public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException {
	SQLExceptionConverter converter = null;

	String converterClassName = ( String ) properties.get( Environment.SQL_EXCEPTION_CONVERTER );
	if ( StringHelper.isNotEmpty( converterClassName ) ) {
		converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() );
	}

	if ( converter == null ) {
		log.trace( "Using dialect defined converter" );
		converter = dialect.buildSQLExceptionConverter();
	}

	if ( converter instanceof Configurable ) {
		try {
			( ( Configurable ) converter ).configure( properties );
		}
		catch ( HibernateException e ) {
			log.warn( "Unable to configure SQLExceptionConverter", e );
			throw e;
		}
	}

	return converter;
}
 
Example 34
Project: cacheonix-core   File: JDataStoreDialect.java   View source code 6 votes vote down vote up
/**
 * Creates new JDataStoreDialect
 */
public JDataStoreDialect() {
	super();

	registerColumnType( Types.BIT, "tinyint" );
	registerColumnType( Types.BIGINT, "bigint" );
	registerColumnType( Types.SMALLINT, "smallint" );
	registerColumnType( Types.TINYINT, "tinyint" );
	registerColumnType( Types.INTEGER, "integer" );
	registerColumnType( Types.CHAR, "char(1)" );
	registerColumnType( Types.VARCHAR, "varchar($l)" );
	registerColumnType( Types.FLOAT, "float" );
	registerColumnType( Types.DOUBLE, "double" );
	registerColumnType( Types.DATE, "date" );
	registerColumnType( Types.TIME, "time" );
	registerColumnType( Types.TIMESTAMP, "timestamp" );
	registerColumnType( Types.VARBINARY, "varbinary($l)" );
	registerColumnType( Types.NUMERIC, "numeric($p, $s)" );

	registerColumnType( Types.BLOB, "varbinary" );
	registerColumnType( Types.CLOB, "varchar" );

	getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
}
 
Example 35
Project: cacheonix-core   File: ConnectionProviderFactory.java   View source code 6 votes vote down vote up
/**
 * Transform JDBC connection properties.
 *
 * Passed in the form <tt>hibernate.connection.*</tt> to the
 * format accepted by <tt>DriverManager</tt> by triming the leading "<tt>hibernate.connection</tt>".
 */
public static Properties getConnectionProperties(Properties properties) {

	Iterator iter = properties.keySet().iterator();
	Properties result = new Properties();
	while ( iter.hasNext() ) {
		String prop = (String) iter.next();
		if ( prop.indexOf(Environment.CONNECTION_PREFIX) > -1 && !SPECIAL_PROPERTIES.contains(prop) ) {
			result.setProperty(
				prop.substring( Environment.CONNECTION_PREFIX.length()+1 ),
				properties.getProperty(prop)
			);
		}
	}
	String userName = properties.getProperty(Environment.USER);
	if (userName!=null) result.setProperty( "user", userName );
	return result;
}
 
Example 36
Project: cacheonix-core   File: DatasourceConnectionProvider.java   View source code 6 votes vote down vote up
public void configure(Properties props) throws HibernateException {

		String jndiName = props.getProperty(Environment.DATASOURCE);
		if (jndiName==null) {
			String msg = "datasource JNDI name was not specified by property " + Environment.DATASOURCE;
			log.fatal(msg);
			throw new HibernateException(msg);
		}

		user = props.getProperty(Environment.USER);
		pass = props.getProperty(Environment.PASS);

		try {
			ds = (DataSource) NamingHelper.getInitialContext(props).lookup(jndiName);
		}
		catch (Exception e) {
			log.fatal( "Could not find datasource: " + jndiName, e );
			throw new HibernateException( "Could not find datasource", e );
		}
		if (ds==null) {
			throw new HibernateException( "Could not find datasource: " + jndiName );
		}
		log.info( "Using datasource: " + jndiName );
	}
 
Example 37
Project: cacheonix-core   File: TreeCacheProvider.java   View source code 6 votes vote down vote up
/**
 * Prepare the underlying JBossCache TreeCache instance.
 *
 * @param properties All current config settings.
 *
 * @throws CacheException Indicates a problem preparing cache for use.
 */
public void start(Properties properties) {
	String resource = properties.getProperty( Environment.CACHE_PROVIDER_CONFIG );

	if ( resource == null ) {
		resource = properties.getProperty( CONFIG_RESOURCE );
	}
	if ( resource == null ) {
		resource = DEFAULT_CONFIG;
	}
	log.debug( "Configuring TreeCache from resource [" + resource + "]" );
	try {
		cache = new org.jboss.cache.TreeCache();
		PropertyConfigurator config = new PropertyConfigurator();
		config.configure( cache, resource );
		TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.getTransactionManagerLookup(properties);
		if (transactionManagerLookup!=null) {
			cache.setTransactionManagerLookup( new TransactionManagerLookupAdaptor(transactionManagerLookup, properties) );
			transactionManager = transactionManagerLookup.getTransactionManager(properties);
		}
		cache.start();
	}
	catch (Exception e) {
		throw new CacheException(e);
	}
}
 
Example 38
Project: cacheonix-core   File: ConfigHelper.java   View source code 6 votes vote down vote up
public static InputStream getResourceAsStream(String resource) {
	String stripped = resource.startsWith("/") ?
			resource.substring(1) : resource;

	InputStream stream = null;
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	if (classLoader!=null) {
		stream = classLoader.getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		stream = Environment.class.getResourceAsStream( resource );
	}
	if ( stream == null ) {
		stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		throw new HibernateException( resource + " not found" );
	}
	return stream;
}
 
Example 39
Project: hibernate-semantic-query   File: CalendarJavaDescriptor.java   View source code 6 votes vote down vote up
public <X> Calendar wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( Calendar.class.isInstance( value ) ) {
		return (Calendar) value;
	}

	if ( ! Date.class.isInstance( value ) ) {
		throw unknownWrap( value.getClass() );
	}

	Calendar cal = new GregorianCalendar();
	if ( Environment.jvmHasTimestampBug() ) {
		final long milliseconds = ( (Date) value ).getTime();
		final long nanoseconds = java.sql.Timestamp.class.isInstance( value )
				? ( (java.sql.Timestamp) value ).getNanos()
				: 0;
		cal.setTime( new Date( milliseconds + nanoseconds / 1000000 ) );
	}
	else {
		cal.setTime( (Date) value );
	}
	return cal;
}
 
Example 40
Project: hibernate-semantic-query   File: CalendarTimeJavaDescriptor.java   View source code 6 votes vote down vote up
public <X> Calendar wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( Calendar.class.isInstance( value ) ) {
		return (Calendar) value;
	}

	if ( ! Date.class.isInstance( value ) ) {
		throw unknownWrap( value.getClass() );
	}

	Calendar cal = new GregorianCalendar();
	if ( Environment.jvmHasTimestampBug() ) {
		final long milliseconds = ( (Date) value ).getTime();
		final long nanoseconds = java.sql.Timestamp.class.isInstance( value )
				? ( (java.sql.Timestamp) value ).getNanos()
				: 0;
		cal.setTime( new Date( milliseconds + nanoseconds / 1000000 ) );
	}
	else {
		cal.setTime( (Date) value );
	}
	return cal;
}