org.hibernate.cfg.AvailableSettings Java Examples

The following examples show how to use org.hibernate.cfg.AvailableSettings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JtaPlatformInitiator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings( {"unchecked"})
public JtaPlatform initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object setting = configurationValues.get( AvailableSettings.JTA_PLATFORM );
	JtaPlatform platform = registry.getService( StrategySelector.class ).resolveStrategy( JtaPlatform.class, setting );

	if ( platform == null ) {
		LOG.debugf( "No JtaPlatform was specified, checking resolver" );
		platform = registry.getService( JtaPlatformResolver.class ).resolveJtaPlatform( configurationValues, registry );
	}

	if ( platform == null ) {
		LOG.debugf( "No JtaPlatform was specified, checking resolver" );
		platform = getFallbackProvider( configurationValues, registry );
	}

	return platform;
}
 
Example #2
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
    Map configuration = properties();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
    }
    Integrator integrator = integrator();
    if (integrator != null) {
        configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
    }

    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
    );
    return entityManagerFactoryBuilder.build();
}
 
Example #3
Source File: NamedProcedureCallDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static ParameterDefinition from(
		ParameterStrategy parameterStrategy,
		StoredProcedureParameter parameterAnnotation,
		int adjustedPosition,
		Map<String, Object> queryHintMap) {
	// see if there was an explicit hint for this parameter in regards to NULL passing
	final Object explicitNullPassingHint;
	if ( parameterStrategy == ParameterStrategy.NAMED ) {
		explicitNullPassingHint = queryHintMap.get( AvailableSettings.PROCEDURE_NULL_PARAM_PASSING + '.' + parameterAnnotation.name() );
	}
	else {
		explicitNullPassingHint = queryHintMap.get( AvailableSettings.PROCEDURE_NULL_PARAM_PASSING + '.' + adjustedPosition );
	}

	return new ParameterDefinition(
			adjustedPosition,
			parameterAnnotation,
			interpretBoolean( explicitNullPassingHint )
	);
}
 
Example #4
Source File: ItemDaoImpl.java    From cosmo with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <STAMP_TYPE extends Stamp> STAMP_TYPE findStampByInternalItemUid(String internalItemUid,
        Class<STAMP_TYPE> clazz) {

    List<Stamp> stamps = (List<Stamp>) em.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);
        }
    }

    return null;
}
 
Example #5
Source File: ResourceLocalReleaseAfterStatementConfiguration.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
protected Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", hibernateDialect);
    properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    properties.put(
        "hibernate.integrator_provider",
            (IntegratorProvider) () -> Collections.singletonList(
                new ClassImportIntegrator(Arrays.asList(PostDTO.class))
            )
    );
    properties.put(
        AvailableSettings.CONNECTION_HANDLING,
        //PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT
        PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION
    );
    return properties;
}
 
Example #6
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 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 #7
Source File: FastBootHibernateReactivePersistenceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void registerVertxPool(String persistenceUnitName,
        RuntimeSettings runtimeSettings,
        PreconfiguredReactiveServiceRegistryBuilder serviceRegistry) {
    if (runtimeSettings.isConfigured(AvailableSettings.URL)) {
        // the pool has been defined in the persistence unit, we can bail out
        return;
    }

    // for now we only support one pool but this will change
    InstanceHandle<Pool> poolHandle = Arc.container().instance(Pool.class);
    if (!poolHandle.isAvailable()) {
        throw new IllegalStateException("No pool has been defined for persistence unit " + persistenceUnitName);
    }

    serviceRegistry.addInitiator(new QuarkusReactiveConnectionPoolInitiator(poolHandle.get()));
}
 
Example #8
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void registerIdentifierGenerators(StandardServiceRegistry ssr) {
    final StrategySelector strategySelector = ssr.getService(StrategySelector.class);

    // apply id generators
    final Object idGeneratorStrategyProviderSetting = buildTimeSettings
            .get(AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER);
    if (idGeneratorStrategyProviderSetting != null) {
        final IdentifierGeneratorStrategyProvider idGeneratorStrategyProvider = strategySelector
                .resolveStrategy(IdentifierGeneratorStrategyProvider.class, idGeneratorStrategyProviderSetting);
        final MutableIdentifierGeneratorFactory identifierGeneratorFactory = ssr
                .getService(MutableIdentifierGeneratorFactory.class);
        if (identifierGeneratorFactory == null) {
            throw persistenceException("Application requested custom identifier generator strategies, "
                    + "but the MutableIdentifierGeneratorFactory could not be found");
        }
        for (Map.Entry<String, Class<?>> entry : idGeneratorStrategyProvider.getStrategies().entrySet()) {
            identifierGeneratorFactory.register(entry.getKey(), entry.getValue());
        }
    }
}
 
