org.hibernate.engine.config.spi.ConfigurationService Java Examples

The following examples show how to use org.hibernate.engine.config.spi.ConfigurationService. 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: PersistentTableBulkIdStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void initialize(MetadataBuildingOptions buildingOptions, SessionFactoryOptions sessionFactoryOptions) {
	final StandardServiceRegistry serviceRegistry = buildingOptions.getServiceRegistry();
	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	final String catalogName = configService.getSetting(
			CATALOG,
			StandardConverters.STRING,
			configService.getSetting( AvailableSettings.DEFAULT_CATALOG, StandardConverters.STRING )
	);
	final String schemaName = configService.getSetting(
			SCHEMA,
			StandardConverters.STRING,
			configService.getSetting( AvailableSettings.DEFAULT_SCHEMA, StandardConverters.STRING )
	);

	this.catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier( catalogName );
	this.schema = jdbcEnvironment.getIdentifierHelper().toIdentifier( schemaName );

	this.dropIdTables = configService.getSetting(
			DROP_ID_TABLES,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #2
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String determineCurrentSchemaName(
		DatabaseMetaData databaseMetaData,
		ServiceRegistry serviceRegistry,
		Dialect dialect) throws SQLException {
	final SchemaNameResolver schemaNameResolver;

	final Object setting = serviceRegistry.getService( ConfigurationService.class ).getSettings().get( SCHEMA_NAME_RESOLVER );
	if ( setting == null ) {
		schemaNameResolver = dialect.getSchemaNameResolver();
	}
	else {
		schemaNameResolver = serviceRegistry.getService( StrategySelector.class ).resolveDefaultableStrategy(
				SchemaNameResolver.class,
				setting,
				dialect.getSchemaNameResolver()
		);
	}

	try {
		return schemaNameResolver.resolveSchemaName( databaseMetaData.getConnection(), dialect );
	}
	catch (Exception e) {
		log.debug( "Unable to resolve connection default schema", e );
		return null;
	}
}
 
Example #3
Source File: DefaultIdentifierGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
	this.serviceRegistry = serviceRegistry;
	this.dialect = serviceRegistry.getService( JdbcEnvironment.class ).getDialect();
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	final boolean useNewIdentifierGenerators = configService.getSetting(
			AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS,
			StandardConverters.BOOLEAN,
			true
	);

	if(!useNewIdentifierGenerators) {
		register( "sequence", SequenceGenerator.class );
	}
}
 
Example #4
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void prepareEventListeners(MetadataImplementor metadata) {
	final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
	final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );

	eventListenerRegistry.prepare( metadata );

	for ( Map.Entry entry : ( (Map<?, ?>) cfgService.getSettings() ).entrySet() ) {
		if ( !String.class.isInstance( entry.getKey() ) ) {
			continue;
		}
		final String propertyName = (String) entry.getKey();
		if ( !propertyName.startsWith( org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX ) ) {
			continue;
		}
		final String eventTypeName = propertyName.substring(
				org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX.length() + 1
		);
		final EventType eventType = EventType.resolveEventTypeByName( eventTypeName );
		final EventListenerGroup eventListenerGroup = eventListenerRegistry.getEventListenerGroup( eventType );
		for ( String listenerImpl : ( (String) entry.getValue() ).split( " ," ) ) {
			eventListenerGroup.appendListener( instantiate( listenerImpl, classLoaderService ) );
		}
	}
}
 
Example #5
Source File: SchemaValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void validate(Metadata metadata, ServiceRegistry serviceRegistry) {
	LOG.runningSchemaValidator();

	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );

	final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class );

	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			ExceptionHandlerHaltImpl.INSTANCE
	);

	tool.getSchemaValidator( config ).doValidation( metadata, executionOptions );
}
 
Example #6
Source File: Oracle12cDialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
	super.contributeTypes( typeContributions, serviceRegistry );

	// account for Oracle's deprecated support for LONGVARBINARY...
	// 		prefer BLOB, unless the user opts out of it
	boolean preferLong = serviceRegistry.getService( ConfigurationService.class ).getSetting(
			PREFER_LONG_RAW,
			StandardConverters.BOOLEAN,
			false
	);

	if ( !preferLong ) {
		typeContributions.contributeType( MaterializedBlobType.INSTANCE, "byte[]", byte[].class.getName() );
		typeContributions.contributeType( WrappedMaterializedBlobType.INSTANCE, "Byte[]", Byte[].class.getName() );
	}
}
 