Example #9
Source File: TransactionCoordinatorBuilderInitiator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static Object determineStrategySelection(Map configurationValues) {
	final Object coordinatorStrategy = configurationValues.get( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY );
	if ( coordinatorStrategy != null ) {
		return coordinatorStrategy;
	}

	final Object legacySetting = configurationValues.get( LEGACY_SETTING_NAME );
	if ( legacySetting != null ) {
		DeprecationLogger.DEPRECATION_LOGGER.logDeprecatedTransactionFactorySetting(
				LEGACY_SETTING_NAME,
				AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY
		);
		return legacySetting;
	}

	// triggers the default
	return null;
}
 
Example #10
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 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 #11
Source File: HibernateUtil.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static SessionFactory createSessionFactory() {
    try {
        Configuration configuration = configuration();
        configuration.setProperty(AvailableSettings.DIALECT, MySQLDialect.class.getName());
        configuration.setProperty(AvailableSettings.USE_QUERY_CACHE, "false");
        configuration.setProperty(AvailableSettings.SHOW_SQL, "false");
        configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
        configuration.setProperty("hibernate.hikari.maximumPoolSize", String.valueOf(Runtime.getRuntime().availableProcessors() * 2));
        configuration.addAnnotatedClass(World.class);
        configuration.addAnnotatedClass(Fortune.class);
        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        return configuration.buildSessionFactory(serviceRegistryBuilder.build());
    } catch (RuntimeException ex) {
        LOGGER.error("Failed to create session factory");
        throw ex;
    }
}
 
Example #12
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public boolean equals(Configuration configuration) {

			Properties prop = configuration.getProperties();

			if (!driverClass.equals(prop.getProperty(AvailableSettings.DRIVER))) {
				return false;
			}
			if (!dialect.equals(prop.getProperty(AvailableSettings.DIALECT))) {
				return false;
			}
			if (!preferredTestQuery.equals(prop.getProperty(PREFFERED_TEST_QUERY))) {
				return false;
			}
			if (!userName.equals(prop.getProperty(AvailableSettings.USER))) {
				return false;
			}
			if (!password.equals(prop.getProperty(AvailableSettings.PASS))) {
				return false;
			}
			if (!createProtocolUrl(this).equals(prop.getProperty(AvailableSettings.URL))) {
				return false;
			}

			return true;
		}
 
Example #13
Source File: DriverManagerConnectionProviderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private PooledConnections buildPool(Map configurationValues) {
	final boolean autoCommit = ConfigurationHelper.getBoolean(
			AvailableSettings.AUTOCOMMIT,
			configurationValues,
			false
	);
	final int minSize = ConfigurationHelper.getInt( MIN_SIZE, configurationValues, 1 );
	final int maxSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 );
	final int initialSize = ConfigurationHelper.getInt( INITIAL_SIZE, configurationValues, minSize );

	ConnectionCreator connectionCreator = buildCreator( configurationValues );
	PooledConnections.Builder pooledConnectionBuilder = new PooledConnections.Builder(
			connectionCreator,
			autoCommit
	);
	pooledConnectionBuilder.initialSize( initialSize );
	pooledConnectionBuilder.minSize( minSize );
	pooledConnectionBuilder.maxSize( maxSize );

	return pooledConnectionBuilder.build();
}
 
Example #14
Source File: OptimizerFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the optimizer to use when there was not one explicitly specified.
 */
public static String determineImplicitOptimizerName(int incrementSize, Properties configSettings) {
	if ( incrementSize <= 1 ) {
		return StandardOptimizerDescriptor.NONE.getExternalName();
	}

	// see if the user defined a preferred pooled optimizer...
	final String preferredPooledOptimizerStrategy = configSettings.getProperty( AvailableSettings.PREFERRED_POOLED_OPTIMIZER );
	if ( StringHelper.isNotEmpty( preferredPooledOptimizerStrategy ) ) {
		return preferredPooledOptimizerStrategy;
	}

	// otherwise fallback to the fallback strategy (considering the deprecated PREFER_POOLED_VALUES_LO setting)
	return ConfigurationHelper.getBoolean( AvailableSettings.PREFER_POOLED_VALUES_LO, configSettings, false )
			? StandardOptimizerDescriptor.POOLED_LO.getExternalName()
			: StandardOptimizerDescriptor.POOLED.getExternalName();
}
 