Example #7
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static TargetDescriptor buildTargetDescriptor(
		EnumSet<TargetType> targetTypes,
		String outputFile,
		ServiceRegistry serviceRegistry) {
	final ScriptTargetOutput scriptTarget;
	if ( targetTypes.contains( TargetType.SCRIPT ) ) {
		if ( outputFile == null ) {
			throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
		}
		scriptTarget = Helper.interpretScriptTargetSetting(
				outputFile,
				serviceRegistry.getService( ClassLoaderService.class ),
				(String) serviceRegistry.getService( ConfigurationService.class ).getSettings().get( AvailableSettings.HBM2DDL_CHARSET_NAME )
		);
	}
	else {
		scriptTarget = null;
	}

	return new TargetDescriptorImpl( targetTypes, scriptTarget );
}
 
Example #8
Source File: DefaultMergeEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private EntityCopyObserver createEntityCopyObserver(SessionFactoryImplementor sessionFactory) {
	final ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
	if ( entityCopyObserverStrategy == null ) {
		final ConfigurationService configurationService
				= serviceRegistry.getService( ConfigurationService.class );
		entityCopyObserverStrategy = configurationService.getSetting(
				AvailableSettings.MERGE_ENTITY_COPY_OBSERVER,
				new ConfigurationService.Converter<String>() {
					@Override
					public String convert(Object value) {
						return value.toString();
					}
				},
				EntityCopyNotAllowedObserver.SHORT_NAME
		);
		LOG.debugf( "EntityCopyObserver strategy: %s", entityCopyObserverStrategy );
	}
	final StrategySelector strategySelector = serviceRegistry.getService( StrategySelector.class );
	return strategySelector.resolveStrategy( EntityCopyObserver.class, entityCopyObserverStrategy );
}
 
Example #9
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static ValidatorFactory resolveProvidedFactory(ConfigurationService cfgService) {
	return cfgService.getSetting(
			FACTORY_PROPERTY,
			new ConfigurationService.Converter<ValidatorFactory>() {
				@Override
				public ValidatorFactory convert(Object value) {
					try {
						return ValidatorFactory.class.cast( value );
					}
					catch ( ClassCastException e ) {
						throw new IntegrationException(
								String.format(
										Locale.ENGLISH,
										"ValidatorFactory reference (provided via `%s` setting) was not castable to %s : %s",
										FACTORY_PROPERTY,
										ValidatorFactory.class.getName(),
										value.getClass().getName()
								)
						);
					}
				}
			},
			null
	);
}
 
Example #10
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "UnusedParameters"})
private static void applyRelationalConstraints(ValidatorFactory factory, ActivationContext activationContext) {
	final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
	if ( !cfgService.getSetting( BeanValidationIntegrator.APPLY_CONSTRAINTS, StandardConverters.BOOLEAN, true  ) ) {
		LOG.debug( "Skipping application of relational constraints from legacy Hibernate Validator" );
		return;
	}

	final Set<ValidationMode> modes = activationContext.getValidationModes();
	if ( ! ( modes.contains( ValidationMode.DDL ) || modes.contains( ValidationMode.AUTO ) ) ) {
		return;
	}

	applyRelationalConstraints(
			factory,
			activationContext.getMetadata().getEntityBindings(),
			cfgService.getSettings(),
			activationContext.getServiceRegistry().getService( JdbcServices.class ).getDialect(),
			new ClassLoaderAccessImpl(
					null,
					activationContext.getServiceRegistry().getService( ClassLoaderService.class )
			)
	);
}
 
Example #11
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ArrayList<MetadataSourceType> resolveInitialSourceProcessOrdering(ConfigurationService configService) {
	final ArrayList<MetadataSourceType> initialSelections = new ArrayList<>();

	final String sourceProcessOrderingSetting = configService.getSetting(
			AvailableSettings.ARTIFACT_PROCESSING_ORDER,
			StandardConverters.STRING
	);
	if ( sourceProcessOrderingSetting != null ) {
		final String[] orderChoices = StringHelper.split( ",; ", sourceProcessOrderingSetting, false );
		initialSelections.addAll( CollectionHelper.arrayList( orderChoices.length ) );
		for ( String orderChoice : orderChoices ) {
			initialSelections.add( MetadataSourceType.parsePrecedence( orderChoice ) );
		}
	}
	if ( initialSelections.isEmpty() ) {
		initialSelections.add( MetadataSourceType.HBM );
		initialSelections.add( MetadataSourceType.CLASS );
	}

	return initialSelections;
}
 