Example #15
Source File: LockModePessimisticReadWriteIntegrationTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testPessimisticNoWait() {
    LOGGER.info("Test PESSIMISTIC_READ blocks PESSIMISTIC_WRITE, NO WAIT fails fast");

    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L,
            LockModeType.PESSIMISTIC_WRITE
        );

        executeSync(() -> doInJPA(_entityManager -> {
            try {
                Post _post = _entityManager.find(Post.class, 1L,
                    LockModeType.PESSIMISTIC_WRITE,
                    Collections.singletonMap(
                        AvailableSettings.JPA_LOCK_TIMEOUT, LockOptions.NO_WAIT
                    )
                );
                fail("Should throw PessimisticEntityLockException");
            } catch (LockTimeoutException expected) {
                //This is expected since the first transaction already acquired this lock
            }
        }));
    });
}
 
Example #16
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenWrongDialectSpecified_thenCommandAcceptanceException() {
    thrown.expect(SchemaManagementException.class);
    thrown.expectCause(isA(CommandAcceptanceException.class));
    thrown.expectMessage("Halting on error : Error executing DDL");

    Configuration cfg = getConfiguration();
    cfg.setProperty(AvailableSettings.DIALECT,
        "org.hibernate.dialect.MySQLDialect");
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");

    // This does not work due to hibernate bug
    // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true");
    cfg.getProperties()
        .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true);

    cfg.addAnnotatedClass(Product.class);
    cfg.buildSessionFactory();
}
 
Example #17
Source File: IdGeneratorInterpreterImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void interpretSequenceGenerator(
		SequenceGenerator sequenceGeneratorAnnotation,
		IdentifierGeneratorDefinition.Builder definitionBuilder) {
	definitionBuilder.setName( sequenceGeneratorAnnotation.name() );

	definitionBuilder.setStrategy( "seqhilo" );

	if ( !BinderHelper.isEmptyAnnotationValue( sequenceGeneratorAnnotation.sequenceName() ) ) {
		definitionBuilder.addParam( org.hibernate.id.SequenceGenerator.SEQUENCE, sequenceGeneratorAnnotation.sequenceName() );
	}
	//FIXME: work on initialValue() through SequenceGenerator.PARAMETERS
	//		steve : or just use o.h.id.enhanced.SequenceStyleGenerator
	if ( sequenceGeneratorAnnotation.initialValue() != 1 ) {
		log.unsupportedInitialValue( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS );
	}
	definitionBuilder.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( sequenceGeneratorAnnotation.allocationSize() - 1 ) );
}
 
Example #18
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 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 #19
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() {
    thrown.expect(SchemaManagementException.class);
    thrown.expectMessage("Schema-validation: missing table");

    Configuration cfg = getConfiguration();
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");
    cfg.addAnnotatedClass(Product.class);
    cfg.buildSessionFactory();
}
 
Example #20
Source File: Hibernate4MemcachedRegionFactoryTest.java    From hibernate4-memcached with Apache License 2.0 5 votes vote down vote up
@Test
public void populateCacheProviderConfigProperties_normal_properties() throws Exception {
    Properties sessionFactoryProperties = new Properties();
    sessionFactoryProperties.setProperty(AvailableSettings.CACHE_PROVIDER_CONFIG,
            "kr/pe/kwonnam/hibernate4memcached/util/normal.properties");

    Properties properties = regionFactory.populateCacheProviderConfigProperties(sessionFactoryProperties);
    assertThat(properties).hasSize(1);
}
 
Example #21
Source File: HibernateMappingContextConfiguration.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Set the target SQL {@link DataSource}
 *
 * @param connectionSource The data source to use
 */
public void setDataSourceConnectionSource(ConnectionSource<DataSource, DataSourceSettings> connectionSource) {
    this.dataSourceName = connectionSource.getName();
    DataSource source = connectionSource.getSource();
    getProperties().put(Environment.DATASOURCE, source);
    getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, GrailsSessionContext.class.getName());
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    if (contextClassLoader != null && contextClassLoader.getClass().getSimpleName().equalsIgnoreCase("RestartClassLoader")) {
        getProperties().put(AvailableSettings.CLASSLOADERS, contextClassLoader);
    } else {
        getProperties().put(AvailableSettings.CLASSLOADERS, connectionSource.getClass().getClassLoader());
    }
}
 
Example #22
Source File: SchemaBuilderUtility.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public void generateVBLSchema(ApplicationContext context, MetadataFactory source, MetadataFactory target,
        Dialect dialect, MetadataSources metadataSources) {
    generateVBLSchema(source, target);
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) metadataSources.getServiceRegistry())
            .applySetting(AvailableSettings.DIALECT, dialect).build();
    ArtifactCollector files = generateHibernateModel(source, serviceRegistry);
    for (File f : files.getFiles("hbm.xml")) {
        metadataSources.addFile(f);
    }
}
 
Example #23
Source File: Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void resolveLegacyLimitHandlerBehavior(ServiceRegistry serviceRegistry) {
	// HHH-11194
	// Temporary solution to set whether legacy limit handler behavior should be used.
	final ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
	legacyLimitHandlerBehavior = configurationService.getSetting(
			AvailableSettings.USE_LEGACY_LIMIT_HANDLERS,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #24
Source File: BootstrapContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public BootstrapContextImpl(
		StandardServiceRegistry serviceRegistry,
		MetadataBuildingOptions metadataBuildingOptions) {
	this.serviceRegistry = serviceRegistry;
	this.classmateContext = new ClassmateContext();
	this.metadataBuildingOptions = metadataBuildingOptions;

	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
	this.classLoaderAccess = new ClassLoaderAccessImpl( classLoaderService );
	this.hcannReflectionManager = generateHcannReflectionManager();

	final StrategySelector strategySelector = serviceRegistry.getService( StrategySelector.class );
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	this.jpaCompliance = new MutableJpaComplianceImpl( configService.getSettings(), false );
	this.scanOptions = new StandardScanOptions(
			(String) configService.getSettings().get( AvailableSettings.SCANNER_DISCOVERY ),
			false
	);

	// ScanEnvironment must be set explicitly
	this.scannerSetting = configService.getSettings().get( AvailableSettings.SCANNER );
	if ( this.scannerSetting == null ) {
		this.scannerSetting = configService.getSettings().get( AvailableSettings.SCANNER_DEPRECATED );
		if ( this.scannerSetting != null ) {
			DEPRECATION_LOGGER.logDeprecatedScannerSetting();
		}
	}
	this.archiveDescriptorFactory = strategySelector.resolveStrategy(
			ArchiveDescriptorFactory.class,
			configService.getSettings().get( AvailableSettings.SCANNER_ARCHIVE_INTERPRETER )
	);
	this.typeConfiguration = new TypeConfiguration();
}
 
Example #25
Source File: UnlimitedMessageColumnsMigration.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public UnlimitedMessageColumnsMigration(Session session, Configuration configuration) throws URISyntaxException {
    this.session = session;
    String dialect = configuration.getProperty(AvailableSettings.DIALECT);
    this.nativeDbQueries = NativeDbQueries.fromDialect(dialect);
    String url = configuration.getProperty(AvailableSettings.URL);
    URI full = new URI(url);
    URI uri = new URI(full.getSchemeSpecificPart());
    this.databaseName = uri.getPath().replace("/", "");
}
 
Example #26
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetTransactionManager() throws Exception {
	DataSource ds = mock(DataSource.class);
	TransactionManager tm = mock(TransactionManager.class);
	LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(ds);
	lsfb.setJtaTransactionManager(tm);
	Object jtaPlatform = lsfb.getProperties().get(AvailableSettings.JTA_PLATFORM);
	assertNotNull(jtaPlatform);
	assertSame(tm, jtaPlatform.getClass().getMethod("retrieveTransactionManager").invoke(jtaPlatform));
	assertTrue(lsfb.getProperties().get(AvailableSettings.TRANSACTION_STRATEGY) instanceof CMTTransactionFactory);
}
 
Example #27
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public void applyConfig(Configuration configuration) {

			Properties prop = configuration.getProperties();

			try {
    			String url = prop.getProperty(AvailableSettings.URL, "");

    			URI full = new URI(url);
				URI uri = new URI(full.getSchemeSpecificPart());
				setProtocol(full.getScheme());
				setSubProtocol(uri.getScheme());
				setHost(uri.getHost());
				int intPort = uri.getPort();
                port = intPort == -1 ? "" : String.valueOf(intPort);
				path = uri.getPath().replace("/", "");
				query = uri.getQuery();
			} catch (URISyntaxException e) {
				logger.error("Could not parse hibernate url.", e);
			}

			driverClass = prop.getProperty(AvailableSettings.DRIVER);
			dialect = prop.getProperty(AvailableSettings.DIALECT);
			preferredTestQuery = prop.getProperty(PREFFERED_TEST_QUERY, "SELECT 1;");

			userName = prop.getProperty(AvailableSettings.USER, "sailfish");
			password = prop.getProperty(AvailableSettings.PASS, "999");

		}
 
Example #28
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 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
 * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one)
 * @since 4.3
 */
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {
	super(metadataSources);

	getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(AvailableSettings.DATASOURCE, dataSource);
	}

	// Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default)
	try {
		// Try Hibernate 5.2
		AvailableSettings.class.getField("CONNECTION_HANDLING");
		getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD");
	}
	catch (NoSuchFieldException ex) {
		// Try Hibernate 5.1
		try {
			AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
			getProperties().put("hibernate.connection.release_mode", "ON_CLOSE");
		}
		catch (NoSuchFieldException ex2) {
			// on Hibernate 5.0.x or lower - no need to change the default there
		}
	}

	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #29
Source File: SakaiPersistenceUnitManager.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public void preparePersistenceUnitInfos() {
    MutablePersistenceUnitInfo pui = new MutablePersistenceUnitInfo();
    pui.setPersistenceUnitName(defaultPersistenceUnitName);
    pui.setExcludeUnlistedClasses(true);

    if (pui.getJtaDataSource() == null) {
        pui.setJtaDataSource(jtaDataSource);
    }
    if (pui.getNonJtaDataSource() == null) {
        pui.setNonJtaDataSource(dataSource);
    }

    // override default UUIDGenerator with AssignableUUIDGenerator
    pui.addProperty(org.hibernate.jpa.AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER, SakaiIdentifierGeneratorProvider.class.getName());
    AssignableUUIDGenerator.setServerConfigurationService(serverConfigurationService);

    postProcessPersistenceUnitInfo(pui);

    Boolean autoddl = serverConfigurationService.getBoolean("auto.ddl", true);
    String hbm2ddl = serverConfigurationService.getString(AvailableSettings.HBM2DDL_AUTO);
    if (autoddl) {
        // if sakai auto.ddl is on then this needs to be set to update
        hbm2ddl = "update";
    }
    pui.getProperties().setProperty(AvailableSettings.HBM2DDL_AUTO, StringUtils.defaultString(hbm2ddl));

    defaultPersistenceUnitInfo = pui;
}
 
Example #30
Source File: ManagedBeanRegistryInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private BeanContainer resoveBeanContainer(Map configurationValues, ServiceRegistryImplementor serviceRegistry) {
	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
	final ConfigurationService cfgSvc = serviceRegistry.getService( ConfigurationService.class );

	// was a specific container explicitly specified?
	final Object explicitBeanContainer = configurationValues.get( AvailableSettings.BEAN_CONTAINER );
	if ( explicitBeanContainer != null ) {
		return interpretExplicitBeanContainer( explicitBeanContainer, classLoaderService, serviceRegistry );
	}

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// simplified CDI support

	final boolean isCdiAvailable = isCdiAvailable( classLoaderService );
	final Object beanManagerRef = cfgSvc.getSettings().get( AvailableSettings.CDI_BEAN_MANAGER );
	if ( beanManagerRef != null ) {
		if ( !isCdiAvailable ) {
			BeansMessageLogger.BEANS_LOGGER.beanManagerButCdiNotAvailable( beanManagerRef );
		}

		return CdiBeanContainerBuilder.fromBeanManagerReference( beanManagerRef, serviceRegistry );
	}
	else {
		if ( isCdiAvailable ) {
			BeansMessageLogger.BEANS_LOGGER.noBeanManagerButCdiAvailable();
		}
	}

	return null;
}