Example #12
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 #13
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 #14
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public MappingDefaultsImpl(StandardServiceRegistry serviceRegistry) {
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	this.implicitSchemaName = configService.getSetting(
			AvailableSettings.DEFAULT_SCHEMA,
			StandardConverters.STRING,
			null
	);

	this.implicitCatalogName = configService.getSetting(
			AvailableSettings.DEFAULT_CATALOG,
			StandardConverters.STRING,
			null
	);

	this.implicitlyQuoteIdentifiers = configService.getSetting(
			AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS,
			StandardConverters.BOOLEAN,
			false
	);

	this.implicitCacheAccessType = configService.getSetting(
			AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY,
			new ConfigurationService.Converter<AccessType>() {
				@Override
				public AccessType convert(Object value) {
					return AccessType.fromExternalName( value.toString() );
				}
			}
	);
}
 
Example #15
Source File: JaccIntegrator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void integrate(
		Metadata metadata,
		SessionFactoryImplementor sessionFactory,
		SessionFactoryServiceRegistry serviceRegistry) {
	doIntegration(
			serviceRegistry.getService( ConfigurationService.class ).getSettings(),
			// pass no permissions here, because atm actually injecting the
			// permissions into the JaccService is handled on SessionFactoryImpl via
			// the org.hibernate.boot.cfgxml.spi.CfgXmlAccessService
			null,
			serviceRegistry
	);
}
 
Example #16
Source File: GlobalTemporaryTableBulkIdStrategy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void initialize(MetadataBuildingOptions buildingOptions, SessionFactoryOptions sessionFactoryOptions) {
	final StandardServiceRegistry serviceRegistry = buildingOptions.getServiceRegistry();
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );
	this.dropIdTables = configService.getSetting(
			DROP_ID_TABLES,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #17
Source File: TableGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the table name to use for the generator values.
 * <p/>
 * Called during {@link #configure configuration}.
 *
 * @see #getTableName()
 * @param params The params supplied in the generator config (plus some standard useful extras).
 * @param jdbcEnvironment The JDBC environment
 * @return The table name to use.
 */
@SuppressWarnings({"UnusedParameters", "WeakerAccess"})
protected QualifiedName determineGeneratorTableName(Properties params, JdbcEnvironment jdbcEnvironment, ServiceRegistry serviceRegistry) {

	String fallbackTableName = DEF_TABLE;

	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( AvailableSettings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackTableName = generatorName;
		}
	}


	String tableName = ConfigurationHelper.getString( TABLE_PARAM, params, fallbackTableName );

	if ( tableName.contains( "." ) ) {
		return QualifiedNameParser.INSTANCE.parse( tableName );
	}
	else {
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		return new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( tableName )
		);
	}
}
 
Example #18
Source File: TableGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	storeLastUsedValue = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( AvailableSettings.TABLE_GENERATOR_STORE_LAST_USED, StandardConverters.BOOLEAN, true );
	identifierType = type;

	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );

	qualifiedTableName = determineGeneratorTableName( params, jdbcEnvironment, serviceRegistry );
	segmentColumnName = determineSegmentColumnName( params, jdbcEnvironment );
	valueColumnName = determineValueColumnName( params, jdbcEnvironment );

	segmentValue = determineSegmentValue( params );

	segmentValueLength = determineSegmentColumnSize( params );
	initialValue = determineInitialValue( params );
	incrementSize = determineIncrementSize( params );

	final String optimizationStrategy = ConfigurationHelper.getString(
			OPT_PARAM,
			params,
			OptimizerFactory.determineImplicitOptimizerName( incrementSize, params )
	);
	int optimizerInitialValue = ConfigurationHelper.getInt( INITIAL_PARAM, params, -1 );
	optimizer = OptimizerFactory.buildOptimizer(
			optimizationStrategy,
			identifierType.getReturnedClass(),
			incrementSize,
			optimizerInitialValue
	);
}
 
Example #19
Source File: StatisticsInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public StatisticsImplementor initiateService(
		SessionFactoryImplementor sessionFactory,
		SessionFactoryOptions sessionFactoryOptions,
		ServiceRegistryImplementor registry) {
	final Object configValue = registry
			.getService( ConfigurationService.class )
			.getSettings()
			.get( STATS_BUILDER );
	return initiateServiceInternal( sessionFactory, configValue, registry );
}
 
Example #20
Source File: StatisticsInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public StatisticsImplementor initiateService(SessionFactoryServiceInitiatorContext context) {
	final Object configValue = context.getServiceRegistry()
			.getService( ConfigurationService.class )
			.getSettings()
			.get( STATS_BUILDER );
	return initiateServiceInternal( context.getSessionFactory(), configValue, context.getServiceRegistry() );
}
 
Example #21
Source File: IdentifierGeneration.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
static QualifiedName determineTableName(Properties params, ServiceRegistry serviceRegistry) {
	String fallbackTableName = TableGenerator.DEF_TABLE;
	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( Settings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackTableName = generatorName;
		}
	}

	String tableName = ConfigurationHelper.getString( TableGenerator.TABLE_PARAM, params, fallbackTableName );

	QualifiedNameParser.NameParts qualifiedTableName;
	if ( tableName.contains( "." ) ) {
		qualifiedTableName = QualifiedNameParser.INSTANCE.parse( tableName );
	}
	else {
		JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		qualifiedTableName = new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( tableName )
		);
	}
	return qualifiedTableName;
}
 
Example #22
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static boolean autoKeywordQuoting(ConfigurationService cfgService) {
	return cfgService.getSetting(
			AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #23
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean globalQuotingSkippedForColumnDefinitions(ConfigurationService cfgService) {
	return cfgService.getSetting(
			AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS_SKIP_COLUMN_DEFINITIONS,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #24
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static boolean logWarnings(ConfigurationService cfgService, Dialect dialect) {
	return cfgService.getSetting(
			AvailableSettings.LOG_JDBC_WARNINGS,
			StandardConverters.BOOLEAN,
			dialect.isJdbcLogWarningsEnabledByDefault()
	);
}
 
Example #25
Source File: IdentifierGeneration.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine the name of the sequence (or table if this resolves to a physical table)
 * to use.
 *
 * @param params The params supplied in the generator config (plus some standard useful extras).
 * @return The sequence name
 */
static QualifiedName determineSequenceName(Properties params, ServiceRegistry serviceRegistry) {
	final String sequencePerEntitySuffix = ConfigurationHelper.getString( SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX, params, SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX );

	String fallbackSequenceName = SequenceStyleGenerator.DEF_SEQUENCE_NAME;
	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( Settings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackSequenceName = generatorName;
		}
	}

	// JPA_ENTITY_NAME value honors <class ... entity-name="..."> (HBM) and @Entity#name (JPA) overrides.
	final String defaultSequenceName = ConfigurationHelper.getBoolean( SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY, params, false )
			? params.getProperty( SequenceStyleGenerator.JPA_ENTITY_NAME ) + sequencePerEntitySuffix
			: fallbackSequenceName;

	final String sequenceName = ConfigurationHelper.getString( SequenceStyleGenerator.SEQUENCE_PARAM, params, defaultSequenceName );
	if ( sequenceName.contains( "." ) ) {
		return QualifiedNameParser.INSTANCE.parse( sequenceName );
	}
	else {
		JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema =  jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		return new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( sequenceName )
		);
	}
}
 
Example #26
Source File: TableReactiveIdentifierGenerator.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	Dialect dialect = jdbcEnvironment.getDialect();

	if (sequenceEmulator) {
		//it's a SequenceStyleGenerator backed by a table
		qualifiedTableName = determineSequenceName( params, serviceRegistry );
		valueColumnName = determineValueColumnNameForSequenceEmulation( params, jdbcEnvironment );
		segmentColumnName = null;
		segmentValue = null;
		initialValue = determineInitialValueForSequenceEmulation( params );

		storeLastUsedValue = false;
	}
	else {
		//It's a regular TableGenerator
		qualifiedTableName = determineTableName( params, serviceRegistry );
		segmentColumnName = determineSegmentColumnName( params, jdbcEnvironment );
		valueColumnName = determineValueColumnNameForTable( params, jdbcEnvironment );
		segmentValue = determineSegmentValue( params );
		initialValue = determineInitialValueForTable( params );

		storeLastUsedValue = serviceRegistry.getService( ConfigurationService.class )
				.getSetting( Settings.TABLE_GENERATOR_STORE_LAST_USED, StandardConverters.BOOLEAN, true );
	}

	// allow physical naming strategies a chance to kick in
	renderedTableName = jdbcEnvironment.getQualifiedObjectNameFormatter()
			.format( qualifiedTableName, dialect );

	selectQuery = buildSelectQuery( dialect );
	updateQuery = buildUpdateQuery( dialect );
	insertQuery = buildInsertQuery( dialect );
}
 
Example #27
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings( {"UnusedDeclaration"})
public static void applyCallbackListeners(ValidatorFactory validatorFactory, ActivationContext activationContext) {
	final Set<ValidationMode> modes = activationContext.getValidationModes();
	if ( ! ( modes.contains( ValidationMode.CALLBACK ) || modes.contains( ValidationMode.AUTO ) ) ) {
		return;
	}

	final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
	final ClassLoaderService classLoaderService = activationContext.getServiceRegistry().getService( ClassLoaderService.class );

	// de-activate not-null tracking at the core level when Bean Validation is present unless the user explicitly
	// asks for it
	if ( cfgService.getSettings().get( Environment.CHECK_NULLABILITY ) == null ) {
		activationContext.getSessionFactory().getSessionFactoryOptions().setCheckNullability( false );
	}

	final BeanValidationEventListener listener = new BeanValidationEventListener(
			validatorFactory,
			cfgService.getSettings(),
			classLoaderService
	);

	final EventListenerRegistry listenerRegistry = activationContext.getServiceRegistry()
			.getService( EventListenerRegistry.class );

	listenerRegistry.addDuplicationStrategy( DuplicationStrategyImpl.INSTANCE );

	listenerRegistry.appendListeners( EventType.PRE_INSERT, listener );
	listenerRegistry.appendListeners( EventType.PRE_UPDATE, listener );
	listenerRegistry.appendListeners( EventType.PRE_DELETE, listener );

	listener.initialize( cfgService.getSettings(), classLoaderService );
}
 
Example #28
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static ValidatorFactory getValidatorFactory(ActivationContext activationContext) {
	// IMPL NOTE : We can either be provided a ValidatorFactory or make one.  We can be provided
	// a ValidatorFactory in 2 different ways.  So here we "get" a ValidatorFactory in the following order:
	//		1) Look into SessionFactoryOptions.getValidatorFactoryReference()
	//		2) Look into ConfigurationService
	//		3) build a new ValidatorFactory

	// 1 - look in SessionFactoryOptions.getValidatorFactoryReference()
	ValidatorFactory factory = resolveProvidedFactory( activationContext.getSessionFactory().getSessionFactoryOptions() );
	if ( factory != null ) {
		return factory;
	}

	// 2 - look in ConfigurationService
	factory = resolveProvidedFactory( activationContext.getServiceRegistry().getService( ConfigurationService.class ) );
	if ( factory != null ) {
		return factory;
	}

	// 3 - build our own
	try {
		return Validation.buildDefaultValidatorFactory();
	}
	catch ( Exception e ) {
		throw new IntegrationException( "Unable to build the default ValidatorFactory", e );
	}
}
 
Example #29
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;
}
 
Example #30
Source File: SchemaUpdate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(EnumSet<TargetType> targetTypes, Metadata metadata, ServiceRegistry serviceRegistry) {
	if ( targetTypes.isEmpty() ) {
		LOG.debug( "Skipping SchemaExport as no targets were specified" );
		return;
	}

	exceptions.clear();
	LOG.runningHbm2ddlSchemaUpdate();

	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
	config.put( AvailableSettings.HBM2DDL_DELIMITER, delimiter );
	config.put( AvailableSettings.FORMAT_SQL, format );

	final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class );

	final ExceptionHandler exceptionHandler = haltOnError
			? ExceptionHandlerHaltImpl.INSTANCE
			: new ExceptionHandlerCollectingImpl();

	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			exceptionHandler
	);

	final TargetDescriptor targetDescriptor = SchemaExport.buildTargetDescriptor( targetTypes, outputFile, serviceRegistry );

	try {
		tool.getSchemaMigrator( config ).doMigration( metadata, executionOptions, targetDescriptor );
	}
	finally {
		if ( exceptionHandler instanceof ExceptionHandlerCollectingImpl ) {
			exceptions.addAll( ( (ExceptionHandlerCollectingImpl) exceptionHandler ).getExceptions() );
		}
	}
}