Projects >> hibernate-orm >>18e44d173975bb24835c03acea0d7909190832e8

Chunk
Conflicting content
import org.hibernate.EntityMode;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.cache.spi.QueryCacheFactory;
<<<<<<< HEAD
=======
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.hql.spi.MultiTableBulkIdStrategy;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.loader.BatchFetchStyle;
Solution content
import org.hibernate.EntityMode;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.cache.spi.QueryCacheFactory;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.hql.spi.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.loader.BatchFetchStyle;
File
Settings.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
//	}
		return entityTuplizerFactory;
	}

<<<<<<< HEAD
=======
//	public ComponentTuplizerFactory getComponentTuplizerFactory() {
//		return componentTuplizerFactory;


>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	// package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	void setDefaultSchemaName(String string) {
Solution content
		return entityTuplizerFactory;
	}

	// package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	void setDefaultSchemaName(String string) {
File
Settings.java
Developer's decision
Version 1
Kind of conflict
Comment
Chunk
Conflicting content
			settings.setQueryCacheFactory( createQueryCacheFactory( properties, serviceRegistry ) );
		}

<<<<<<< HEAD
		String prefix = properties.getProperty( Environment.CACHE_REGION_PREFIX );
=======
		// The cache provider is needed when we either have second-level cache enabled
		// or query cache enabled.  Note that useSecondLevelCache is enabled by default
		settings.setRegionFactory( createRegionFactory( properties, ( useSecondLevelCache || useQueryCache ), serviceRegistry ) );

		boolean useMinimalPuts = ConfigurationHelper.getBoolean(
				AvailableSettings.USE_MINIMAL_PUTS, properties, settings.getRegionFactory().isMinimalPutsEnabledByDefault()
		);
		if ( debugEnabled ) {
			LOG.debugf( "Optimize cache for minimal puts: %s", enabledDisabled(useMinimalPuts) );
		}
		settings.setMinimalPutsEnabled( useMinimalPuts );

		String prefix = properties.getProperty( AvailableSettings.CACHE_REGION_PREFIX );
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
		if ( StringHelper.isEmpty(prefix) ) {
			prefix=null;
		}
Solution content
			settings.setQueryCacheFactory( createQueryCacheFactory( properties, serviceRegistry ) );
		}

		String prefix = properties.getProperty( Environment.CACHE_REGION_PREFIX );
		if ( StringHelper.isEmpty(prefix) ) {
			prefix=null;
		}
File
SettingsFactory.java
Developer's decision
Version 1
Kind of conflict
Comment
If statement
Method invocation
Variable
Chunk
Conflicting content
		}
		settings.setStructuredCacheEntriesEnabled( useStructuredCacheEntries );

<<<<<<< HEAD
		boolean useIdentifierRollback = ConfigurationHelper.getBoolean( Environment.USE_IDENTIFIER_ROLLBACK, properties );
=======

		//Statistics and logging:

		boolean useStatistics = ConfigurationHelper.getBoolean( AvailableSettings.GENERATE_STATISTICS, properties );
		if ( debugEnabled ) {
			LOG.debugf( "Statistics: %s", enabledDisabled(useStatistics) );
		}
		settings.setStatisticsEnabled( useStatistics );

		boolean useIdentifierRollback = ConfigurationHelper.getBoolean( AvailableSettings.USE_IDENTIFIER_ROLLBACK, properties );
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
		if ( debugEnabled ) {
			LOG.debugf( "Deleted entity synthetic identifier rollback: %s", enabledDisabled(useIdentifierRollback) );
		}
Solution content
		}
		settings.setStructuredCacheEntriesEnabled( useStructuredCacheEntries );

		boolean useIdentifierRollback = ConfigurationHelper.getBoolean( AvailableSettings.USE_IDENTIFIER_ROLLBACK, properties );
		if ( debugEnabled ) {
			LOG.debugf( "Deleted entity synthetic identifier rollback: %s", enabledDisabled(useIdentifierRollback) );
		}
File
SettingsFactory.java
Developer's decision
Combination
Kind of conflict
Comment
If statement
Method invocation
Variable
Chunk
Conflicting content
		}
	}

<<<<<<< HEAD
=======
	private static RegionFactory createRegionFactory(Properties properties, boolean cachingEnabled, ServiceRegistry serviceRegistry) {
		String regionFactoryClassName = RegionFactoryInitiator.mapLegacyNames(
				ConfigurationHelper.getString(
						AvailableSettings.CACHE_REGION_FACTORY, properties, null
				)
		);
		if ( regionFactoryClassName == null || !cachingEnabled) {
			regionFactoryClassName = DEF_CACHE_REG_FACTORY;
		}
		LOG.debugf( "Cache region factory : %s", regionFactoryClassName );
		try {
			try {
				return (RegionFactory) serviceRegistry.getService( ClassLoaderService.class )
						.classForName( regionFactoryClassName )
						.getConstructor( Properties.class )
						.newInstance( properties );
			}
			catch ( NoSuchMethodException e ) {
				// no constructor accepting Properties found, try no arg constructor
				LOG.debugf(
						"%s did not provide constructor accepting java.util.Properties; attempting no-arg constructor.",
						regionFactoryClassName
				);
				return (RegionFactory) serviceRegistry.getService( ClassLoaderService.class )
						.classForName( regionFactoryClassName )
						.newInstance();
			}
		}
		catch ( Exception e ) {
			throw new HibernateException( "could not instantiate RegionFactory [" + regionFactoryClassName + "]", e );
		}
	}
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	//todo remove this once we move to new metamodel
	public static RegionFactory createRegionFactory(Properties properties, boolean cachingEnabled) {
		// todo : REMOVE!  THIS IS TOTALLY A TEMPORARY HACK FOR org.hibernate.cfg.AnnotationBinder which will be going away
Solution content
		}
	}

	//todo remove this once we move to new metamodel
	public static RegionFactory createRegionFactory(Properties properties, boolean cachingEnabled) {
		// todo : REMOVE!  THIS IS TOTALLY A TEMPORARY HACK FOR org.hibernate.cfg.AnnotationBinder which will be going away
File
SettingsFactory.java
Developer's decision
Version 1
Kind of conflict
Method declaration
Chunk
Conflicting content
import java.util.Properties;
import java.util.Set;

<<<<<<< HEAD
import org.jboss.logging.Logger;

=======
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
Solution content
import java.util.Properties;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
File
Dialect.java
Developer's decision
Version 2
Kind of conflict
Import
Chunk
Conflicting content
		this.transactionEnvironment = new TransactionEnvironmentImpl( this );
		this.observer.sessionFactoryCreated( this );

<<<<<<< HEAD
		final JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting = determineJpaMetaModelPopulationSetting( cfg );
		if ( jpaMetaModelPopulationSetting != JpaMetaModelPopulationSetting.DISABLED ) {
			this.jpaMetamodel = org.hibernate.jpa.metamodel.internal.legacy.MetamodelImpl.buildMetamodel(
					cfg.getClassMappings(),
					this,
					jpaMetaModelPopulationSetting == JpaMetaModelPopulationSetting.IGNORE_UNSUPPORTED
			);
=======
	private JdbcConnectionAccess buildLocalConnectionAccess() {
		return new JdbcConnectionAccess() {
			@Override
			public Connection obtainConnection() throws SQLException {
				return settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE
						? serviceRegistry.getService( ConnectionProvider.class ).getConnection()
						: serviceRegistry.getService( MultiTenantConnectionProvider.class ).getAnyConnection();
			}

			@Override
			public void releaseConnection(Connection connection) throws SQLException {
				if ( settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE ) {
					serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection );
				}
				else {
					serviceRegistry.getService( MultiTenantConnectionProvider.class ).releaseAnyConnection( connection );
				}
			}

			@Override
			public boolean supportsAggressiveRelease() {
				return false;
			}
		};
	}

	@SuppressWarnings({ "unchecked" })
	private CustomEntityDirtinessStrategy determineCustomEntityDirtinessStrategy() {
		CustomEntityDirtinessStrategy defaultValue = new CustomEntityDirtinessStrategy() {
			@Override
			public boolean canDirtyCheck(Object entity, EntityPersister persister, Session session) {
				return false;
			}

			@Override
			public boolean isDirty(Object entity, EntityPersister persister, Session session) {
				return false;
			}

			@Override
			public void resetDirty(Object entity, EntityPersister persister, Session session) {
			}

			@Override
			public void findDirty(
					Object entity,
					EntityPersister persister,
					Session session,
					DirtyCheckContext dirtyCheckContext) {
				// todo : implement proper method body
			}
		};
		return serviceRegistry.getService( ConfigurationService.class ).getSetting(
				AvailableSettings.CUSTOM_ENTITY_DIRTINESS_STRATEGY,
				CustomEntityDirtinessStrategy.class,
				defaultValue
		);
	}

	@SuppressWarnings({ "unchecked" })
	private CurrentTenantIdentifierResolver determineCurrentTenantIdentifierResolver(
			CurrentTenantIdentifierResolver explicitResolver) {
		if ( explicitResolver != null ) {
			return explicitResolver;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
		}
		else {
			jpaMetamodel = null;
Solution content
		this.transactionEnvironment = new TransactionEnvironmentImpl( this );
		this.observer.sessionFactoryCreated( this );

		final JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting = determineJpaMetaModelPopulationSetting( cfg );
		if ( jpaMetaModelPopulationSetting != JpaMetaModelPopulationSetting.DISABLED ) {
			this.jpaMetamodel = org.hibernate.jpa.metamodel.internal.legacy.MetamodelImpl.buildMetamodel(
					cfg.getClassMappings(),
					this,
					jpaMetaModelPopulationSetting == JpaMetaModelPopulationSetting.IGNORE_UNSUPPORTED
			);
		}
		else {
			jpaMetamodel = null;
		}
	}

	private JdbcConnectionAccess buildLocalConnectionAccess() {
		return new JdbcConnectionAccess() {
			@Override
			public Connection obtainConnection() throws SQLException {
				return settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE
						? serviceRegistry.getService( ConnectionProvider.class ).getConnection()
						: serviceRegistry.getService( MultiTenantConnectionProvider.class ).getAnyConnection();
			}

			@Override
			public void releaseConnection(Connection connection) throws SQLException {
				if ( settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE ) {
					serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection );
				}
				else {
					serviceRegistry.getService( MultiTenantConnectionProvider.class ).releaseAnyConnection( connection );
				}
			}

			@Override
			public boolean supportsAggressiveRelease() {
				return false;
			}
		};
	}

	protected JpaMetaModelPopulationSetting determineJpaMetaModelPopulationSetting(Configuration cfg) {
		final String setting = cfg.getProperties().getProperty( AvailableSettings.JPA_METAMODEL_POPULATION );
		return JpaMetaModelPopulationSetting.parse( setting );
	}

	@SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"})
	public SessionFactoryImpl(MetadataImplementor metadata,SessionFactoryOptions sessionFactoryOptions) throws HibernateException {
		LOG.debug( "Building session factory" );

		this.sessionFactoryOptions = sessionFactoryOptions;

		this.properties = createPropertiesFromMap(
		final String cacheRegionPrefix = stringBuilder.toString();
				metadata.getServiceRegistry().getService( ConfigurationService.class ).getSettings()
		);

		// TODO: these should be moved into SessionFactoryOptions
		this.settings = new SettingsFactory().buildSettings(
				properties,
				metadata.getServiceRegistry()
		);

		this.serviceRegistry =
				sessionFactoryOptions.getServiceRegistry()
						.getService( SessionFactoryServiceRegistryFactory.class )
						.buildServiceRegistry( this, metadata );

		this.jdbcServices = this.serviceRegistry.getService( JdbcServices.class );
		this.dialect = this.jdbcServices.getDialect();
		this.cacheAccess = this.serviceRegistry.getService( CacheImplementor.class );

		// TODO: get SQL functions from JdbcServices (HHH-6559)
		//this.sqlFunctionRegistry = new SQLFunctionRegistry( this.jdbcServices.getSqlFunctions() );
		this.sqlFunctionRegistry = new SQLFunctionRegistry( this.dialect, new HashMap() );

		// TODO: get SQL functions from a new service
		// this.sqlFunctionRegistry = new SQLFunctionRegistry( getDialect(), cfg.getSqlFunctions() );

		for ( SessionFactoryObserver observer : sessionFactoryOptions.getSessionFactoryObservers() ) {
			this.observer.addObserver( observer );
		}

		this.typeResolver = metadata.getTypeResolver().scope( this );
		this.typeHelper = new TypeLocatorImpl( typeResolver );

		this.filters = new HashMap();
		for ( FilterDefinition filterDefinition : metadata.getFilterDefinitions() ) {
			filters.put( filterDefinition.getFilterName(), filterDefinition );
		}

		LOG.debugf( "Session factory constructed with filter configurations : %s", filters );
		LOG.debugf( "Instantiating session factory with properties: %s", properties );

		this.queryPlanCache = new QueryPlanCache( this );

		class IntegratorObserver implements SessionFactoryObserver {
			private ArrayList integrators = new ArrayList();

			@Override
			public void sessionFactoryCreated(SessionFactory factory) {
			}

			@Override
			public void sessionFactoryClosed(SessionFactory factory) {
				for ( Integrator integrator : integrators ) {
					integrator.disintegrate( SessionFactoryImpl.this, SessionFactoryImpl.this.serviceRegistry );
				}
			}
		}

        final IntegratorObserver integratorObserver = new IntegratorObserver();
        this.observer.addObserver(integratorObserver);
        for (Integrator integrator : serviceRegistry.getService(IntegratorService.class).getIntegrators()) {
            integrator.integrate(metadata, this, this.serviceRegistry);
            integratorObserver.integrators.add(integrator);
        }


		//Generators:

		identifierGenerators = new HashMap();
		for ( EntityBinding entityBinding : metadata.getEntityBindings() ) {
			if ( entityBinding.isRoot() ) {
				identifierGenerators.put(
						entityBinding.getEntity().getName(),
						entityBinding.getHierarchyDetails().getEntityIdentifier().getIdentifierGenerator()
				);
			}
		}

		///////////////////////////////////////////////////////////////////////
		// Prepare persisters and link them up with their cache
		// region/access-strategy

		final MetamodelBuilder jpaMetamodelBuilder = new MetamodelBuilder(
				this,
				JpaMetaModelPopulationSetting.parse(
						properties.getProperty( AvailableSettings.JPA_METAMODEL_POPULATION  )
				)
		);

		StringBuilder stringBuilder = new StringBuilder();
		if ( settings.getCacheRegionPrefix() != null) {
			stringBuilder
					.append( settings.getCacheRegionPrefix() )
					.append( '.' );
		}

		RegionFactory regionFactory = serviceRegistry.getService( RegionFactory.class );
		entityPersisters = new HashMap();
		Map entityAccessStrategies = new HashMap();
		Map classMeta = new HashMap();
		for ( EntityBinding model : metadata.getEntityBindings() ) {
			// TODO: should temp table prep happen when metadata is being built?
			//model.prepareTemporaryTables( metadata, getDialect() );
			// cache region is defined by the root-class in the hierarchy...
			EntityBinding rootEntityBinding = metadata.getRootEntityBinding( model.getEntity().getName() );
			EntityRegionAccessStrategy accessStrategy = null;
			if ( settings.isSecondLevelCacheEnabled() &&
					rootEntityBinding.getHierarchyDetails().getCaching() != null &&
					model.getHierarchyDetails().getCaching() != null  ) {
				final String cacheRegionName = cacheRegionPrefix + rootEntityBinding.getHierarchyDetails().getCaching().getRegion();
				accessStrategy = EntityRegionAccessStrategy.class.cast( entityAccessStrategies.get( cacheRegionName ) );
				if ( accessStrategy == null ) {
					AccessType accessType = model.getHierarchyDetails().getCaching().getAccessType();
					if ( accessType == null ) {
						accessType = regionFactory.getDefaultAccessType();
					}
					if ( LOG.isTraceEnabled() ) {
						LOG.tracev( "Building cache for entity data [{0}]", model.getEntity().getName() );
					}
					EntityRegion entityRegion = serviceRegistry.getService( RegionFactory.class ).buildEntityRegion(
							cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
					);
					accessStrategy = entityRegion.buildAccessStrategy( accessType );
					entityAccessStrategies.put( cacheRegionName, accessStrategy );
					cacheAccess.addCacheRegion( cacheRegionName, entityRegion );
				}
			}

			NaturalIdRegionAccessStrategy naturalIdAccessStrategy = null;
			if ( settings.isSecondLevelCacheEnabled() &&
					rootEntityBinding.getHierarchyDetails().getNaturalIdCaching() != null &&
					model.getHierarchyDetails().getNaturalIdCaching() != null ) {
				final String naturalIdCacheRegionName = cacheRegionPrefix + rootEntityBinding.getHierarchyDetails()
						.getNaturalIdCaching()
						.getRegion();
				naturalIdAccessStrategy = (NaturalIdRegionAccessStrategy) entityAccessStrategies.get(
						naturalIdCacheRegionName
				);
				if ( naturalIdAccessStrategy == null ) {
					final CacheDataDescriptionImpl naturaIdCacheDataDescription = CacheDataDescriptionImpl.decode( model );
					NaturalIdRegion naturalIdRegion = null;
					try {
						naturalIdRegion = serviceRegistry.getService( RegionFactory.class )
								.buildNaturalIdRegion(
										naturalIdCacheRegionName,
										properties,
										naturaIdCacheDataDescription
								);
					}
					catch ( UnsupportedOperationException e ) {
						LOG.warnf(
								"Shared cache region factory [%s] does not support natural id caching; " +
										"shared NaturalId caching will be disabled for not be enabled for %s",
								serviceRegistry.getService( RegionFactory.class ).getClass().getName(),
								model.getEntity().getName()
						);
					}
					if ( naturalIdRegion != null ) {
						naturalIdAccessStrategy = naturalIdRegion.buildAccessStrategy( serviceRegistry.getService( RegionFactory.class ).getDefaultAccessType() );
						entityAccessStrategies.put( naturalIdCacheRegionName, naturalIdAccessStrategy );
						cacheAccess.addCacheRegion( naturalIdCacheRegionName, naturalIdRegion );
					}
				}
			}
			EntityPersister cp = serviceRegistry.getService( PersisterFactory.class ).createEntityPersister(
					model, accessStrategy,naturalIdAccessStrategy, this, metadata
			);
			entityPersisters.put( model.getEntity().getName(), cp );
			classMeta.put( model.getEntity().getName(), cp.getClassMetadata() );
			jpaMetamodelBuilder.add( model );
		}
		this.classMetadata = Collections.unmodifiableMap(classMeta);

		Map> tmpEntityToCollectionRoleMap = new HashMap>();
		collectionPersisters = new HashMap();
		Map tmpCollectionMetadata = new HashMap();
		for ( PluralAttributeBinding model : metadata.getCollectionBindings() ) {
			if ( model.getAttribute() == null ) {
				throw new IllegalStateException( "No attribute defined for a AbstractPluralAttributeBinding: " +  model );
			}
			if ( model.getAttribute().isSingular() ) {
				throw new IllegalStateException(
						"AbstractPluralAttributeBinding has a Singular attribute defined: " + model.getAttribute().getName()
				);
			}
			CollectionRegionAccessStrategy accessStrategy = null;
			if ( settings.isSecondLevelCacheEnabled() &&
					model.getCaching() != null ) {
				final String cacheRegionName = cacheRegionPrefix + model.getCaching().getRegion();
				AccessType accessType = model.getCaching().getAccessType();
				if(accessType == null){
					accessType = regionFactory.getDefaultAccessType();
				}
				if ( accessType != null && settings.isSecondLevelCacheEnabled() ) {
					if ( LOG.isTraceEnabled() ) {
						LOG.tracev( "Building cache for collection data [{0}]", model.getAttribute().getRole() );
					}
					CollectionRegion collectionRegion = serviceRegistry.getService( RegionFactory.class ).buildCollectionRegion(
							cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
					);
					accessStrategy = collectionRegion.buildAccessStrategy( accessType );
					entityAccessStrategies.put( cacheRegionName, accessStrategy );
					cacheAccess.addCacheRegion( cacheRegionName, collectionRegion );
				}
				CollectionRegion collectionRegion = serviceRegistry.getService( RegionFactory.class ).buildCollectionRegion(
						cacheRegionName, properties, CacheDataDescriptionImpl.decode( model )
				);
				accessStrategy = collectionRegion.buildAccessStrategy( accessType );
				entityAccessStrategies.put( cacheRegionName, accessStrategy );
				cacheAccess.addCacheRegion( cacheRegionName, collectionRegion );
			}
			CollectionPersister persister = serviceRegistry
					.getService( PersisterFactory.class )
					.createCollectionPersister( metadata, model, accessStrategy, this );
			collectionPersisters.put( model.getAttribute().getRole(), persister );
			tmpCollectionMetadata.put( model.getAttribute().getRole(), persister.getCollectionMetadata() );
			Type indexType = persister.getIndexType();
			if ( indexType != null && indexType.isAssociationType() && !indexType.isAnyType() ) {
				String entityName = ( ( AssociationType ) indexType ).getAssociatedEntityName( this );
				Set roles = tmpEntityToCollectionRoleMap.get( entityName );
				if ( roles == null ) {
					roles = new HashSet();
					tmpEntityToCollectionRoleMap.put( entityName, roles );
				}
				roles.add( persister.getRole() );
			}
			Type elementType = persister.getElementType();
			if ( elementType.isAssociationType() && !elementType.isAnyType() ) {
				String entityName = ( ( AssociationType ) elementType ).getAssociatedEntityName( this );
				Set roles = tmpEntityToCollectionRoleMap.get( entityName );
				if ( roles == null ) {
					roles = new HashSet();
					tmpEntityToCollectionRoleMap.put( entityName, roles );
				}
				roles.add( persister.getRole() );
			}
		}
		collectionMetadata = Collections.unmodifiableMap( tmpCollectionMetadata );
		for ( Map.Entry> entry : tmpEntityToCollectionRoleMap.entrySet() ) {
			entry.setValue( Collections.unmodifiableSet( entry.getValue() ) );
		}
		collectionRolesByEntityParticipant = Collections.unmodifiableMap( tmpEntityToCollectionRoleMap );

		//Named Queries:
		namedQueries = new HashMap();
		for ( NamedQueryDefinition namedQueryDefinition :  metadata.getNamedQueryDefinitions() ) {
			namedQueries.put( namedQueryDefinition.getName(), namedQueryDefinition );
		}
		namedSqlQueries = new HashMap();
		for ( NamedSQLQueryDefinition namedNativeQueryDefinition: metadata.getNamedNativeQueryDefinitions() ) {
			namedSqlQueries.put( namedNativeQueryDefinition.getName(), namedNativeQueryDefinition );
		}
		sqlResultSetMappings = Collections.unmodifiableMap( new HashMap( metadata.getResultSetMappingDefinitions() ) );
		imports = new HashMap(metadata.getImports());

		// after *all* persisters and named queries are registered
	@Override
		Iterator iter = entityPersisters.values().iterator();
		while ( iter.hasNext() ) {
			final EntityPersister persister = ( ( EntityPersister ) iter.next() );
			persister.postInstantiate();
			registerEntityNameResolvers( persister );

		}
		iter = collectionPersisters.values().iterator();
		while ( iter.hasNext() ) {
			final CollectionPersister persister = ( ( CollectionPersister ) iter.next() );
			persister.postInstantiate();
		}

		//JNDI + Serialization:

		name = settings.getSessionFactoryName();
		try {
			uuid = (String) UUID_GENERATOR.generate(null, null);
		}
		catch (Exception e) {
			throw new AssertionFailure("Could not generate UUID");
		}
		SessionFactoryRegistry.INSTANCE.addSessionFactory(
				uuid, 
				name,
				settings.isSessionFactoryNameAlsoJndiName(),
				this,
				serviceRegistry.getService( JndiService.class )
		);

		LOG.debug("Instantiated session factory");

		if ( settings.isAutoCreateSchema() ) {
			new SchemaExport( metadata )
					.setImportSqlCommandExtractor( serviceRegistry.getService( ImportSqlCommandExtractor.class ) )
					.create( false, true );
		}

		if ( settings.isAutoDropSchema() ) {
			schemaExport = new SchemaExport( metadata )
					.setImportSqlCommandExtractor( serviceRegistry.getService( ImportSqlCommandExtractor.class ) );
		}

		currentSessionContext = buildCurrentSessionContext();

		//checking for named queries
		if ( settings.isNamedQueryStartupCheckingEnabled() ) {
			final Map errors = checkNamedQueries();
			if ( ! errors.isEmpty() ) {
				StringBuilder failingQueries = new StringBuilder( "Errors in named queries: " );
				String sep = "";
				for ( Map.Entry entry : errors.entrySet() ) {
					LOG.namedQueryError( entry.getKey(), entry.getValue() );
					failingQueries.append( entry.getKey() ).append( sep );
					sep = ", ";
				}
				throw new HibernateException( failingQueries.toString() );
			}
		}

		// this needs to happen after persisters are all ready to go...
		this.fetchProfiles = new HashMap();
		for ( org.hibernate.metamodel.spi.binding.FetchProfile mappingProfile : metadata.getFetchProfiles() ) {
			final FetchProfile fetchProfile = new FetchProfile( mappingProfile.getName() );
			for ( org.hibernate.metamodel.spi.binding.FetchProfile.Fetch mappingFetch : mappingProfile.getFetches() ) {
				// resolve the persister owning the fetch
				final String entityName = getImportedClassName( mappingFetch.getEntity() );
				final EntityPersister owner = entityName == null ? null : entityPersisters.get( entityName );
				if ( owner == null ) {
					throw new HibernateException(
							"Unable to resolve entity reference [" + mappingFetch.getEntity()
									+ "] in fetch profile [" + fetchProfile.getName() + "]"
					);
				}

				// validate the specified association fetch
				Type associationType = owner.getPropertyType( mappingFetch.getAssociation() );
				if ( associationType == null || ! associationType.isAssociationType() ) {
					throw new HibernateException( "Fetch profile [" + fetchProfile.getName() + "] specified an invalid association" );
				}

				// resolve the style
				final Fetch.Style fetchStyle = Fetch.Style.parse( mappingFetch.getStyle() );

				// then construct the fetch instance...
				fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
				( ( Loadable ) owner ).registerAffectingFetchProfile( fetchProfile.getName() );
			}
			fetchProfiles.put( fetchProfile.getName(), fetchProfile );
		}

		this.transactionEnvironment = new TransactionEnvironmentImpl( this );
		this.observer.sessionFactoryCreated( this );
		this.jpaMetamodel = jpaMetamodelBuilder.buildMetamodel();
	}

	@SuppressWarnings( {"unchecked"} )
	private static Properties createPropertiesFromMap(Map map) {
		Properties properties = new Properties();
		properties.putAll( map );
		return properties;
	}

	public Session openSession() throws HibernateException {
		return withOptions().openSession();
	}

	public Session openTemporarySession() throws HibernateException {
		return withOptions()
				.autoClose( false )
				.flushBeforeCompletion( false )
				.connectionReleaseMode( ConnectionReleaseMode.AFTER_STATEMENT )
				.openSession();
	}

	public Session getCurrentSession() throws HibernateException {
		if ( currentSessionContext == null ) {
			throw new HibernateException( "No CurrentSessionContext configured!" );
		}
		return currentSessionContext.currentSession();
	}

	@Override
	public SessionBuilderImplementor withOptions() {
		return new SessionBuilderImpl( this );
	}

	@Override
	public StatelessSessionBuilder withStatelessOptions() {
		return new StatelessSessionBuilderImpl( this );
	}

	public StatelessSession openStatelessSession() {
		return withStatelessOptions().openStatelessSession();
	}

	public StatelessSession openStatelessSession(Connection connection) {
		return withStatelessOptions().connection( connection ).openStatelessSession();
	}


	@Override
	public void addObserver(SessionFactoryObserver observer) {
		this.observer.addObserver( observer );
	}

	public TransactionEnvironment getTransactionEnvironment() {
		return transactionEnvironment;
	}

	public Properties getProperties() {
		return properties;
	}

	public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
		return null;
	}

	public TypeResolver getTypeResolver() {
		return typeResolver;
	}

	private void registerEntityNameResolvers(EntityPersister persister) {
		if ( persister.getEntityMetamodel() == null || persister.getEntityMetamodel().getTuplizer() == null ) {
			return;
		}
		registerEntityNameResolvers( persister.getEntityMetamodel().getTuplizer() );
	}

	private void registerEntityNameResolvers(EntityTuplizer tuplizer) {
		EntityNameResolver[] resolvers = tuplizer.getEntityNameResolvers();
		if ( resolvers == null ) {
			return;
		}

		for ( EntityNameResolver resolver : resolvers ) {
			registerEntityNameResolver( resolver );
		}
	}

	private static final Object ENTITY_NAME_RESOLVER_MAP_VALUE = new Object();

	public void registerEntityNameResolver(EntityNameResolver resolver) {
		entityNameResolvers.put( resolver, ENTITY_NAME_RESOLVER_MAP_VALUE );
	}

	public Iterable iterateEntityNameResolvers() {
		return entityNameResolvers.keySet();
	}

	public QueryPlanCache getQueryPlanCache() {
		return queryPlanCache;
	}

	@SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"})
	private Map checkNamedQueries() throws HibernateException {
		Map errors = new HashMap();

		// Check named HQL queries
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf( "Checking %s named HQL queries", namedQueries.size() );
		}
		Iterator itr = namedQueries.entrySet().iterator();
		while ( itr.hasNext() ) {
			final Map.Entry entry = ( Map.Entry ) itr.next();
			final String queryName = ( String ) entry.getKey();
			final NamedQueryDefinition qd = ( NamedQueryDefinition ) entry.getValue();
			// this will throw an error if there's something wrong.
			try {
				LOG.debugf( "Checking named query: %s", queryName );
				//TODO: BUG! this currently fails for named queries for non-POJO entities
				queryPlanCache.getHQLQueryPlan( qd.getQueryString(), false, Collections.EMPTY_MAP );
			}
			catch ( QueryException e ) {
				errors.put( queryName, e );
			}
			catch ( MappingException e ) {
				errors.put( queryName, e );
			}


		}
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf( "Checking %s named SQL queries", namedSqlQueries.size() );
		}
		itr = namedSqlQueries.entrySet().iterator();
		while ( itr.hasNext() ) {
			final Map.Entry entry = ( Map.Entry ) itr.next();
			final String queryName = ( String ) entry.getKey();
			final NamedSQLQueryDefinition qd = ( NamedSQLQueryDefinition ) entry.getValue();
			// this will throw an error if there's something wrong.
			try {
				LOG.debugf( "Checking named SQL query: %s", queryName );
				// TODO : would be really nice to cache the spec on the query-def so as to not have to re-calc the hash;
				// currently not doable though because of the resultset-ref stuff...
				NativeSQLQuerySpecification spec;
				if ( qd.getResultSetRef() != null ) {
					ResultSetMappingDefinition definition = sqlResultSetMappings.get( qd.getResultSetRef() );
					if ( definition == null ) {
						throw new MappingException( "Unable to find resultset-ref definition: " + qd.getResultSetRef() );
					}
					spec = new NativeSQLQuerySpecification(
							qd.getQueryString(),
					        definition.getQueryReturns(),
					        qd.getQuerySpaces()
					);
				}
				else {
					spec =  new NativeSQLQuerySpecification(
							qd.getQueryString(),
					        qd.getQueryReturns(),
					        qd.getQuerySpaces()
					);
				}
				queryPlanCache.getNativeSQLQueryPlan( spec );
			}
			catch ( QueryException e ) {
				errors.put( queryName, e );
			}
			catch ( MappingException e ) {
				errors.put( queryName, e );
			}

		}

		return errors;
	}

	public EntityPersister getEntityPersister(String entityName) throws MappingException {
		EntityPersister result = entityPersisters.get(entityName);
		if ( result == null ) {
			throw new MappingException( "Unknown entity: " + entityName );
		}
		return result;
	}

	@Override
	public Map getCollectionPersisters() {
		return collectionPersisters;
	}

	@Override
	public Map getEntityPersisters() {
		return entityPersisters;
	}

	public CollectionPersister getCollectionPersister(String role) throws MappingException {
		CollectionPersister result = collectionPersisters.get(role);
		if ( result == null ) {
			throw new MappingException( "Unknown collection role: " + role );
		}
		return result;
	}

	public Settings getSettings() {
		return settings;
	}

	@Override
	public SessionFactoryOptions getSessionFactoryOptions() {
		return sessionFactoryOptions;
	}

	public JdbcServices getJdbcServices() {
		return jdbcServices;
	}

	public Dialect getDialect() {
		if ( serviceRegistry == null ) {
			throw new IllegalStateException( "Cannot determine dialect because serviceRegistry is null." );
		}
		return dialect;
	}

	public Interceptor getInterceptor() {
		return sessionFactoryOptions.getInterceptor();
	}

	public SQLExceptionConverter getSQLExceptionConverter() {
		return getSQLExceptionHelper().getSqlExceptionConverter();
	}

	public SqlExceptionHelper getSQLExceptionHelper() {
		return getJdbcServices().getSqlExceptionHelper();
	}

	public Set getCollectionRolesByEntityParticipant(String entityName) {
		return collectionRolesByEntityParticipant.get( entityName );
	}

	@Override
	public Reference getReference() {
		// from javax.naming.Referenceable
        LOG.debug( "Returning a Reference to the SessionFactory" );
		return new Reference(
				SessionFactoryImpl.class.getName(),
				new StringRefAddr("uuid", uuid),
				SessionFactoryRegistry.ObjectFactoryImpl.class.getName(),
				null
		);
	}

	@Override
	public void registerNamedQueryDefinition(String name, NamedQueryDefinition definition) {
		if ( NamedSQLQueryDefinition.class.isInstance( definition ) ) {
			throw new IllegalArgumentException( "NamedSQLQueryDefinition instance incorrectly passed to registerNamedQueryDefinition" );
		}
		final NamedQueryDefinition previous = namedQueries.put( name, definition );
		if ( previous != null ) {
			LOG.debugf(
					"registering named query definition [%s] overriding previously registered definition [%s]",
					name,
					previous
			);
		}
	}

	@Override
	public NamedQueryDefinition getNamedQuery(String queryName) {
		return namedQueries.get( queryName );
	}

	@Override
	public void registerNamedSQLQueryDefinition(String name, NamedSQLQueryDefinition definition) {
		final NamedSQLQueryDefinition previous = namedSqlQueries.put( name, definition );
		if ( previous != null ) {
			LOG.debugf(
					"registering named SQL query definition [%s] overriding previously registered definition [%s]",
					name,
					previous
			);
		}
	}

	@Override
	public NamedSQLQueryDefinition getNamedSQLQuery(String queryName) {
		return namedSqlQueries.get( queryName );
	}

	@Override
	public ResultSetMappingDefinition getResultSetMapping(String resultSetName) {
		return sqlResultSetMappings.get( resultSetName );
	}

	@Override
	public Type getIdentifierType(String className) throws MappingException {
		return getEntityPersister(className).getIdentifierType();
	}

	@Override
	public String getIdentifierPropertyName(String className) throws MappingException {
		return getEntityPersister(className).getIdentifierPropertyName();
	}

	@Override
	public Type[] getReturnTypes(String queryString) throws HibernateException {
		return queryPlanCache.getHQLQueryPlan( queryString, false, Collections.EMPTY_MAP )
				.getReturnMetadata()
				.getReturnTypes();
	}

	public String[] getReturnAliases(String queryString) throws HibernateException {
		return queryPlanCache.getHQLQueryPlan( queryString, false, Collections.EMPTY_MAP )
				.getReturnMetadata()
				.getReturnAliases();
	}

	public ClassMetadata getClassMetadata(Class persistentClass) throws HibernateException {
		return getClassMetadata( persistentClass.getName() );
	}

	public CollectionMetadata getCollectionMetadata(String roleName) throws HibernateException {
		return collectionMetadata.get( roleName );
	}

	public ClassMetadata getClassMetadata(String entityName) throws HibernateException {
		return classMetadata.get( entityName );
	}

	/**
	 * Given the name of an entity class, determine all the class and interface names by which it can be
	 * referenced in an HQL query.
	 *
     * @param className The name of the entity class
	 *
	 * @return the names of all persistent (mapped) classes that extend or implement the
	 *     given class or interface, accounting for implicit/explicit polymorphism settings
	 *     and excluding mapped subclasses/joined-subclasses of other classes in the result.
	 * @throws MappingException
	 */
	public String[] getImplementors(String className) throws MappingException {

		final Class clazz;
		try {
			clazz = serviceRegistry.getService( ClassLoaderService.class ).classForName( className );
		}
		catch (ClassLoadingException cnfe) {
			return new String[] { className }; //for a dynamic-class
		}

		ArrayList results = new ArrayList();
		for ( EntityPersister checkPersister : entityPersisters.values() ) {
			if ( ! Queryable.class.isInstance( checkPersister ) ) {
				continue;
			}
			final Queryable checkQueryable = Queryable.class.cast( checkPersister );
			final String checkQueryableEntityName = checkQueryable.getEntityName();
			final boolean isMappedClass = className.equals( checkQueryableEntityName );
			if ( checkQueryable.isExplicitPolymorphism() ) {
				if ( isMappedClass ) {
					return new String[] { className }; //NOTE EARLY EXIT
				}
			}
			else {
				if ( isMappedClass ) {
					results.add( checkQueryableEntityName );
				}
				else {
					final Class mappedClass = checkQueryable.getMappedClass();
					if ( mappedClass != null && clazz.isAssignableFrom( mappedClass ) ) {
						final boolean assignableSuperclass;
						if ( checkQueryable.isInherited() ) {
							Class mappedSuperclass = getEntityPersister( checkQueryable.getMappedSuperclass() ).getMappedClass();
							assignableSuperclass = clazz.isAssignableFrom( mappedSuperclass );
						}
						else {
							assignableSuperclass = false;
						}
						if ( !assignableSuperclass ) {
							results.add( checkQueryableEntityName );
						}
					}
				}
			}
		}
		return results.toArray( new String[results.size()] );
	}

	public String getImportedClassName(String className) {
		String result = imports.get(className);
		if (result==null) {
			try {
				serviceRegistry.getService( ClassLoaderService.class ).classForName( className );
				return className;
			}
			catch (ClassLoadingException cnfe) {
				return null;
			}
		}
		else {
			return result;
		}
	}

	public Map getAllClassMetadata() throws HibernateException {
		return classMetadata;
	}

	public Map getAllCollectionMetadata() throws HibernateException {
		return collectionMetadata;
	}

	public Type getReferencedPropertyType(String className, String propertyName)
		throws MappingException {
		return getEntityPersister( className ).getPropertyType( propertyName );
	}

	public ConnectionProvider getConnectionProvider() {
		return jdbcServices.getConnectionProvider();
	}

	/**
	 * Closes the session factory, releasing all held resources.
	 *
	 * 
    *
  1. cleans up used cache regions and "stops" the cache provider. *
  2. close the JDBC connection *
  3. remove the JNDI binding *
* * Note: Be aware that the sessionFactory instance still can * be a "heavy" object memory wise after close() has been called. Thus * it is important to not keep referencing the instance to let the garbage * collector release the memory. * @throws HibernateException */ public void close() throws HibernateException { if ( isClosed ) { LOG.trace( "Already closed" ); return; } LOG.closing(); isClosed = true; settings.getMultiTableBulkIdStrategy().release( jdbcServices, buildLocalConnectionAccess() ); Iterator iter = entityPersisters.values().iterator(); while ( iter.hasNext() ) { EntityPersister p = (EntityPersister) iter.next(); if ( p.hasCache() ) { p.getCacheAccessStrategy().getRegion().destroy(); } } iter = collectionPersisters.values().iterator(); while ( iter.hasNext() ) { CollectionPersister p = (CollectionPersister) iter.next(); if ( p.hasCache() ) { p.getCacheAccessStrategy().getRegion().destroy(); } } // cacheAccess.stop(); queryPlanCache.cleanup(); if ( settings.isAutoDropSchema() ) { schemaExport.drop( false, true ); } SessionFactoryRegistry.INSTANCE.removeSessionFactory( uuid, name, settings.isSessionFactoryNameAlsoJndiName(), serviceRegistry.getService( JndiService.class ) ); observer.sessionFactoryClosed( this ); serviceRegistry.destroy(); } public Cache getCache() { return cacheAccess; } public void evictEntity(String entityName, Serializable id) throws HibernateException { getCache().evictEntity( entityName, id ); } public void evictEntity(String entityName) throws HibernateException { getCache().evictEntityRegion( entityName ); } public void evict(Class persistentClass, Serializable id) throws HibernateException { getCache().evictEntity( persistentClass, id ); } public void evict(Class persistentClass) throws HibernateException { getCache().evictEntityRegion( persistentClass ); } public void evictCollection(String roleName, Serializable id) throws HibernateException { getCache().evictCollection( roleName, id ); } public void evictCollection(String roleName) throws HibernateException { getCache().evictCollectionRegion( roleName ); } public void evictQueries() throws HibernateException { cacheAccess.evictQueries(); } public void evictQueries(String regionName) throws HibernateException { getCache().evictQueryRegion( regionName ); } public UpdateTimestampsCache getUpdateTimestampsCache() { return cacheAccess.getUpdateTimestampsCache(); } public QueryCache getQueryCache() { return cacheAccess.getQueryCache(); } public QueryCache getQueryCache(String regionName) throws HibernateException { return cacheAccess.getQueryCache( regionName ); } public Region getSecondLevelCacheRegion(String regionName) { return cacheAccess.getSecondLevelCacheRegion( regionName ); } public Region getNaturalIdCacheRegion(String regionName) { return cacheAccess.getNaturalIdCacheRegion( regionName ); } @SuppressWarnings( {"unchecked"}) public Map getAllSecondLevelCacheRegions() { return cacheAccess.getAllSecondLevelCacheRegions(); } public boolean isClosed() { return isClosed; } public Statistics getStatistics() { return getStatisticsImplementor(); } public StatisticsImplementor getStatisticsImplementor() { return serviceRegistry.getService( StatisticsImplementor.class ); } public FilterDefinition getFilterDefinition(String filterName) throws HibernateException { FilterDefinition def = filters.get( filterName ); if ( def == null ) { throw new HibernateException( "No such filter configured [" + filterName + "]" ); } return def; } public boolean containsFetchProfileDefinition(String name) { return fetchProfiles.containsKey( name ); } public Set getDefinedFilterNames() { return filters.keySet(); } public IdentifierGenerator getIdentifierGenerator(String rootEntityName) { return identifierGenerators.get(rootEntityName); } private org.hibernate.engine.transaction.spi.TransactionFactory transactionFactory() { return serviceRegistry.getService( org.hibernate.engine.transaction.spi.TransactionFactory.class ); } private boolean canAccessTransactionManager() { try { return serviceRegistry.getService( JtaPlatform.class ).retrieveTransactionManager() != null; } catch (Exception e) { return false; } } private CurrentSessionContext buildCurrentSessionContext() { String impl = properties.getProperty( Environment.CURRENT_SESSION_CONTEXT_CLASS ); // for backward-compatibility if ( impl == null ) { if ( canAccessTransactionManager() ) { impl = "jta"; } else { return null; } } if ( "jta".equals( impl ) ) { if ( ! transactionFactory().compatibleWithJtaSynchronization() ) { LOG.autoFlushWillNotWork(); } return new JTASessionContext( this ); } else if ( "thread".equals( impl ) ) { return new ThreadLocalSessionContext( this ); } else if ( "managed".equals( impl ) ) { return new ManagedSessionContext( this ); } else { try { Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl ); return ( CurrentSessionContext ) implClass .getConstructor( new Class[] { SessionFactoryImplementor.class } ) .newInstance( this ); } catch( Throwable t ) { LOG.unableToConstructCurrentSessionContext( impl, t ); return null; } } } public ServiceRegistryImplementor getServiceRegistry() { return serviceRegistry; } @Override public EntityNotFoundDelegate getEntityNotFoundDelegate() { return sessionFactoryOptions.getEntityNotFoundDelegate(); } public SQLFunctionRegistry getSqlFunctionRegistry() { return sqlFunctionRegistry; } public FetchProfile getFetchProfile(String name) { return fetchProfiles.get( name ); } public TypeHelper getTypeHelper() { return typeHelper; } static class SessionBuilderImpl implements SessionBuilderImplementor { private final SessionFactoryImpl sessionFactory; private SessionOwner sessionOwner; private Interceptor interceptor; private Connection connection; private ConnectionReleaseMode connectionReleaseMode; private boolean autoClose; private boolean autoJoinTransactions = true; private boolean flushBeforeCompletion; private String tenantIdentifier; SessionBuilderImpl(SessionFactoryImpl sessionFactory) { this.sessionFactory = sessionFactory; this.sessionOwner = null; final Settings settings = sessionFactory.settings; // set up default builder values... this.interceptor = sessionFactory.getInterceptor(); this.connectionReleaseMode = settings.getConnectionReleaseMode(); this.autoClose = settings.isAutoCloseSessionEnabled(); this.flushBeforeCompletion = settings.isFlushBeforeCompletionEnabled(); if ( sessionFactory.getCurrentTenantIdentifierResolver() != null ) { tenantIdentifier = sessionFactory.getCurrentTenantIdentifierResolver().resolveCurrentTenantIdentifier(); } } protected TransactionCoordinatorImpl getTransactionCoordinator() { return null; } @Override public Session openSession() { return new SessionImpl( connection, sessionFactory, sessionOwner, getTransactionCoordinator(), autoJoinTransactions, sessionFactory.getServiceRegistry().getService( RegionFactory.class ).nextTimestamp(), interceptor, flushBeforeCompletion, autoClose, connectionReleaseMode, tenantIdentifier ); } @Override public SessionBuilder owner(SessionOwner sessionOwner) { this.sessionOwner = sessionOwner; return this; } @Override public SessionBuilder interceptor(Interceptor interceptor) { this.interceptor = interceptor; return this; } @Override public SessionBuilder noInterceptor() { this.interceptor = EmptyInterceptor.INSTANCE; return this; } @Override public SessionBuilder connection(Connection connection) { this.connection = connection; return this; } @Override public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode) { this.connectionReleaseMode = connectionReleaseMode; return this; } @Override public SessionBuilder autoJoinTransactions(boolean autoJoinTransactions) { this.autoJoinTransactions = autoJoinTransactions; return this; } @Override public SessionBuilder autoClose(boolean autoClose) { this.autoClose = autoClose; return this; } @Override public SessionBuilder flushBeforeCompletion(boolean flushBeforeCompletion) { this.flushBeforeCompletion = flushBeforeCompletion; return this; } @Override public SessionBuilder tenantIdentifier(String tenantIdentifier) { this.tenantIdentifier = tenantIdentifier; return this; } } public static class StatelessSessionBuilderImpl implements StatelessSessionBuilder { private final SessionFactoryImpl sessionFactory; private Connection connection; private String tenantIdentifier; public StatelessSessionBuilderImpl(SessionFactoryImpl sessionFactory) { this.sessionFactory = sessionFactory; } @Override public StatelessSession openStatelessSession() { return new StatelessSessionImpl( connection, tenantIdentifier, sessionFactory ); } @Override public StatelessSessionBuilder connection(Connection connection) { this.connection = connection; return this; } @Override public StatelessSessionBuilder tenantIdentifier(String tenantIdentifier) { this.tenantIdentifier = tenantIdentifier; return this; } } @Override public CustomEntityDirtinessStrategy getCustomEntityDirtinessStrategy() { return sessionFactoryOptions.getCustomEntityDirtinessStrategy(); } @Override public CurrentTenantIdentifierResolver getCurrentTenantIdentifierResolver() { return sessionFactoryOptions.getCurrentTenantIdentifierResolver(); } @Override public Metamodel getJpaMetamodel() { return jpaMetamodel; } // Serialization handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Custom serialization hook defined by Java spec. Used when the factory is directly serialized * * @param out The stream into which the object is being serialized. * * @throws IOException Can be thrown by the stream */ private void writeObject(ObjectOutputStream out) throws IOException { LOG.debugf( "Serializing: %s", uuid ); out.defaultWriteObject(); LOG.trace( "Serialized" ); } /** * Custom serialization hook defined by Java spec. Used when the factory is directly deserialized * * @param in The stream from which the object is being deserialized. * * @throws IOException Can be thrown by the stream * @throws ClassNotFoundException Again, can be thrown by the stream */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { LOG.trace( "Deserializing" ); in.defaultReadObject(); LOG.debugf( "Deserialized: %s", uuid ); } /** * Custom serialization hook defined by Java spec. Used when the factory is directly deserialized. * Here we resolve the uuid/name read from the stream previously to resolve the SessionFactory * instance to use based on the registrations with the {@link SessionFactoryRegistry} * * @return The resolved factory to use. * * @throws InvalidObjectException Thrown if we could not resolve the factory by uuid/name. */ private Object readResolve() throws InvalidObjectException { LOG.trace( "Resolving serialized SessionFactory" ); return locateSessionFactoryOnDeserialization( uuid, name ); } private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, String name) throws InvalidObjectException{ final SessionFactory uuidResult = SessionFactoryRegistry.INSTANCE.getSessionFactory( uuid ); if ( uuidResult != null ) { LOG.debugf( "Resolved SessionFactory by UUID [%s]", uuid ); return uuidResult; } // in case we were deserialized in a different JVM, look for an instance with the same name // (provided we were given a name) if ( name != null ) { final SessionFactory namedResult = SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( name ); if ( namedResult != null ) { LOG.debugf( "Resolved SessionFactory by name [%s]", name ); return namedResult; } } throw new InvalidObjectException( "Could not find a SessionFactory [uuid=" + uuid + ",name=" + name + "]" ); } /** * Custom serialization hook used during Session serialization. * * @param oos The stream to which to write the factory * @throws IOException Indicates problems writing out the serial data stream */ void serialize(ObjectOutputStream oos) throws IOException { oos.writeUTF( uuid ); oos.writeBoolean( name != null ); if ( name != null ) { oos.writeUTF( name ); } } /** * Custom deserialization hook used during Session deserialization. * * @param ois The stream from which to "read" the factory * @return The deserialized factory * @throws IOException indicates problems reading back serial data stream * @throws ClassNotFoundException indicates problems reading back serial data stream */ static SessionFactoryImpl deserialize(ObjectInputStream ois) throws IOException, ClassNotFoundException { LOG.trace( "Deserializing SessionFactory from Session" ); final String uuid = ois.readUTF(); boolean isNamed = ois.readBoolean(); final String name = isNamed ? ois.readUTF() : null; return (SessionFactoryImpl) locateSessionFactoryOnDeserialization( uuid, name ); } }
File
SessionFactoryImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
If statement
Method declaration
Method invocation
Method signature
Return statement
Variable
Chunk
Conflicting content
 */
package org.hibernate.mapping;

<<<<<<< HEAD
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
=======
import javax.persistence.AttributeConverter;
import java.lang.annotation.Annotation;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import java.lang.reflect.TypeVariable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
Solution content
 */
package org.hibernate.mapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.TypeVariable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
File
SimpleValue.java
Developer's decision
Combination
Kind of conflict
Import
Chunk
Conflicting content
import java.util.HashMap;
import java.util.Map;

<<<<<<< HEAD:hibernate-core/src/main/java/org/hibernate/metamodel/internal/source/annotations/attribute/type/LobTypeResolver.java
import org.hibernate.metamodel.internal.source.annotations.attribute.MappedAttribute;
import org.hibernate.metamodel.internal.source.annotations.util.JPADotNames;
import org.hibernate.metamodel.internal.source.annotations.util.JandexHelper;
=======
import org.hibernate.AssertionFailure;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.metamodel.source.annotations.attribute.MappedAttribute;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454:hibernate-core/src/main/java/org/hibernate/metamodel/source/annotations/attribute/type/LobTypeResolver.java
import org.hibernate.type.CharacterArrayClobType;
import org.hibernate.type.PrimitiveCharacterArrayClobType;
import org.hibernate.type.SerializableToBlobType;
Solution content
import java.util.HashMap;
import java.util.Map;

import org.hibernate.metamodel.internal.source.annotations.attribute.MappedAttribute;
import org.hibernate.metamodel.internal.source.annotations.util.JPADotNames;
import org.hibernate.metamodel.internal.source.annotations.util.JandexHelper;
import org.hibernate.type.CharacterArrayClobType;
import org.hibernate.type.PrimitiveCharacterArrayClobType;
import org.hibernate.type.SerializableToBlobType;
File
LobTypeResolver.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
			propertySelectable[i] = !attributeBinding.isBackRef();

<<<<<<< HEAD
			propertyUniqueness[i] = attributeBinding.isAlternateUniqueKey();
=======
			// TODO: fix this when backrefs are working
			//propertySelectable[i] = singularAttributeBinding.isBackRef();
			propertySelectable[i] = true;

			propertyUniqueness[i] = singularAttributeBinding.isAlternateUniqueKey();
			
			// TODO: Does this need AttributeBindings wired into lobProperties?  Currently in Property only.
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

			i++;
Solution content
			propertySelectable[i] = !attributeBinding.isBackRef();

			propertyUniqueness[i] = attributeBinding.isAlternateUniqueKey();

			i++;
File
AbstractEntityPersister.java
Developer's decision
Version 1
Kind of conflict
Array access
Comment
Method invocation
Chunk
Conflicting content
import java.sql.SQLException;
import java.util.Map;

<<<<<<< HEAD
=======
import org.dom4j.Node;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
Solution content
import java.sql.SQLException;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
File
AbstractStandardBasicType.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.MarkerObject;
import org.hibernate.internal.util.collections.ArrayHelper;
<<<<<<< HEAD
import org.hibernate.metamodel.spi.relational.Size;
=======
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.relational.Size;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.EntityPersister;
Solution content
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.MarkerObject;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.spi.relational.Size;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.EntityPersister;
File
CollectionType.java
Developer's decision
Combination
Kind of conflict
Import
Chunk
Conflicting content
 * @author Gavin King
 * @author Steve Ebersole
 */
<<<<<<< HEAD
public class CustomType extends AbstractType implements IdentifierType, DiscriminatorType, VersionType, BasicType, StringRepresentableType {
=======
public class CustomType
		extends AbstractType
		implements IdentifierType, DiscriminatorType, VersionType, BasicType, StringRepresentableType {

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	private final UserType userType;
	private final String name;
	private final int[] types;
Solution content
 * @author Gavin King
 * @author Steve Ebersole
 */
public class CustomType
		extends AbstractType
		implements IdentifierType, DiscriminatorType, VersionType, BasicType, StringRepresentableType {

	private final UserType userType;
	private final String name;
	private final int[] types;
File
CustomType.java
Developer's decision
Version 1
Kind of conflict
Class signature
Chunk
Conflicting content
		userType.nullSafeSet( st, value, index, session );
	}

<<<<<<< HEAD
=======
	@SuppressWarnings({ "UnusedDeclaration" })
	public String toXMLString(Object value, SessionFactoryImplementor factory) {
		return toString( value );
	}

	@SuppressWarnings({ "UnusedDeclaration" })
	public Object fromXMLString(String xml, Mapping factory) {
		return fromStringValue( xml );
	}

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	public String getName() {
		return name;
	}
Solution content
		userType.nullSafeSet( st, value, index, session );
	}

	public String getName() {
		return name;
	}
File
CustomType.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
		if ( StringRepresentableType.class.isInstance( userType ) ) {
			return ( (StringRepresentableType) userType ).toString( value );
		}
<<<<<<< HEAD
		else {
			if ( value == null ) {
				return null;
			}
			else {
				return value.toString();
			}
		}
=======
		if ( value == null ) {
			return null;
		}
		if ( EnhancedUserType.class.isInstance( userType ) ) {
			//noinspection deprecation
			return ( (EnhancedUserType) userType ).toXMLString( value );
		}
		return value.toString();
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	}

	@Override
Solution content
		if ( StringRepresentableType.class.isInstance( userType ) ) {
			return ( (StringRepresentableType) userType ).toString( value );
		}
		else {
			if ( value == null ) {
				return null;
			}
			else {
				return value.toString();
			}
		}
	}

	@Override
File
CustomType.java
Developer's decision
Version 1
Kind of conflict
If statement
Method invocation
Return statement
Chunk
Conflicting content
		if ( StringRepresentableType.class.isInstance( userType ) ) {
			return ( (StringRepresentableType) userType ).fromStringValue( string );
		}
<<<<<<< HEAD
		else {
			throw new HibernateException(
					String.format(
							"Custom UserType class [%s] did not implement %s, cannot process #fromStringValue call",
							name,
							StringRepresentableType.class
					)
			);
		}
=======
		if ( EnhancedUserType.class.isInstance( userType ) ) {
			//noinspection deprecation
			return ( (EnhancedUserType) userType ).fromXMLString( string );
		}
		throw new HibernateException(
				String.format(
						"Could not process #fromStringValue, UserType class [%s] did not implement %s or %s",
						name,
						StringRepresentableType.class.getName(),
						EnhancedUserType.class.getName()
				)
		);
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	}
}
Solution content
		if ( StringRepresentableType.class.isInstance( userType ) ) {
			return ( (StringRepresentableType) userType ).fromStringValue( string );
		}
		else {
			throw new HibernateException(
					String.format(
							"Custom UserType class [%s] did not implement %s, cannot process #fromStringValue call",
							name,
							StringRepresentableType.class
					)
			);
		}
	}
}
File
CustomType.java
Developer's decision
Version 1
Kind of conflict
If statement
Throw statement
Chunk
Conflicting content
	
	private static final long serialVersionUID = 1L;

<<<<<<< HEAD
	public Object get(ResultSet rs, String name) throws SQLException {
		Blob blob = rs.getBlob( name );
		if ( rs.wasNull() ) return null;
		int length = (int) blob.length();
		byte[] primaryResult = blob.getBytes( 1, length );
		return fromBytes( primaryResult );
	}

	private static byte[] toBytes(Object object) throws SerializationException {
		return SerializationHelper.serialize( (Serializable) object );
	}

	private Object fromBytes(byte[] bytes) throws SerializationException {
		return SerializationHelper.deserialize( bytes, getReturnedClass().getClassLoader() );
	}

	public void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException {
		if ( value != null ) {
			byte[] toSet;
			toSet = toBytes( value );
			if ( session.getFactory().getDialect().useInputStreamToInsertBlob() ) {
				st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length );
			}
			else {
				st.setBlob( index, Hibernate.getLobCreator( session ).createBlob( toSet ) );
			}
		}
		else {
			st.setNull( index, sqlTypes( null )[0] );
		}
	}

	public String toLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException {
		return type.toLoggableString( value, factory );
	}

	public Object deepCopy(Object value, SessionFactoryImplementor factory)
			throws HibernateException {
		return type.deepCopy( value, null );
	}

	public boolean isMutable() {
		return type.isMutable();
	}

	public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache)
			throws HibernateException {
		return type.replace( original, target, session, owner, copyCache );
=======
	/**
	 * @param sqlTypeDescriptor
	 * @param javaTypeDescriptor
	 */
	public SerializableToBlobType() {
		super( BlobTypeDescriptor.DEFAULT, new SerializableTypeDescriptor( Serializable.class ) );
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	}

	/**
Solution content
	
	private static final long serialVersionUID = 1L;

	/**
	 * @param sqlTypeDescriptor
	 * @param javaTypeDescriptor
	 */
	public SerializableToBlobType() {
		super( BlobTypeDescriptor.DEFAULT, new SerializableTypeDescriptor( Serializable.class ) );
	}

	/**
File
SerializableToBlobType.java
Developer's decision
Version 2
Kind of conflict
Comment
Method declaration
Method invocation
Method signature
Return statement
Chunk
Conflicting content
package org.hibernate.usertype;

/**
<<<<<<< HEAD
 * A custom type that may function as an identifier or discriminator type.
=======
 * A custom type that may function as an identifier or discriminator type
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
 * 
 * @author Gavin King
 *
Solution content
package org.hibernate.usertype;

/**
 * A custom type that may function as an identifier or discriminator type.
 * 
 * @author Gavin King
 *
File
EnhancedUserType.java
Developer's decision
Version 1
Kind of conflict
Comment
Chunk
Conflicting content
	 * Return an SQL literal representation of the value
	 */
	public String objectToSQLString(Object value);
<<<<<<< HEAD
=======
	
	/**
	 * Return a string representation of this value, as it should appear in an XML document
	 *
	 * @deprecated To be removed in 5.  Implement {@link org.hibernate.type.StringRepresentableType#toString(Object)}
	 * instead.  See HHH-7776 for details
	 */
	@Deprecated
	public String toXMLString(Object value);

	/**
	 * Parse a string representation of this value, as it appears in an XML document
	 *
	 * @deprecated To be removed in 5.  Implement
	 * {@link org.hibernate.type.StringRepresentableType#fromStringValue(String)} instead.
	 * See HHH-7776 for details
	 */
	@Deprecated
	public Object fromXMLString(String xmlValue);
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
}
Solution content
	 * Return an SQL literal representation of the value
	 */
	public String objectToSQLString(Object value);
}
File
EnhancedUserType.java
Developer's decision
Version 1
Kind of conflict
Annotation
Comment
Method interface
Chunk
Conflicting content
<<<<<<< HEAD
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010 by Red Hat Inc and/or its affiliates or by
 * third-party contributors as indicated by either @author tags or express
 * copyright attribution statements applied by the authors.  All
 * third-party contributions are distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
/**
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */

package org.hibernate.test.annotations.beanvalidation;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;

/**
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 */
@Entity
public class Tv {

	@Id
	@Size(max = 2)
	public String serial;

	@Length(max = 5)
	public String model;

	public int size;

	@Size(max = 2)
	public String name;

	@Future
	public Date expDate;

	@Size(min = 0)
	public String description;

	@Min(1000)
	public BigInteger lifetime;

	@NotNull
	@Valid
	public Tuner tuner;

	@Valid
	public Recorder recorder;

	@Embeddable
	public static class Tuner {
		@NotNull
		public String frequency;
	}

	@Embeddable
	public static class Recorder {
		@NotNull
		public BigDecimal time;
	}
}
=======
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010 by Red Hat Inc and/or its affiliates or by
 * third-party contributors as indicated by either @author tags or express
 * copyright attribution statements applied by the authors.  All
 * third-party contributions are distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */

package org.hibernate.test.annotations.beanvalidation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;

 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 */
@Entity
public class Tv {

	@Id
	@Size(max = 2)
	public String serial;

	@Length(max = 5)
	public String model;

	public int size;

	@Size(max = 2)
	public String name;

	@Future
	public Date expDate;

	@Size(min = 0)
	public String description;

	@Min(1000)
	public BigInteger lifetime;

	@NotNull
	@Valid
	public Tuner tuner;

	@Valid
	public Recorder recorder;

	@Embeddable
	public static class Tuner {
		@NotNull
		public String frequency;
	}

	@Embeddable
	public static class Recorder {
		@NotNull
        @Column(name = "`time`")
		public BigDecimal time;
	}
}
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
Solution content
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010 by Red Hat Inc and/or its affiliates or by
 * third-party contributors as indicated by either @author tags or express
 * copyright attribution statements applied by the authors.  All
 * third-party contributions are distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */

package org.hibernate.test.annotations.beanvalidation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;

/**
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 */
@Entity
public class Tv {

	@Id
	@Size(max = 2)
	public String serial;

	@Length(max = 5)
	public String model;

	public int size;

	@Size(max = 2)
	public String name;

	@Future
	public Date expDate;

	@Size(min = 0)
	public String description;

	@Min(1000)
	public BigInteger lifetime;

	@NotNull
	@Valid
	public Tuner tuner;

	@Valid
	public Recorder recorder;

	@Embeddable
	public static class Tuner {
		@NotNull
		public String frequency;
	}

	@Embeddable
	public static class Recorder {
		@NotNull
        @Column(name = "`time`")
		public BigDecimal time;
	}
}
File
Tv.java
Developer's decision
Version 2
Kind of conflict
Annotation
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.annotations.filter.subclass.SubClassTest;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;

@FailureExpectedWithNewMetamodel
=======
import org.junit.Test;
import org.hibernate.testing.*;

@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class JoinedSubClassTest extends SubClassTest{

	@Override
Solution content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.annotations.filter.subclass.SubClassTest;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.SkipForDialect;
import org.junit.Test;

@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class JoinedSubClassTest extends SubClassTest{

	@Override
File
JoinedSubClassTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Import
Chunk
Conflicting content
import org.hibernate.Session;
import org.hibernate.Transaction;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======

import org.hibernate.testing.TestForIssue;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;

import static org.junit.Assert.assertEquals;
Solution content
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
File
IdManyToOneTest.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.loader.BatchFetchStyle;

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;

import static org.junit.Assert.assertEquals;
Solution content
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.loader.BatchFetchStyle;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
File
BatchFetchTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
/**
 * @author Steve Ebersole
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class JoinedFilteredBulkManipulationTest extends BaseCoreFunctionalTestCase {
	@Override
	public String[] getMappings() {
Solution content
/**
 * @author Steve Ebersole
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class JoinedFilteredBulkManipulationTest extends BaseCoreFunctionalTestCase {
	@Override
	public String[] getMappings() {
File
JoinedFilteredBulkManipulationTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
 *
 * @author Steve
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
	private static final Logger log = Logger.getLogger( ASTParserLoadingTest.class );
Solution content
 *
 * @author Steve
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
	private static final Logger log = Logger.getLogger( ASTParserLoadingTest.class );
File
ASTParserLoadingTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
/**
 * @author Steve Ebersole
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
	@Override
	protected Class[] getAnnotatedClasses() {
Solution content
/**
 * @author Steve Ebersole
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
	@Override
	protected Class[] getAnnotatedClasses() {
File
JoinedSubclassBulkManipTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.testing.SkipForDialect;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

/**
 * @author Gail Badner
Solution content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.SkipForDialect;

/**
 * @author Gail Badner
File
EntityWithInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
/**
 * @author Gail Badner
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class EntityWithInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
Solution content
/**
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class EntityWithInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
File
EntityWithInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
/**
 * @author Gail Badner
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class VersionedEntityWithInverseOneToManyJoinFailureExpectedTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
Solution content
/**
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class VersionedEntityWithInverseOneToManyJoinFailureExpectedTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
File
VersionedEntityWithInverseOneToManyJoinFailureExpectedTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.testing.SkipForDialect;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.TestForIssue;

Solution content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;

File
VersionedEntityWithInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
	public String[] getMappings() {
 * @author Gail Badner
 */
@TestForIssue( jiraKey = "HHH-4992" )
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class VersionedEntityWithInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
Solution content
 * @author Gail Badner
 */
@TestForIssue( jiraKey = "HHH-4992" )
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class VersionedEntityWithInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
File
VersionedEntityWithInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.testing.SkipForDialect;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

/**
 * @author Gail Badner
Solution content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.SkipForDialect;

/**
 * @author Gail Badner
File
EntityWithNonInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
/**
 * @author Gail Badner
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class EntityWithNonInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
Solution content
/**
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class EntityWithNonInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
File
EntityWithNonInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.testing.SkipForDialect;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

/**
 * @author Gail Badner
Solution content
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.test.immutable.entitywithmutablecollection.AbstractEntityWithOneToManyTest;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.SkipForDialect;

/**
 * @author Gail Badner
File
VersionedEntityWithNonInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
/**
 * @author Gail Badner
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class VersionedEntityWithNonInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
Solution content
/**
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class VersionedEntityWithNonInverseOneToManyJoinTest extends AbstractEntityWithOneToManyTest {
	@Override
	public String[] getMappings() {
File
VersionedEntityWithNonInverseOneToManyJoinTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.criterion.Restrictions;

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;

import static org.junit.Assert.assertEquals;
Solution content
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
File
KeyManyToOneTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
import java.util.TreeMap;
import java.util.TreeSet;

<<<<<<< HEAD
=======
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.event.spi.EventSource;
import org.hibernate.testing.*;
import org.jboss.logging.Logger;
import org.junit.Test;

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.FlushMode;
Solution content
import java.util.TreeMap;
import java.util.TreeSet;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.FlushMode;
File
FooBarTest.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.stat.CollectionStatistics;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======

import org.junit.Test;
import junit.framework.Assert;

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;

import static org.junit.Assert.assertEquals;
Solution content
import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.stat.CollectionStatistics;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
File
BatchedManyToManyTest.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
<<<<<<< HEAD
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package org.hibernate.test.manytomanyassociationclass.compositeid;

import org.hibernate.test.manytomanyassociationclass.AbstractManyToManyAssociationClassTest;
import org.hibernate.test.manytomanyassociationclass.Membership;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;

/**
 * Tests on many-to-many association using an association class with a composite ID containing
 * the IDs from the associated entities.
 *
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
public class ManyToManyAssociationClassCompositeIdTest extends AbstractManyToManyAssociationClassTest {
	@Override
	public String[] getMappings() {
		return new String[] { "manytomanyassociationclass/compositeid/Mappings.hbm.xml" };
	}

	@Override
	public Membership createMembership( String name ) {
		return new MembershipWithCompositeId( name );
	}
=======
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package org.hibernate.test.manytomanyassociationclass.compositeid;

import org.hibernate.test.manytomanyassociationclass.AbstractManyToManyAssociationClassTest;
import org.hibernate.test.manytomanyassociationclass.Group;
import org.hibernate.test.manytomanyassociationclass.Membership;
import org.hibernate.test.manytomanyassociationclass.User;

/**
 * Tests on many-to-many association using an association class with a composite ID containing
 * the IDs from the associated entities.
 *
 * @author Gail Badner
 */
public class ManyToManyAssociationClassCompositeIdTest extends AbstractManyToManyAssociationClassTest {
	@Override
	public String[] getMappings() {
		return new String[] { "manytomanyassociationclass/compositeid/Mappings.hbm.xml" };
	}

	@Override
	public Membership createMembership( String name ) {
		return new MembershipWithCompositeId( name );
	}
	
	@Override
	public void deleteMembership(User u, Group g, Membership ug) {
		if ( u == null || g == null ) {
			throw new IllegalArgumentException();
		}
		u.getMemberships().remove( ug );
		g.getMemberships().remove( ug );
		ug.setId(null);
	}

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
}
Solution content
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package org.hibernate.test.manytomanyassociationclass.compositeid;

import org.hibernate.test.manytomanyassociationclass.AbstractManyToManyAssociationClassTest;
import org.hibernate.test.manytomanyassociationclass.Group;
import org.hibernate.test.manytomanyassociationclass.Membership;
import org.hibernate.test.manytomanyassociationclass.User;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;

/**
 * Tests on many-to-many association using an association class with a composite ID containing
 * the IDs from the associated entities.
 *
 * @author Gail Badner
 */
@FailureExpectedWithNewMetamodel
public class ManyToManyAssociationClassCompositeIdTest extends AbstractManyToManyAssociationClassTest {
	@Override
	public String[] getMappings() {
		return new String[] { "manytomanyassociationclass/compositeid/Mappings.hbm.xml" };
	}

	@Override
	public Membership createMembership( String name ) {
		return new MembershipWithCompositeId( name );
	}
	
	@Override
	public void deleteMembership(User u, Group g, Membership ug) {
		if ( u == null || g == null ) {
			throw new IllegalArgumentException();
		}
		u.getMemberships().remove( ug );
		g.getMemberships().remove( ug );
		ug.setId(null);
	}

}
File
ManyToManyAssociationClassCompositeIdTest.java
Developer's decision
Combination
Kind of conflict
Annotation
Class signature
Comment
Import
Method declaration
Package declaration
Chunk
Conflicting content
		session.getTransaction().commit();
		session.close();
	}
<<<<<<< HEAD

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testInsertedNaturalIdCachedAfterTransactionSuccess() {

		Session session = openSession();
		session.getSessionFactory().getStatistics().clear();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.flush();
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);
		session.delete(it);
		session.getTransaction().commit();
		assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testInsertedNaturalIdNotCachedAfterTransactionFailure() {

		Session session = openSession();
		session.getSessionFactory().getStatistics().clear();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.flush();
		session.getTransaction().rollback();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNull(it);
		assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testChangedNaturalIdCachedAfterTransactionSuccess() {
		Session session = openSession();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);

		it.setName("modified");
		session.flush();
		session.getTransaction().commit();
		session.close();

		session.getSessionFactory().getStatistics().clear();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
		assertNotNull(it);
		session.delete(it);
		session.getTransaction().commit();
		session.close();

		assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testChangedNaturalIdNotCachedAfterTransactionFailure() {
		Session session = openSession();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);

		it.setName("modified");
		session.flush();
		session.getTransaction().rollback();
		session.close();

		session.getSessionFactory().getStatistics().clear();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
		assertNull(it);
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		session.delete(it);
		session.getTransaction().commit();
		session.close();

		assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

=======
	
	
	
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	@Test
	public void testNaturalIdRecachingWhenNeeded() {
		Session session = openSession();
Solution content
		session.save( it );
		session.getTransaction().commit();
		session.close();
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testInsertedNaturalIdCachedAfterTransactionSuccess() {

		Session session = openSession();
		session.getSessionFactory().getStatistics().clear();
		session.beginTransaction();
		Another it = new Another( "it");
		session.flush();
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);
		session.delete(it);
		session.getTransaction().commit();
		assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testInsertedNaturalIdNotCachedAfterTransactionFailure() {

		Session session = openSession();
		session.getSessionFactory().getStatistics().clear();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.flush();
		session.getTransaction().rollback();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNull(it);
		assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testChangedNaturalIdCachedAfterTransactionSuccess() {
		Session session = openSession();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);

		it.setName("modified");
		session.flush();
		session.getTransaction().commit();
		session.close();

		session.getSessionFactory().getStatistics().clear();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
		assertNotNull(it);
		session.delete(it);
		session.getTransaction().commit();
		session.close();

		assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	@TestForIssue( jiraKey = "HHH-7278" )
	public void testChangedNaturalIdNotCachedAfterTransactionFailure() {
		Session session = openSession();
		session.beginTransaction();
		Another it = new Another( "it");
		session.save( it );
		session.getTransaction().commit();
		session.close();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		assertNotNull(it);

		it.setName("modified");
		session.flush();
		session.getTransaction().rollback();
		session.close();

		session.getSessionFactory().getStatistics().clear();

		session = openSession();
		session.beginTransaction();
		it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
		assertNull(it);
		it = (Another) session.bySimpleNaturalId(Another.class).load("it");
		session.delete(it);
		session.getTransaction().commit();
		session.close();

		assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
	}

	@Test
	public void testNaturalIdRecachingWhenNeeded() {
		Session session = openSession();
File
CachedMutableNaturalIdTest.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
import org.hibernate.Session;
import org.hibernate.testing.FailureExpected;
<<<<<<< HEAD
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
=======
import org.hibernate.testing.TestForIssue;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;

import static org.junit.Assert.assertEquals;
Solution content
import org.hibernate.Session;
import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
File
DeleteOneToOneOrphansTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Chunk
Conflicting content
/**
 * @author Steve Ebersole
 */
<<<<<<< HEAD
@FailureExpectedWithNewMetamodel
=======
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
public class JoinedSubclassFilterTest extends BaseCoreFunctionalTestCase {
	@Override
	public final String[] getMappings() {
Solution content
/**
 * @author Steve Ebersole
 */
@FailureExpectedWithNewMetamodel
@SkipForDialect(
        value = CUBRIDDialect.class,
        comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" +
                "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables"
)
public class JoinedSubclassFilterTest extends BaseCoreFunctionalTestCase {
	@Override
	public final String[] getMappings() {
File
JoinedSubclassFilterTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Chunk
Conflicting content
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
			);
		}
<<<<<<< HEAD
		else if ( PostgreSQL81Dialect.class.isInstance( getDialect() ) )  {
=======
		else if (SybaseDialect.class.isInstance( getDialect() )) {
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
			assertSame(
					BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING,
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
Solution content
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
			);
		}
		else if (SybaseDialect.class.isInstance( getDialect() )) {
			assertSame(
					BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING,
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
File
TypeOverrideTest.java
Developer's decision
Version 2
Kind of conflict
If statement
Chunk
Conflicting content
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
<<<<<<< HEAD
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.CacheRegionDefinition;
import org.hibernate.boot.spi.JaccDefinition;
=======
import org.hibernate.boot.registry.selector.spi.StrategySelector;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
Solution content
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.boot.spi.CacheRegionDefinition;
import org.hibernate.boot.spi.JaccDefinition;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
File
EntityManagerFactoryBuilderImpl.java
Developer's decision
Combination
Kind of conflict
Import
Chunk
Conflicting content
		}
	}

<<<<<<< HEAD
	private void processProperties(BootstrapServiceRegistry bootstrapServiceRegistry) {
		applyJdbcConnectionProperties();
		applyTransactionProperties();

		final Object validationFactory = configurationValues.get( AvailableSettings.VALIDATION_FACTORY );
		if ( validationFactory != null ) {
			BeanValidationIntegrator.validateFactory( validationFactory );
		}

		// flush before completion validation
		if ( "true".equals( configurationValues.get( Environment.FLUSH_BEFORE_COMPLETION ) ) ) {
			serviceRegistryBuilder.applySetting( Environment.FLUSH_BEFORE_COMPLETION, "false" );
			LOG.definingFlushBeforeCompletionIgnoredInHem( Environment.FLUSH_BEFORE_COMPLETION );
		}

		for ( Map.Entry entry : configurationValues.entrySet() ) {
			if ( entry.getKey() instanceof String ) {
				final String keyString = (String) entry.getKey();

				if ( AvailableSettings.INTERCEPTOR.equals( keyString ) ) {
					sessionFactoryInterceptor = instantiateCustomClassFromConfiguration(
							entry.getValue(),
							Interceptor.class,
							bootstrapServiceRegistry
					);
				}
				else if ( AvailableSettings.SESSION_INTERCEPTOR.equals( keyString ) ) {
					settings.setSessionInterceptorClass(
							loadSessionInterceptorClass( entry.getValue(), bootstrapServiceRegistry )
					);
				}
				else if ( AvailableSettings.NAMING_STRATEGY.equals( keyString ) ) {
					namingStrategy = instantiateCustomClassFromConfiguration(
							entry.getValue(),
							NamingStrategy.class,
							bootstrapServiceRegistry
					);
				}
				else if ( AvailableSettings.SESSION_FACTORY_OBSERVER.equals( keyString ) ) {
					suppliedSessionFactoryObserver = instantiateCustomClassFromConfiguration(
							entry.getValue(),
							SessionFactoryObserver.class,
							bootstrapServiceRegistry
					);
				}
				else if ( AvailableSettings.DISCARD_PC_ON_CLOSE.equals( keyString ) ) {
					settings.setReleaseResourcesOnCloseEnabled( "true".equals( entry.getValue() ) );
				}
				else if ( keyString.startsWith( AvailableSettings.CLASS_CACHE_PREFIX ) ) {
					addCacheRegionDefinition(
							keyString.substring( AvailableSettings.CLASS_CACHE_PREFIX.length() + 1 ),
							(String) entry.getValue(),
							CacheRegionDefinition.CacheRegionType.ENTITY
					);
				}
				else if ( keyString.startsWith( AvailableSettings.COLLECTION_CACHE_PREFIX ) ) {
					addCacheRegionDefinition(
							keyString.substring( AvailableSettings.COLLECTION_CACHE_PREFIX.length() + 1 ),
							(String) entry.getValue(),
							CacheRegionDefinition.CacheRegionType.COLLECTION
					);
				}
				else if ( keyString.startsWith( AvailableSettings.JACC_PREFIX )
						&& ! ( keyString.equals( AvailableSettings.JACC_CONTEXT_ID )
						|| keyString.equals( AvailableSettings.JACC_ENABLED ) ) ) {
					addJaccDefinition( (String) entry.getKey(), entry.getValue() );
				}
			}
		}
	}

	private void applyJdbcConnectionProperties() {
		if ( persistenceUnit.getJtaDataSource() != null ) {
			serviceRegistryBuilder.applySetting( Environment.DATASOURCE, persistenceUnit.getJtaDataSource() );
		}
		else if ( persistenceUnit.getNonJtaDataSource() != null ) {
			serviceRegistryBuilder.applySetting( Environment.DATASOURCE, persistenceUnit.getNonJtaDataSource() );
		}
		else {
			final String driver = (String) configurationValues.get( AvailableSettings.JDBC_DRIVER );
			if ( StringHelper.isNotEmpty( driver ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.DRIVER, driver );
			}
			final String url = (String) configurationValues.get( AvailableSettings.JDBC_URL );
			if ( StringHelper.isNotEmpty( url ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.URL, url );
			}
			final String user = (String) configurationValues.get( AvailableSettings.JDBC_USER );
			if ( StringHelper.isNotEmpty( user ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.USER, user );
			}
			final String pass = (String) configurationValues.get( AvailableSettings.JDBC_PASSWORD );
			if ( StringHelper.isNotEmpty( pass ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.PASS, pass );
			}
		}
	}

	private void applyTransactionProperties() {
		PersistenceUnitTransactionType txnType = PersistenceUnitTransactionTypeHelper.interpretTransactionType(
				configurationValues.get( AvailableSettings.TRANSACTION_TYPE )
		);
		if ( txnType == null ) {
			txnType = persistenceUnit.getTransactionType();
		}
		if ( txnType == null ) {
			// is it more appropriate to have this be based on bootstrap entry point (EE vs SE)?
			txnType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
		}
		settings.setTransactionType( txnType );
		boolean hasTxStrategy = configurationValues.containsKey( Environment.TRANSACTION_STRATEGY );
		if ( hasTxStrategy ) {
			LOG.overridingTransactionStrategyDangerous( Environment.TRANSACTION_STRATEGY );
		}
		else {
			if ( txnType == PersistenceUnitTransactionType.JTA ) {
				serviceRegistryBuilder.applySetting( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class );
			}
			else if ( txnType == PersistenceUnitTransactionType.RESOURCE_LOCAL ) {
				serviceRegistryBuilder.applySetting( Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class );
=======
	/**
	 * Builds the {@link BootstrapServiceRegistry} used to eventually build the {@link org.hibernate.boot.registry.StandardServiceRegistryBuilder}; mainly
	 * used here during instantiation to define class-loading behavior.
	 *
	 * @param integrationSettings Any integration settings passed by the EE container or SE application
	 *
	 * @return The built BootstrapServiceRegistry
	 */
	private BootstrapServiceRegistry buildBootstrapServiceRegistry(Map integrationSettings) {
		final BootstrapServiceRegistryBuilder bootstrapServiceRegistryBuilder = new BootstrapServiceRegistryBuilder();
		bootstrapServiceRegistryBuilder.with( new JpaIntegrator() );

		final IntegratorProvider integratorProvider = (IntegratorProvider) integrationSettings.get( INTEGRATOR_PROVIDER );
		if ( integratorProvider != null ) {
			integrationSettings.remove( INTEGRATOR_PROVIDER );
			for ( Integrator integrator : integratorProvider.getIntegrators() ) {
				bootstrapServiceRegistryBuilder.with( integrator );
			}
		}

		ClassLoader classLoader = (ClassLoader) integrationSettings.get( org.hibernate.cfg.AvailableSettings.APP_CLASSLOADER );
		if ( classLoader != null ) {
			integrationSettings.remove( org.hibernate.cfg.AvailableSettings.APP_CLASSLOADER );
		}
		else {
			classLoader = persistenceUnit.getClassLoader();
		}
		bootstrapServiceRegistryBuilder.withApplicationClassLoader( classLoader );

		return bootstrapServiceRegistryBuilder.build();
	}

	@SuppressWarnings("unchecked")
	private Map mergePropertySources(
			PersistenceUnitDescriptor persistenceUnit,
			Map integrationSettings,
			final BootstrapServiceRegistry bootstrapServiceRegistry) {
		final Map merged = new HashMap();
		// first, apply persistence.xml-defined settings
		if ( persistenceUnit.getProperties() != null ) {
			merged.putAll( persistenceUnit.getProperties() );
		}

		merged.put( AvailableSettings.PERSISTENCE_UNIT_NAME, persistenceUnit.getName() );

		// see if the persistence.xml settings named a Hibernate config file....
		final ValueHolder configLoaderHolder = new ValueHolder(
				new ValueHolder.DeferredInitializer() {
					@Override
					public ConfigLoader initialize() {
						return new ConfigLoader( bootstrapServiceRegistry );
					}
				}
		);

		{
			final String cfgXmlResourceName = (String) merged.remove( AvailableSettings.CFG_FILE );
			if ( StringHelper.isNotEmpty( cfgXmlResourceName ) ) {
				// it does, so load those properties
				JaxbHibernateConfiguration configurationElement = configLoaderHolder.getValue()
						.loadConfigXmlResource( cfgXmlResourceName );
				processHibernateConfigurationElement( configurationElement, merged );
			}
		}

		// see if integration settings named a Hibernate config file....
		{
			final String cfgXmlResourceName = (String) integrationSettings.get( AvailableSettings.CFG_FILE );
			if ( StringHelper.isNotEmpty( cfgXmlResourceName ) ) {
				integrationSettings.remove( AvailableSettings.CFG_FILE );
				// it does, so load those properties
				JaxbHibernateConfiguration configurationElement = configLoaderHolder.getValue().loadConfigXmlResource(
						cfgXmlResourceName
				);
				processHibernateConfigurationElement( configurationElement, merged );
			}
		}

		// finally, apply integration-supplied settings (per JPA spec, integration settings should override other sources)
		merged.putAll( integrationSettings );

		if ( ! merged.containsKey( AvailableSettings.VALIDATION_MODE ) ) {
			if ( persistenceUnit.getValidationMode() != null ) {
				merged.put( AvailableSettings.VALIDATION_MODE, persistenceUnit.getValidationMode() );
			}
		}

		if ( ! merged.containsKey( AvailableSettings.SHARED_CACHE_MODE ) ) {
			if ( persistenceUnit.getSharedCacheMode() != null ) {
				merged.put( AvailableSettings.SHARED_CACHE_MODE, persistenceUnit.getSharedCacheMode() );
			}
		}

		// was getting NPE exceptions from the underlying map when just using #putAll, so going this safer route...
		Iterator itr = merged.entrySet().iterator();
		while ( itr.hasNext() ) {
			final Map.Entry entry = (Map.Entry) itr.next();
			if ( entry.getValue() == null ) {
				itr.remove();
			}
		}

		return merged;
	}

	@SuppressWarnings("unchecked")
	private void processHibernateConfigurationElement(
			JaxbHibernateConfiguration configurationElement,
			Map mergeMap) {
		if ( ! mergeMap.containsKey( org.hibernate.cfg.AvailableSettings.SESSION_FACTORY_NAME ) ) {
			String cfgName = configurationElement.getSessionFactory().getName();
			if ( cfgName != null ) {
				mergeMap.put( org.hibernate.cfg.AvailableSettings.SESSION_FACTORY_NAME, cfgName );
			}
		}

		for ( JaxbHibernateConfiguration.JaxbSessionFactory.JaxbProperty jaxbProperty : configurationElement.getSessionFactory().getProperty() ) {
			mergeMap.put( jaxbProperty.getName(), jaxbProperty.getValue() );
		}

		for ( JaxbHibernateConfiguration.JaxbSessionFactory.JaxbMapping jaxbMapping : configurationElement.getSessionFactory().getMapping() ) {
			cfgXmlNamedMappings.add( jaxbMapping );
		}

		for ( Object cacheDeclaration : configurationElement.getSessionFactory().getClassCacheOrCollectionCache() ) {
			if ( JaxbHibernateConfiguration.JaxbSessionFactory.JaxbClassCache.class.isInstance( cacheDeclaration ) ) {
				final JaxbHibernateConfiguration.JaxbSessionFactory.JaxbClassCache jaxbClassCache
						= (JaxbHibernateConfiguration.JaxbSessionFactory.JaxbClassCache) cacheDeclaration;
				cacheRegionDefinitions.add(
						new CacheRegionDefinition(
								CacheRegionDefinition.CacheType.ENTITY,
								jaxbClassCache.getClazz(),
								jaxbClassCache.getUsage().value(),
								jaxbClassCache.getRegion(),
								"all".equals( jaxbClassCache.getInclude() )
						)
				);
			}
			else {
				final JaxbHibernateConfiguration.JaxbSessionFactory.JaxbCollectionCache jaxbCollectionCache
						= (JaxbHibernateConfiguration.JaxbSessionFactory.JaxbCollectionCache) cacheDeclaration;
				cacheRegionDefinitions.add(
						new CacheRegionDefinition(
								CacheRegionDefinition.CacheType.COLLECTION,
								jaxbCollectionCache.getCollection(),
								jaxbCollectionCache.getUsage().value(),
								jaxbCollectionCache.getRegion(),
								false
						)
				);
			}
		}

		if ( configurationElement.getSecurity() != null ) {
			final String contextId = configurationElement.getSecurity().getContext();
			for ( JaxbHibernateConfiguration.JaxbSecurity.JaxbGrant grant : configurationElement.getSecurity().getGrant() ) {
				jaccDefinitions.add(
						new JaccDefinition(
								contextId,
								grant.getRole(),
								grant.getEntityName(),
								grant.getActions()
						)
				);
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
			}
		}
	}
Solution content
		}
	}

	private String jaccContextId;

	private void addJaccDefinition(String key, Object value) {
		if ( jaccContextId == null ) {
			jaccContextId = (String) configurationValues.get( AvailableSettings.JACC_CONTEXT_ID );
			if ( jaccContextId == null ) {
				throw persistenceException(
						"Entities have been configured for JACC, but "
								+ AvailableSettings.JACC_CONTEXT_ID + " has not been set"
				);
			}
		}

		try {
			final int roleStart = AvailableSettings.JACC_PREFIX.length() + 1;
			final String role = key.substring( roleStart, key.indexOf( '.', roleStart ) );
			final int classStart = roleStart + role.length() + 1;
			final String clazz = key.substring( classStart, key.length() );

			final JaccDefinition def = new JaccDefinition( jaccContextId, role, clazz, (String) value );

			jaccDefinitions.add( def );

		}
		catch ( IndexOutOfBoundsException e ) {
			throw persistenceException( "Illegal usage of " + AvailableSettings.JACC_PREFIX + ": " + key );
		}
	}

	private void addCacheRegionDefinition(String role, String value, CacheRegionDefinition.CacheRegionType cacheType) {
		final StringTokenizer params = new StringTokenizer( value, ";, " );
		if ( !params.hasMoreTokens() ) {
			StringBuilder error = new StringBuilder( "Illegal usage of " );
			if ( cacheType == CacheRegionDefinition.CacheRegionType.ENTITY ) {
				error.append( AvailableSettings.CLASS_CACHE_PREFIX )
						.append( ": " )
						.append( AvailableSettings.CLASS_CACHE_PREFIX );
			}
			else {
				error.append( AvailableSettings.COLLECTION_CACHE_PREFIX )
						.append( ": " )
						.append( AvailableSettings.COLLECTION_CACHE_PREFIX );
			}
			error.append( '.' )
					.append( role )
					.append( ' ' )
					.append( value )
					.append( ".  Was expecting configuration, but found none" );
			throw persistenceException( error.toString() );
		}

		String usage = params.nextToken();
		String region = null;
		if ( params.hasMoreTokens() ) {
			region = params.nextToken();
		}
		boolean lazyProperty = true;
		if ( cacheType == CacheRegionDefinition.CacheRegionType.ENTITY ) {
			if ( params.hasMoreTokens() ) {
				lazyProperty = "all".equalsIgnoreCase( params.nextToken() );
			}
		}
		else {
			lazyProperty = false;
		}

		final CacheRegionDefinition def = new CacheRegionDefinition( cacheType, role, usage, region, lazyProperty );
		cacheRegionDefinitions.add( def );
	}

	@SuppressWarnings("unchecked")
	private ScanResult scan(BootstrapServiceRegistry bootstrapServiceRegistry) {
		Scanner scanner = locateOrBuildScanner( bootstrapServiceRegistry );
		ScanningContext scanningContext = new ScanningContext();

		final ScanResult scanResult = new ScanResult();
		if ( persistenceUnit.getMappingFileNames() != null ) {
			scanResult.getMappingFiles().addAll( persistenceUnit.getMappingFileNames() );
		}

		// dunno, but the old code did it...
		scanningContext.setSearchOrm( ! scanResult.getMappingFiles().contains( META_INF_ORM_XML ) );

		if ( persistenceUnit.getJarFileUrls() != null ) {
			prepareAutoDetectionSettings( scanningContext, false );
			for ( URL jar : persistenceUnit.getJarFileUrls() ) {
				scanningContext.setUrl( jar );
				scanInContext( scanner, scanningContext, scanResult );
			}
		}

		prepareAutoDetectionSettings( scanningContext, persistenceUnit.isExcludeUnlistedClasses() );
		scanningContext.setUrl( persistenceUnit.getPersistenceUnitRootUrl() );
		scanInContext( scanner, scanningContext, scanResult );

		return scanResult;
	}

	@SuppressWarnings("unchecked")
	private Scanner locateOrBuildScanner(BootstrapServiceRegistry bootstrapServiceRegistry) {
		final Object value = configurationValues.remove( AvailableSettings.SCANNER );
		if ( value == null ) {
			}
		}
			return new NativeScanner();
		}

		if ( Scanner.class.isInstance( value ) ) {
			return (Scanner) value;
		}

		Class scannerClass;
		if ( Class.class.isInstance( value ) ) {
			try {
				scannerClass = (Class) value;
			}
			catch ( ClassCastException e ) {
				throw persistenceException( "Expecting Scanner implementation, but found " + ((Class) value).getName() );
			}
		}
		else {
			final String scannerClassName = value.toString();
			try {
				scannerClass = bootstrapServiceRegistry.getService( ClassLoaderService.class ).classForName(
						scannerClassName
				);
			}
			catch ( ClassCastException e ) {
				throw persistenceException( "Expecting Scanner implementation, but found " + scannerClassName );
			}
		}

		try {
			return scannerClass.newInstance();
		}
		catch ( Exception e ) {
			throw persistenceException( "Unable to instantiate Scanner class: " + scannerClass, e );
		}
	}

	private void prepareAutoDetectionSettings(ScanningContext context, boolean excludeUnlistedClasses) {
		final String detectionSetting = (String) configurationValues.get( AvailableSettings.AUTODETECTION );

		if ( detectionSetting == null ) {
			if ( excludeUnlistedClasses ) {
				context.setDetectClasses( false );
				context.setDetectHbmFiles( false );
			}
			else {
				context.setDetectClasses( true );
				context.setDetectHbmFiles( true );
			}
		}
		else {
			for ( String token : StringHelper.split( ", ", detectionSetting ) ) {
				if ( "class".equalsIgnoreCase( token ) ) {
					context.setDetectClasses( true );
				}
				if ( "hbm".equalsIgnoreCase( token ) ) {
					context.setDetectClasses( true );
				}
	}

	private void scanInContext(
			Scanner scanner,
			ScanningContext scanningContext,
			ScanResult scanResult) {
		if ( scanningContext.getUrl() == null ) {
			// not sure i like just ignoring this being null, but this is exactly what the old code does...
			LOG.containerProvidingNullPersistenceUnitRootUrl();
			return;
		}

		try {
			if ( scanningContext.isDetectClasses() ) {
				Set matchingPackages = scanner.getPackagesInJar( scanningContext.url, new HashSet>(0) );
				for ( Package pkg : matchingPackages ) {
					scanResult.getPackageNames().add( pkg.getName() );
				}

				Set> annotationsToLookFor = new HashSet>();
				annotationsToLookFor.add( Entity.class );
				annotationsToLookFor.add( MappedSuperclass.class );
				annotationsToLookFor.add( Embeddable.class );
				annotationsToLookFor.add( Converter.class );
				Set> matchingClasses = scanner.getClassesInJar( scanningContext.url, annotationsToLookFor );
				for ( Class clazz : matchingClasses ) {
					scanResult.getManagedClassNames().add( clazz.getName() );
				}
			}

			Set patterns = new HashSet();
			if ( scanningContext.isSearchOrm() ) {
				patterns.add( META_INF_ORM_XML );
			}
			if ( scanningContext.isDetectHbmFiles() ) {
				patterns.add( "**/*.hbm.xml" );
			}
			if ( ! scanResult.getMappingFiles().isEmpty() ) {
				patterns.addAll( scanResult.getMappingFiles() );
			}
			if ( patterns.size() != 0 ) {
				Set files = scanner.getFilesInJar( scanningContext.getUrl(), patterns );
				for ( NamedInputStream file : files ) {
					scanResult.getHbmFiles().add( file );
					scanResult.getMappingFiles().remove( file.getName() );
				}
			}
		}
		catch (PersistenceException e ) {
			throw e;
		}
		catch ( RuntimeException e ) {
			throw persistenceException( "error trying to scan url: " + scanningContext.getUrl().toString(), e );
		}
	}

	@Override
	public EntityManagerFactoryBuilder withValidatorFactory(Object validatorFactory) {
		this.validatorFactory = validatorFactory;

		if ( validatorFactory != null ) {
			BeanValidationIntegrator.validateFactory( validatorFactory );
		}
		return this;
	}

	@Override
	public EntityManagerFactoryBuilder withDataSource(DataSource dataSource) {
		this.dataSource = dataSource;

		return this;
	}

	@Override
	public void cancel() {
		// todo : close the bootstrap registry (not critical, but nice to do)

	}

	@SuppressWarnings("unchecked")
	public EntityManagerFactory build() {
		processProperties();

		final ServiceRegistry serviceRegistry = buildServiceRegistry();
		final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );

		// IMPL NOTE : TCCL handling here is temporary.
		//		It is needed because this code still uses Hibernate Configuration and Hibernate commons-annotations
		// 		in turn which relies on TCCL being set.

		return ( (ClassLoaderServiceImpl) classLoaderService ).withTccl(
				new ClassLoaderServiceImpl.Work() {
					@Override
					public EntityManagerFactoryImpl perform() {
						hibernateConfiguration = buildHibernateConfiguration( serviceRegistry );

						SessionFactoryImplementor sessionFactory;
						try {
							sessionFactory = (SessionFactoryImplementor) hibernateConfiguration.buildSessionFactory(
									serviceRegistry
							);
						}
						catch (MappingException e) {
							throw persistenceException( "Unable to build Hibernate SessionFactory", e );
						}

						if ( suppliedSessionFactoryObserver != null ) {
							sessionFactory.addObserver( suppliedSessionFactoryObserver );
						}
						sessionFactory.addObserver( new ServiceRegistryCloser() );

						// NOTE : passing cfg is temporary until
						return new EntityManagerFactoryImpl(
								persistenceUnit.getName(),
								sessionFactory,
								settings,
								configurationValues,
								hibernateConfiguration
						);
					}
				}
		);
	}

	private void processProperties() {
		applyJdbcConnectionProperties();
		applyTransactionProperties();

		Object validationFactory = this.validatorFactory;
		if ( validationFactory == null ) {
			validationFactory = configurationValues.get( AvailableSettings.VALIDATION_FACTORY );
		}
		if ( validationFactory != null ) {
			BeanValidationIntegrator.validateFactory( validationFactory );
			serviceRegistryBuilder.applySetting( AvailableSettings.VALIDATION_FACTORY, validationFactory );
		}

		// flush before completion validation
		if ( "true".equals( configurationValues.get( Environment.FLUSH_BEFORE_COMPLETION ) ) ) {
			serviceRegistryBuilder.applySetting( Environment.FLUSH_BEFORE_COMPLETION, "false" );
			LOG.definingFlushBeforeCompletionIgnoredInHem( Environment.FLUSH_BEFORE_COMPLETION );
		}

				cfg.addAnnotatedClass(
		final StrategySelector strategySelector = serviceRegistryBuilder.getBootstrapServiceRegistry().getService( StrategySelector.class );

		for ( Object oEntry : configurationValues.entrySet() ) {
			Map.Entry entry = (Map.Entry) oEntry;
			if ( entry.getKey() instanceof String ) {
				final String keyString = (String) entry.getKey();

				if ( AvailableSettings.INTERCEPTOR.equals( keyString ) ) {
					sessionFactoryInterceptor = strategySelector.resolveStrategy( Interceptor.class, entry.getValue() );
				}
				else if ( AvailableSettings.SESSION_INTERCEPTOR.equals( keyString ) ) {
					settings.setSessionInterceptorClass(
							loadSessionInterceptorClass( entry.getValue(), strategySelector )
					);
				}
				else if ( AvailableSettings.NAMING_STRATEGY.equals( keyString ) ) {
					namingStrategy = strategySelector.resolveStrategy( NamingStrategy.class, entry.getValue() );
				}
				else if ( AvailableSettings.SESSION_FACTORY_OBSERVER.equals( keyString ) ) {
					suppliedSessionFactoryObserver = strategySelector.resolveStrategy( SessionFactoryObserver.class, entry.getValue() );
				}
				else if ( AvailableSettings.DISCARD_PC_ON_CLOSE.equals( keyString ) ) {
					settings.setReleaseResourcesOnCloseEnabled( "true".equals( entry.getValue() ) );
				}
				else if ( keyString.startsWith( AvailableSettings.CLASS_CACHE_PREFIX ) ) {
					addCacheRegionDefinition(
							keyString.substring( AvailableSettings.CLASS_CACHE_PREFIX.length() + 1 ),
							(String) entry.getValue(),
							CacheRegionDefinition.CacheRegionType.ENTITY
					);
				}
				else if ( keyString.startsWith( AvailableSettings.COLLECTION_CACHE_PREFIX ) ) {
					addCacheRegionDefinition(
							keyString.substring( AvailableSettings.COLLECTION_CACHE_PREFIX.length() + 1 ),
							(String) entry.getValue(),
							CacheRegionDefinition.CacheRegionType.COLLECTION
					);
				}
				else if ( keyString.startsWith( AvailableSettings.JACC_PREFIX )
						&& ! ( keyString.equals( AvailableSettings.JACC_CONTEXT_ID )
						|| keyString.equals( AvailableSettings.JACC_ENABLED ) ) ) {
					addJaccDefinition( (String) entry.getKey(), entry.getValue() );
				}
			}
		}
	}

	private void applyJdbcConnectionProperties() {

		if ( dataSource != null ) {
			serviceRegistryBuilder.applySetting( Environment.DATASOURCE, dataSource );
		}
		else if ( persistenceUnit.getJtaDataSource() != null ) {
			serviceRegistryBuilder.applySetting( Environment.DATASOURCE, persistenceUnit.getJtaDataSource() );
		}
		else if ( persistenceUnit.getNonJtaDataSource() != null ) {
			serviceRegistryBuilder.applySetting( Environment.DATASOURCE, persistenceUnit.getNonJtaDataSource() );
		}
		else {
			final String driver = (String) configurationValues.get( AvailableSettings.JDBC_DRIVER );
			if ( StringHelper.isNotEmpty( driver ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.DRIVER, driver );
			}
			final String url = (String) configurationValues.get( AvailableSettings.JDBC_URL );
			if ( StringHelper.isNotEmpty( url ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.URL, url );
			}
			final String user = (String) configurationValues.get( AvailableSettings.JDBC_USER );
			if ( StringHelper.isNotEmpty( user ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.USER, user );
			}
			final String pass = (String) configurationValues.get( AvailableSettings.JDBC_PASSWORD );
			if ( StringHelper.isNotEmpty( pass ) ) {
				serviceRegistryBuilder.applySetting( org.hibernate.cfg.AvailableSettings.PASS, pass );
			}
		}
	}

	private void applyTransactionProperties() {
		PersistenceUnitTransactionType txnType = PersistenceUnitTransactionTypeHelper.interpretTransactionType(
				configurationValues.get( AvailableSettings.TRANSACTION_TYPE )
		);
		if ( txnType == null ) {
			txnType = persistenceUnit.getTransactionType();
		}
		if ( txnType == null ) {
			// is it more appropriate to have this be based on bootstrap entry point (EE vs SE)?
				else {
			txnType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
		}
		settings.setTransactionType( txnType );
		boolean hasTxStrategy = configurationValues.containsKey( Environment.TRANSACTION_STRATEGY );
		if ( hasTxStrategy ) {
			LOG.overridingTransactionStrategyDangerous( Environment.TRANSACTION_STRATEGY );
		}
		else {
			if ( txnType == PersistenceUnitTransactionType.JTA ) {
				serviceRegistryBuilder.applySetting( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class );
			}
			else if ( txnType == PersistenceUnitTransactionType.RESOURCE_LOCAL ) {
				serviceRegistryBuilder.applySetting( Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class );
			}
		}
	}

	@SuppressWarnings("unchecked")
	private Class loadSessionInterceptorClass(Object value, StrategySelector strategySelector) {
		if ( value == null ) {
			return null;
		}

		return Class.class.isInstance( value )
				? (Class) value
				: strategySelector.selectStrategyImplementor( Interceptor.class, value.toString() );
	}

	public ServiceRegistry buildServiceRegistry() {
		return serviceRegistryBuilder.build();
	}

	public Configuration buildHibernateConfiguration(ServiceRegistry serviceRegistry) {
		Properties props = new Properties();
		props.putAll( configurationValues );
		Configuration cfg = new Configuration().setProperties( props );

		cfg.setEntityNotFoundDelegate( jpaEntityNotFoundDelegate );

		if ( namingStrategy != null ) {
			cfg.setNamingStrategy( namingStrategy );
		}

		if ( sessionFactoryInterceptor != null ) {
			cfg.setInterceptor( sessionFactoryInterceptor );
		}

		final Object strategyProviderValue = props.get( AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER );
		final IdentifierGeneratorStrategyProvider strategyProvider = strategyProviderValue == null
				? null
				: serviceRegistry.getService( StrategySelector.class )
						.resolveStrategy( IdentifierGeneratorStrategyProvider.class, strategyProviderValue );
		if ( strategyProvider != null ) {
			final MutableIdentifierGeneratorFactory identifierGeneratorFactory = cfg.getIdentifierGeneratorFactory();
			for ( Map.Entry> entry : strategyProvider.getStrategies().entrySet() ) {
				identifierGeneratorFactory.register( entry.getKey(), entry.getValue() );
			}
		}

		if ( jaccDefinitions != null ) {
			for ( JaccDefinition jaccDefinition : jaccDefinitions ) {
				JACCConfiguration jaccCfg = new JACCConfiguration( jaccDefinition.getContextId() );
				jaccCfg.addPermission(
						jaccDefinition.getRole(),
						jaccDefinition.getClazz(),
						jaccDefinition.getActions()
				);
			}
		}

		if ( cacheRegionDefinitions != null ) {
			for ( CacheRegionDefinition cacheRegionDefinition : cacheRegionDefinitions ) {
				if ( cacheRegionDefinition.getRegionType() == CacheRegionDefinition.CacheRegionType.ENTITY ) {
					cfg.setCacheConcurrencyStrategy(
							cacheRegionDefinition.getRole(),
							cacheRegionDefinition.getUsage(),
							cacheRegionDefinition.getRegion(),
							cacheRegionDefinition.isCacheLazy()
					);
				}
				else {
					cfg.setCollectionCacheConcurrencyStrategy(
							cacheRegionDefinition.getRole(),
							cacheRegionDefinition.getUsage(),
							cacheRegionDefinition.getRegion()
					);
				}
			}
		}


		// todo : need to have this use the metamodel codebase eventually...

		for ( JaxbMapping jaxbMapping : cfgXmlNamedMappings ) {
			if ( jaxbMapping.getClazz() != null ) {
						serviceRegistry.getService( ClassLoaderService.class ).classForName( jaxbMapping.getClazz() )
				);
			}
			else if ( jaxbMapping.getResource() != null ) {
				cfg.addResource( jaxbMapping.getResource() );
			}
			else if ( jaxbMapping.getJar() != null ) {
				cfg.addJar( new File( jaxbMapping.getJar() ) );
			}
			else if ( jaxbMapping.getPackage() != null ) {
				cfg.addPackage( jaxbMapping.getPackage() );
			}
		}

		List loadedAnnotatedClasses = (List) configurationValues.remove( AvailableSettings.LOADED_CLASSES );
		if ( loadedAnnotatedClasses != null ) {
			for ( Class cls : loadedAnnotatedClasses ) {
				cfg.addAnnotatedClass( cls );
			}
		}

		for ( String className : metadataSources.getAnnotatedMappingClassNames() ) {
			cfg.addAnnotatedClass( serviceRegistry.getService( ClassLoaderService.class ).classForName( className ) );
		}

		for ( MetadataSources.ConverterDescriptor converterDescriptor : metadataSources.getConverterDescriptors() ) {
			final Class converterClass;
			try {
				Class theClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( converterDescriptor.converterClassName );
				converterClass = (Class) theClass;
			}
			catch (ClassCastException e) {
				throw persistenceException(
						String.format(
								"AttributeConverter implementation [%s] does not implement AttributeConverter interface",
								converterDescriptor.converterClassName
						)
				);
			}
			cfg.addAttributeConverter( converterClass, converterDescriptor.autoApply );
		}

		for ( String resourceName : metadataSources.mappingFileResources ) {
			Boolean useMetaInf = null;
			try {
				if ( resourceName.endsWith( META_INF_ORM_XML ) ) {
					useMetaInf = true;
				}
				cfg.addResource( resourceName );
			}
			catch( MappingNotFoundException e ) {
				if ( ! resourceName.endsWith( META_INF_ORM_XML ) ) {
					throw persistenceException( "Unable to find XML mapping file in classpath: " + resourceName );
				}
					useMetaInf = false;
					//swallow it, the META-INF/orm.xml is optional
				}
			}
			catch( MappingException me ) {
				throw persistenceException( "Error while reading JPA XML file: " + resourceName, me );
			}

			if ( Boolean.TRUE.equals( useMetaInf ) ) {
				LOG.exceptionHeaderFound( getExceptionHeader(), META_INF_ORM_XML );
			}
			else if (Boolean.FALSE.equals(useMetaInf)) {
				LOG.exceptionHeaderNotFound( getExceptionHeader(), META_INF_ORM_XML );
			}
		}
		for ( NamedInputStream namedInputStream : metadataSources.namedMappingFileInputStreams ) {
			try {
				//addInputStream has the responsibility to close the stream
				cfg.addInputStream( new BufferedInputStream( namedInputStream.getStream() ) );
			}
			catch (MappingException me) {
				//try our best to give the file name
				if ( StringHelper.isEmpty( namedInputStream.getName() ) ) {
					throw me;
				}
				else {
					throw new MappingException("Error while parsing file: " + namedInputStream.getName(), me );
				}
			}
		}
		for ( String packageName : metadataSources.packageNames ) {
			cfg.addPackage( packageName );
		}
		return cfg;
	}

	public static class ServiceRegistryCloser implements SessionFactoryObserver {
		@Override
		public void sessionFactoryCreated(SessionFactory sessionFactory) {
			// nothing to do
		}

		@Override
		public void sessionFactoryClosed(SessionFactory sessionFactory) {
			SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) sessionFactory );
			sfi.getServiceRegistry().destroy();
			ServiceRegistry basicRegistry = sfi.getServiceRegistry().getParentServiceRegistry();
			( (ServiceRegistryImplementor) basicRegistry ).destroy();
		}
	}

	private PersistenceException persistenceException(String message) {
		return persistenceException( message, null );
	}

	private PersistenceException persistenceException(String message, Exception cause) {
		return new PersistenceException(
				getExceptionHeader() + message,
				cause
		);
	}

	private String getExceptionHeader() {
		return "[PersistenceUnit: " + persistenceUnit.getName() + "] ";
	}

	public static class ScanningContext {
		private URL url;
		private boolean detectClasses;
		private boolean detectHbmFiles;
		private boolean searchOrm;

		public URL getUrl() {
			return url;
		}

		public void setUrl(URL url) {
			this.url = url;
		}

		public boolean isDetectClasses() {
			return detectClasses;
		}

		public void setDetectClasses(boolean detectClasses) {
			this.detectClasses = detectClasses;
		}

		public boolean isDetectHbmFiles() {
			return detectHbmFiles;
		}

		public void setDetectHbmFiles(boolean detectHbmFiles) {
			this.detectHbmFiles = detectHbmFiles;
		}

		public boolean isSearchOrm() {
			return searchOrm;
		}

		public void setSearchOrm(boolean searchOrm) {
			this.searchOrm = searchOrm;
		}
	}

	private static class ScanResult {
		private final List managedClassNames = new ArrayList();
		private final List packageNames = new ArrayList();
		private final List hbmFiles = new ArrayList();
		private final List mappingFiles = new ArrayList();

		public List getManagedClassNames() {
			return managedClassNames;
		}

		public List getPackageNames() {
			return packageNames;
		}

		public List getHbmFiles() {
			return hbmFiles;
		}

		public List getMappingFiles() {
			return mappingFiles;
		}
	}

	public static class MetadataSources {
		private final List annotatedMappingClassNames = new ArrayList();
		private final List converterDescriptors = new ArrayList();
		private final List namedMappingFileInputStreams = new ArrayList();
		private final List mappingFileResources = new ArrayList();
		private final List packageNames = new ArrayList();

		public List getAnnotatedMappingClassNames() {
			return annotatedMappingClassNames;
		}

		public List getConverterDescriptors() {
			return converterDescriptors;
		}

		public List getNamedMappingFileInputStreams() {
			return namedMappingFileInputStreams;
		}

		public List getPackageNames() {
			return packageNames;
		}

		public List collectMappingClassNames() {
			// todo : the complete answer to this involves looking through the mapping files as well.
			// 		Really need the metamodel branch code to do that properly
			return annotatedMappingClassNames;
		}

		public static class ConverterDescriptor {
			private final String converterClassName;
			private final boolean autoApply;

			public ConverterDescriptor(String converterClassName, boolean autoApply) {
				this.converterClassName = converterClassName;
				this.autoApply = autoApply;
			}
		}
	}
}
File
EntityManagerFactoryBuilderImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
For statement
If statement
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
		}
	}

<<<<<<< HEAD
	@SuppressWarnings("unchecked")
	private Class loadSessionInterceptorClass(
			Object value,
			BootstrapServiceRegistry bootstrapServiceRegistry) {
		if ( value == null ) {
			return null;
		}

		Class theClass;
		if ( Class.class.isInstance( value ) ) {
			theClass = (Class) value;
		}
		else {
			theClass = bootstrapServiceRegistry.getService( ClassLoaderService.class ).classForName( value.toString() );
		}

		try {
			return (Class) theClass;
		}
		catch (ClassCastException e) {
			throw persistenceException(
					String.format(
							"Specified Interceptor implementation class [%s] was not castable to Interceptor",
							theClass.getName()
					)
			);
		}
	}

	private void addCacheRegionDefinition(String role, String value, CacheRegionDefinition.CacheRegionType cacheType) {
=======
	private void addCacheRegionDefinition(String role, String value, CacheRegionDefinition.CacheType cacheType) {
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
		final StringTokenizer params = new StringTokenizer( value, ";, " );
		if ( !params.hasMoreTokens() ) {
			StringBuilder error = new StringBuilder( "Illegal usage of " );
Solution content
		}
	}

	private void addCacheRegionDefinition(String role, String value, CacheRegionDefinition.CacheRegionType cacheType) {
		final StringTokenizer params = new StringTokenizer( value, ";, " );
		if ( !params.hasMoreTokens() ) {
			StringBuilder error = new StringBuilder( "Illegal usage of " );
File
EntityManagerFactoryBuilderImpl.java
Developer's decision
Combination
Kind of conflict
Annotation
Method declaration
Method signature
Chunk
Conflicting content
    */
   @Override
   public void start(Settings settings, Properties properties) throws CacheException {
<<<<<<< HEAD
     	start();
=======
      log.debug("Starting Infinispan region factory");
      try {
         transactionManagerlookup = createTransactionManagerLookup(settings, properties);
         manager = createCacheManager(properties);
         initGenericDataTypeOverrides();
         Enumeration keys = properties.propertyNames();
         while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            int prefixLoc;
            if ((prefixLoc = key.indexOf(PREFIX)) != -1) {
               dissectProperty(prefixLoc, key, properties);
            }
         }
         defineGenericDataTypeCacheConfigurations(properties);
         definePendingPutsCache();
      } catch (CacheException ce) {
         throw ce;
      } catch (Throwable t) {
          throw new CacheException("Unable to start region factory", t);
      }
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
   }

   private void definePendingPutsCache() {
Solution content
    */
   @Override
   public void start(Settings settings, Properties properties) throws CacheException {
     	start();
   }

   private void definePendingPutsCache() {
File
InfinispanRegionFactory.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Try statement
Chunk
Conflicting content
      return Collections.unmodifiableSet(definedConfigurations);
   }

<<<<<<< HEAD
   protected EmbeddedCacheManager createCacheManager() throws CacheException {
	   try {
		   ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
		   String configLoc = configurationService.getSetting(
				   INFINISPAN_CONFIG_RESOURCE_PROP,
				   StandardConverters.STRING, DEF_INFINISPAN_CONFIG_RESOURCE
		   );
		   EmbeddedCacheManager manager = new DefaultCacheManager( configLoc, false );
		   Boolean globalStats = configurationService.getSetting(
				   INFINISPAN_GLOBAL_STATISTICS_PROP,
				   StandardConverters.BOOLEAN,
				   false
		   );
		   if ( globalStats ) {
			   manager.getGlobalConfiguration().fluent().globalJmxStatistics();
		   }
		   manager.start();
		   return manager;
	   }
	   catch ( IOException e ) {
		   throw new CacheException( "Unable to create default cache manager", e );
	   }
=======
   protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
      try {
         String configLoc = ConfigurationHelper.getString(
               INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE);
         ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
         InputStream is = FileLookupFactory.newInstance().lookupFileStrict(
               configLoc, ctxClassLoader);
         ParserRegistry parserRegistry = new ParserRegistry(ctxClassLoader);
         ConfigurationBuilderHolder holder = parserRegistry.parse(is);

         // Override global jmx statistics exposure
         String globalStats = extractProperty(
               INFINISPAN_GLOBAL_STATISTICS_PROP, properties);
         if (globalStats != null)
            holder.getGlobalConfigurationBuilder().globalJmxStatistics()
                  .enabled(Boolean.parseBoolean(globalStats));

         return createCacheManager(holder);
      } catch (IOException e) {
         throw new CacheException("Unable to create default cache manager", e);
      }
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
   }

   protected EmbeddedCacheManager createCacheManager(
Solution content
      return Collections.unmodifiableSet(definedConfigurations);
   }

   protected EmbeddedCacheManager createCacheManager(Map properties) throws CacheException {
      try {
         String configLoc = ConfigurationHelper.getString(
               INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE);
         ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
         InputStream is = FileLookupFactory.newInstance().lookupFileStrict(
               configLoc, ctxClassLoader);
         ParserRegistry parserRegistry = new ParserRegistry(ctxClassLoader);
         ConfigurationBuilderHolder holder = parserRegistry.parse(is);

         // Override global jmx statistics exposure
         String globalStats = extractProperty(
               INFINISPAN_GLOBAL_STATISTICS_PROP, properties);
         if (globalStats != null)
            holder.getGlobalConfigurationBuilder().globalJmxStatistics()
                  .enabled(Boolean.parseBoolean(globalStats));

         return createCacheManager(holder);
      } catch (IOException e) {
         throw new CacheException("Unable to create default cache manager", e);
      }
   }

   protected EmbeddedCacheManager createCacheManager(
File
InfinispanRegionFactory.java
Developer's decision
Manual
Kind of conflict
Method signature
Try statement
Chunk
Conflicting content
      return cfgOverride;
   }

<<<<<<< HEAD
   private void defineGenericDataTypeCacheConfigurations(Map properties) throws CacheException {
=======
   private void defineGenericDataTypeCacheConfigurations(Properties properties) {
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
      String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY};
      for (String type : defaultGenericDataTypes) {
         TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties);
Solution content
      return cfgOverride;
   }

   private void defineGenericDataTypeCacheConfigurations(Map properties) {
      String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY};
      for (String type : defaultGenericDataTypes) {
         TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties);
File
InfinispanRegionFactory.java
Developer's decision
Manual
Kind of conflict
Method signature
Chunk
Conflicting content
      return cache;
   }

<<<<<<< HEAD
   private Configuration configureTransactionManager(Configuration regionOverrides, String templateCacheName, Map properties) {
=======
   private void configureTransactionManager(ConfigurationBuilder builder,
         String cacheName, Properties properties) {
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
      // Get existing configuration to verify whether a tm was configured or not.
      Configuration baseCfg = manager.getCacheConfiguration(cacheName);
      if (baseCfg != null && baseCfg.transaction().transactionMode().isTransactional()) {
Solution content
      return cache;
   }

   private void configureTransactionManager(ConfigurationBuilder builder,
         String cacheName, Map properties) {
      // Get existing configuration to verify whether a tm was configured or not.
      Configuration baseCfg = manager.getCacheConfiguration(cacheName);
      if (baseCfg != null && baseCfg.transaction().transactionMode().isTransactional()) {
File
InfinispanRegionFactory.java
Developer's decision
Manual
Kind of conflict
Method signature
Chunk
Conflicting content
            log.debug("Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " +
                            "class than Hibernate [" + hbTmLookupClassName + "]");
         } else {
<<<<<<< HEAD
            regionOverrides.fluent().transactionManagerLookup( transactionManagerlookup );
=======
            // Infinispan TM lookup class null, so apply Hibernate one directly
            builder.transaction().transactionManagerLookup(transactionManagerlookup);
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
         }

         String useSyncProp = extractProperty(INFINISPAN_USE_SYNCHRONIZATION_PROP, properties);
Solution content
            log.debug("Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " +
                            "class than Hibernate [" + hbTmLookupClassName + "]");
         } else {
            // Infinispan TM lookup class null, so apply Hibernate one directly
            builder.transaction().transactionManagerLookup(transactionManagerlookup);
         }

         String useSyncProp = extractProperty(INFINISPAN_USE_SYNCHRONIZATION_PROP, properties);
File
InfinispanRegionFactory.java
Developer's decision
Version 2
Kind of conflict
Comment
Method invocation
Chunk
Conflicting content
import org.hibernate.cache.infinispan.entity.EntityRegionImpl;
import org.hibernate.cache.infinispan.query.QueryResultsRegionImpl;
import org.hibernate.cache.infinispan.timestamp.TimestampsRegionImpl;
<<<<<<< HEAD
import org.hibernate.cache.infinispan.util.CacheAdapter;
import org.hibernate.cache.internal.RegionFactoryInitiator;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
=======
import org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.hibernate.engine.transaction.jta.platform.internal.JBossStandAloneJtaPlatform;
import org.hibernate.service.ServiceRegistry;
Solution content
import org.hibernate.cache.infinispan.entity.EntityRegionImpl;
import org.hibernate.cache.infinispan.query.QueryResultsRegionImpl;
import org.hibernate.cache.infinispan.timestamp.TimestampsRegionImpl;
import org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.internal.JBossStandAloneJtaPlatform;
import org.hibernate.service.ServiceRegistry;
File
InfinispanRegionFactoryTestCase.java
Developer's decision
Combination
Kind of conflict
Import
Chunk
Conflicting content
 * @author Galder Zamarreño
 * @since 3.5
 */
<<<<<<< HEAD
public class InfinispanRegionFactoryTestCase {
	@Test
	public void testConfigurationProcessing() {
		final String person = "com.acme.Person";
		final String addresses = "com.acme.Person.addresses";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "person-addresses-cache" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "120000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "60000" );
		p.setProperty( "hibernate.cache.infinispan.query.cfg", "my-query-cache" );
		p.setProperty( "hibernate.cache.infinispan.query.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.query.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.query.eviction.max_entries", "10000" );

		SessionFactoryImplementor sf = createSessionFactory(null, p );
		try {
			InfinispanRegionFactory factory = (InfinispanRegionFactory) sf.getServiceRegistry()
					.getService( RegionFactory.class );

			assertEquals( "entity", factory.getTypeOverrides().get( "entity" ).getCacheName() );
			assertEquals( "entity", factory.getTypeOverrides().get( "collection" ).getCacheName() );
			assertEquals( "timestamps", factory.getTypeOverrides().get( "timestamps" ).getCacheName() );

			assertEquals( "person-cache", factory.getTypeOverrides().get( person ).getCacheName() );
			assertEquals( EvictionStrategy.LRU, factory.getTypeOverrides().get( person ).getEvictionStrategy() );
			assertEquals( 2000, factory.getTypeOverrides().get( person ).getEvictionWakeUpInterval() );
			assertEquals( 5000, factory.getTypeOverrides().get( person ).getEvictionMaxEntries() );
			assertEquals( 60000, factory.getTypeOverrides().get( person ).getExpirationLifespan() );
			assertEquals( 30000, factory.getTypeOverrides().get( person ).getExpirationMaxIdle() );

			assertEquals( "person-addresses-cache", factory.getTypeOverrides().get( addresses ).getCacheName() );
			assertEquals( 120000, factory.getTypeOverrides().get( addresses ).getExpirationLifespan() );
			assertEquals( 60000, factory.getTypeOverrides().get( addresses ).getExpirationMaxIdle() );

			assertEquals( "my-query-cache", factory.getTypeOverrides().get( "query" ).getCacheName() );
			assertEquals( EvictionStrategy.FIFO, factory.getTypeOverrides().get( "query" ).getEvictionStrategy() );
			assertEquals( 3000, factory.getTypeOverrides().get( "query" ).getEvictionWakeUpInterval() );
			assertEquals( 10000, factory.getTypeOverrides().get( "query" ).getEvictionMaxEntries() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildEntityCollectionRegionsPersonPlusEntityCollectionOverrides() {
		final String person = "com.acme.Person";
		final String address = "com.acme.Address";
		final String car = "com.acme.Car";
		final String addresses = "com.acme.Person.addresses";
		final String parts = "com.acme.Car.parts";
		Properties p = new Properties();
		// First option, cache defined for entity and overrides for generic entity data type and entity itself.
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000" );
		p.setProperty( "hibernate.cache.infinispan.entity.cfg", "myentity-cache" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.max_entries", "20000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "addresses-cache" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.eviction.wake_up_interval", "2500" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.eviction.max_entries", "5500" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "65000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "35000" );
		p.setProperty( "hibernate.cache.infinispan.collection.cfg", "mycollection-cache" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.strategy", "LRU" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.max_entries", "25000" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );

		try {
			InfinispanRegionFactory factory = (InfinispanRegionFactory) sf.getServiceRegistry()
					.getService( RegionFactory.class );
			EmbeddedCacheManager manager = factory.getCacheManager();
			assertFalse( manager.getGlobalConfiguration().isExposeGlobalJmxStatistics() );
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertFalse( factory.getDefinedConfigurations().contains( person ) );
			assertNotNull( factory.getTypeOverrides().get( addresses ) );
			assertFalse( factory.getDefinedConfigurations().contains( addresses ) );
			CacheAdapter cache = null;

			EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion( person, p, null );
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertTrue( factory.getDefinedConfigurations().contains( person ) );
			assertNull( factory.getTypeOverrides().get( address ) );
			cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.LRU, cacheCfg.getEvictionStrategy() );
			assertEquals( 2000, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 5000, cacheCfg.getEvictionMaxEntries() );
			assertEquals( 60000, cacheCfg.getExpirationLifespan() );
			assertEquals( 30000, cacheCfg.getExpirationMaxIdle() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );

			region = (EntityRegionImpl) factory.buildEntityRegion( address, p, null );
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertTrue( factory.getDefinedConfigurations().contains( person ) );
			assertNull( factory.getTypeOverrides().get( address ) );
			cache = region.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy() );
			assertEquals( 3000, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 20000, cacheCfg.getEvictionMaxEntries() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );

			region = (EntityRegionImpl) factory.buildEntityRegion( car, p, null );
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertTrue( factory.getDefinedConfigurations().contains( person ) );
			assertNull( factory.getTypeOverrides().get( address ) );
			cache = region.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy() );
			assertEquals( 3000, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 20000, cacheCfg.getEvictionMaxEntries() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );

			CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(
					addresses,
					p,
					null
			);
			assertNotNull( factory.getTypeOverrides().get( addresses ) );
			assertTrue( factory.getDefinedConfigurations().contains( person ) );
			assertNull( factory.getTypeOverrides().get( parts ) );
			cache = collectionRegion.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy() );
			assertEquals( 2500, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 5500, cacheCfg.getEvictionMaxEntries() );
			assertEquals( 65000, cacheCfg.getExpirationLifespan() );
			assertEquals( 35000, cacheCfg.getExpirationMaxIdle() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );

			collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion( parts, p, null );
			assertNotNull( factory.getTypeOverrides().get( addresses ) );
			assertTrue( factory.getDefinedConfigurations().contains( addresses ) );
			assertNull( factory.getTypeOverrides().get( parts ) );
			cache = collectionRegion.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.LRU, cacheCfg.getEvictionStrategy() );
			assertEquals( 3500, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 25000, cacheCfg.getEvictionMaxEntries() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );

			collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion( parts, p, null );
			assertNotNull( factory.getTypeOverrides().get( addresses ) );
			assertTrue( factory.getDefinedConfigurations().contains( addresses ) );
			assertNull( factory.getTypeOverrides().get( parts ) );
			cache = collectionRegion.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.LRU, cacheCfg.getEvictionStrategy() );
			assertEquals( 3500, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 25000, cacheCfg.getEvictionMaxEntries() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildEntityCollectionRegionOverridesOnly() {
		CacheAdapter cache;
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.max_entries", "30000" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.strategy", "LRU" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500" );
		p.setProperty( "hibernate.cache.infinispan.collection.eviction.max_entries", "35000" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		factory.getCacheManager();
		try {
			EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion( "com.acme.Address", p, null );
			assertNull( factory.getTypeOverrides().get( "com.acme.Address" ) );
			cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy() );
			assertEquals( 3000, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 30000, cacheCfg.getEvictionMaxEntries() );
			assertEquals( 100000, cacheCfg.getExpirationMaxIdle() );

			CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(
					"com.acme.Person.addresses",
					p,
					null
			);
			assertNull( factory.getTypeOverrides().get( "com.acme.Person.addresses" ) );
			cache = collectionRegion.getCacheAdapter();
			cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.LRU, cacheCfg.getEvictionStrategy() );
			assertEquals( 3500, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 35000, cacheCfg.getEvictionMaxEntries() );
			assertEquals( 100000, cacheCfg.getExpirationMaxIdle() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() {
		final String person = "com.acme.Person";
		Properties p = new Properties();
		// Third option, no cache defined for entity and overrides for generic entity data type and entity itself.
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000" );
		p.setProperty( "hibernate.cache.infinispan.entity.cfg", "myentity-cache" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.max_entries", "10000" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		try {
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertFalse( factory.getDefinedConfigurations().contains( person ) );
			EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion( person, p, null );
			assertNotNull( factory.getTypeOverrides().get( person ) );
			assertTrue( factory.getDefinedConfigurations().contains( person ) );
			CacheAdapter cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.LRU, cacheCfg.getEvictionStrategy() );
			assertEquals( 3000, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 10000, cacheCfg.getEvictionMaxEntries() );
			assertEquals( 60000, cacheCfg.getExpirationLifespan() );
			assertEquals( 30000, cacheCfg.getExpirationMaxIdle() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testTimestampValidation() {
		Properties p = new Properties();
		final DefaultCacheManager manager = new DefaultCacheManager();
		SessionFactoryImplementor sf = null;
		try {
			sf = createSessionFactory( manager, p );
			InfinispanRegionFactory factory = (InfinispanRegionFactory) sf.getServiceRegistry()
					.getService( RegionFactory.class );
			Configuration config = new Configuration();
			config.setCacheMode( CacheMode.INVALIDATION_SYNC );
			manager.defineConfiguration( "timestamps", config );

			factory.start( null, p );
			fail( "Should have failed saying that invalidation is not allowed for timestamp caches." );
		}
		catch ( CacheException ce ) {
		}
		finally {
			if ( sf != null ) {
				sf.close();
			}
		}
	}

	@Test
	public void testBuildDefaultTimestampsRegion() {
		final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
		Properties p = new Properties();
		SessionFactoryImplementor sf = createSessionFactory( null, p );

		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		try {
			assertTrue( factory.getDefinedConfigurations().contains( "timestamps" ) );
			assertTrue( factory.getTypeOverrides().get( "timestamps" ).getCacheName().equals( "timestamps" ) );
			Configuration config = new Configuration();
			config.setFetchInMemoryState( false );
			manager.defineConfiguration( "timestamps", config );
			TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion( timestamps, p );
			CacheAdapter cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.NONE, cacheCfg.getEvictionStrategy() );
			assertEquals( CacheMode.REPL_ASYNC, cacheCfg.getCacheMode() );
			assertTrue( cacheCfg.isUseLazyDeserialization() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildDiffCacheNameTimestampsRegion() {
		final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );

		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		try {
			assertFalse( factory.getDefinedConfigurations().contains( "timestamp" ) );
			assertTrue( factory.getDefinedConfigurations().contains( "unrecommended-timestamps" ) );
			assertTrue(
					factory.getTypeOverrides()
							.get( "timestamps" )
							.getCacheName()
							.equals( "unrecommended-timestamps" )
			);
			Configuration config = new Configuration();
			config.setFetchInMemoryState( false );
			config.setCacheMode( CacheMode.REPL_SYNC );
			manager.defineConfiguration( "unrecommended-timestamps", config );
			TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion( timestamps, p );
			CacheAdapter cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.NONE, cacheCfg.getEvictionStrategy() );
			assertEquals( CacheMode.REPL_SYNC, cacheCfg.getCacheMode() );
			assertFalse( cacheCfg.isUseLazyDeserialization() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildTimestamRegionWithCacheNameOverride() {
		final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		try {
			factory.buildTimestampsRegion( timestamps, p );
			assertTrue( factory.getDefinedConfigurations().contains( "mytimestamps-cache" ) );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildTimestamRegionWithFifoEvictionOverride() {
		final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000" );
		InfinispanRegionFactory factory = null;
		SessionFactoryImplementor sf = null;
		try {
			sf = createSessionFactory( null, p );
			factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
			factory.buildTimestampsRegion( timestamps, p );
			assertTrue( factory.getDefinedConfigurations().contains( "mytimestamps-cache" ) );
			fail( "Should fail cos no eviction configurations are allowed for timestamp caches" );
		}
		catch ( CacheException ce ) {
		}
		finally {
			if ( sf != null ) {
				sf.close();
			}
		}
	}

	@Test
	public void testBuildTimestamRegionWithNoneEvictionOverride() {
		final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.timestamps.cfg", "timestamps-none-eviction" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.strategy", "NONE" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		manager.getGlobalConfiguration().setTransportClass( null );
		try {
			factory.buildTimestampsRegion( timestamps, p );
			assertTrue( factory.getDefinedConfigurations().contains( "timestamps-none-eviction" ) );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildQueryRegion() {
		final String query = "org.hibernate.cache.internal.StandardQueryCache";
		Properties p = new Properties();
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		manager.getGlobalConfiguration().setTransportClass( null );
		try {
			assertTrue( factory.getDefinedConfigurations().contains( "local-query" ) );
			QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion( query, p );
			CacheAdapter cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( CacheMode.LOCAL, cacheCfg.getCacheMode() );
			assertFalse( cacheCfg.isExposeJmxStatistics() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testBuildQueryRegionWithCustomRegionName() {
		final String queryRegionName = "myquery";
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.myquery.cfg", "timestamps-none-eviction" );
		p.setProperty( "hibernate.cache.infinispan.myquery.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.myquery.eviction.wake_up_interval", "2222" );
		p.setProperty( "hibernate.cache.infinispan.myquery.eviction.max_entries", "11111" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );

		InfinispanRegionFactory factory = ( InfinispanRegionFactory )sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		manager.getGlobalConfiguration().setTransportClass( null );
		try {
			assertTrue( factory.getDefinedConfigurations().contains( "local-query" ) );
			QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(
					queryRegionName,
					p
			);
			assertNotNull( factory.getTypeOverrides().get( queryRegionName ) );
			assertTrue( factory.getDefinedConfigurations().contains( queryRegionName ) );
			CacheAdapter cache = region.getCacheAdapter();
			Configuration cacheCfg = cache.getConfiguration();
			assertEquals( EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy() );
			assertEquals( 2222, cacheCfg.getEvictionWakeUpInterval() );
			assertEquals( 11111, cacheCfg.getEvictionMaxEntries() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testEnableStatistics() {
		Properties p = new Properties();
		p.setProperty( InfinispanRegionFactory.INFINISPAN_GLOBAL_STATISTICS_PROP, "true" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000" );
		p.setProperty( "hibernate.cache.infinispan.entity.cfg", "myentity-cache" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.max_entries", "10000" );
		SessionFactoryImplementor sf = createSessionFactory( null, p );
		InfinispanRegionFactory factory = (InfinispanRegionFactory)sf.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		try {
			assertTrue( manager.getGlobalConfiguration().isExposeGlobalJmxStatistics() );
			EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion( "com.acme.Address", p, null );
			CacheAdapter cache = region.getCacheAdapter();
			assertTrue( factory.getTypeOverrides().get( "entity" ).isExposeStatistics() );
			assertTrue( cache.getConfiguration().isExposeJmxStatistics() );

			region = (EntityRegionImpl) factory.buildEntityRegion( "com.acme.Person", p, null );
			cache = region.getCacheAdapter();
			assertTrue( factory.getTypeOverrides().get( "com.acme.Person" ).isExposeStatistics() );
			assertTrue( cache.getConfiguration().isExposeJmxStatistics() );

			final String query = "org.hibernate.cache.internal.StandardQueryCache";
			QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion( query, p );
			cache = queryRegion.getCacheAdapter();
			assertTrue( factory.getTypeOverrides().get( "query" ).isExposeStatistics() );
			assertTrue( cache.getConfiguration().isExposeJmxStatistics() );

			final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
			Configuration config = new Configuration();
			config.setFetchInMemoryState( false );
			manager.defineConfiguration( "timestamps", config );
			TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(
					timestamps,
					p
			);
			cache = timestampsRegion.getCacheAdapter();
			assertTrue( factory.getTypeOverrides().get( "timestamps" ).isExposeStatistics() );
			assertTrue( cache.getConfiguration().isExposeJmxStatistics() );

			CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(
					"com.acme.Person.addresses",
					p,
					null
			);
			cache = collectionRegion.getCacheAdapter();
			assertTrue( factory.getTypeOverrides().get( "collection" ).isExposeStatistics() );
			assertTrue( cache.getConfiguration().isExposeJmxStatistics() );
		}
		finally {
			sf.close();
		}
	}

	@Test
	public void testDisableStatistics() {
		Properties p = new Properties();
		p.setProperty( "hibernate.cache.infinispan.statistics", "false" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000" );
		p.setProperty( "hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000" );
		p.setProperty( "hibernate.cache.infinispan.entity.cfg", "myentity-cache" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.strategy", "FIFO" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000" );
		p.setProperty( "hibernate.cache.infinispan.entity.eviction.max_entries", "10000" );
		SessionFactoryImplementor sessionFactoryImplementor = createSessionFactory( null, p );
		InfinispanRegionFactory factory = ( InfinispanRegionFactory )sessionFactoryImplementor.getServiceRegistry().getService( RegionFactory.class );
		EmbeddedCacheManager manager = factory.getCacheManager();
		try {
			assertFalse( manager.getGlobalConfiguration().isExposeGlobalJmxStatistics() );
			EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion( "com.acme.Address", p, null );
			CacheAdapter cache = region.getCacheAdapter();
			assertFalse( factory.getTypeOverrides().get( "entity" ).isExposeStatistics() );
			assertFalse( cache.getConfiguration().isExposeJmxStatistics() );

			region = (EntityRegionImpl) factory.buildEntityRegion( "com.acme.Person", p, null );
			cache = region.getCacheAdapter();
			assertFalse( factory.getTypeOverrides().get( "com.acme.Person" ).isExposeStatistics() );
			assertFalse( cache.getConfiguration().isExposeJmxStatistics() );

			final String query = "org.hibernate.cache.internal.StandardQueryCache";
			QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion( query, p );
			cache = queryRegion.getCacheAdapter();
			assertFalse( factory.getTypeOverrides().get( "query" ).isExposeStatistics() );
			assertFalse( cache.getConfiguration().isExposeJmxStatistics() );

			final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
			Configuration config = new Configuration();
			config.setFetchInMemoryState( false );
			manager.defineConfiguration( "timestamps", config );
			TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(
					timestamps,
					p
			);
			cache = timestampsRegion.getCacheAdapter();
			assertFalse( factory.getTypeOverrides().get( "timestamps" ).isExposeStatistics() );
			assertFalse( cache.getConfiguration().isExposeJmxStatistics() );

			CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(
					"com.acme.Person.addresses",
					p,
					null
			);
			cache = collectionRegion.getCacheAdapter();
			assertFalse( factory.getTypeOverrides().get( "collection" ).isExposeStatistics() );
			assertFalse( cache.getConfiguration().isExposeJmxStatistics() );
		}
		finally {
			sessionFactoryImplementor.close();
		}
	}

	private SessionFactoryImplementor createSessionFactory(final EmbeddedCacheManager manager, Properties p) {
		Properties properties = new Properties();
		properties.putAll( p );
		properties.put(
				RegionFactoryInitiator.IMPL_NAME,
				new InfinispanRegionFactory() {
					@Override
					protected EmbeddedCacheManager createCacheManager() throws CacheException {
						if ( manager != null ) {
							return manager;
						}
						else {
							return super.createCacheManager();
						}
					}
				}
		);
		properties.put( AvailableSettings.JTA_PLATFORM, JBossStandAloneJtaPlatform.class.getName() );
		org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
		cfg.setProperties( properties );
		ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( properties );
		return (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry );
	}

=======
public class InfinispanRegionFactoryTestCase  {

   @Test
   public void testConfigurationProcessing() {
      final String person = "com.acme.Person";
      final String addresses = "com.acme.Person.addresses";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "person-addresses-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "120000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "60000");
      p.setProperty("hibernate.cache.infinispan.query.cfg", "my-query-cache");
      p.setProperty("hibernate.cache.infinispan.query.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.query.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.query.eviction.max_entries", "10000");

      InfinispanRegionFactory factory = createRegionFactory(p);

      try {
         assertEquals("entity", factory.getTypeOverrides().get("entity").getCacheName());
         assertEquals("entity", factory.getTypeOverrides().get("collection").getCacheName());
         assertEquals("timestamps", factory.getTypeOverrides().get("timestamps").getCacheName());

         assertEquals("person-cache", factory.getTypeOverrides().get(person).getCacheName());
         assertEquals(EvictionStrategy.LRU, factory.getTypeOverrides().get(person).getEvictionStrategy());
         assertEquals(2000, factory.getTypeOverrides().get(person).getEvictionWakeUpInterval());
         assertEquals(5000, factory.getTypeOverrides().get(person).getEvictionMaxEntries());
         assertEquals(60000, factory.getTypeOverrides().get(person).getExpirationLifespan());
         assertEquals(30000, factory.getTypeOverrides().get(person).getExpirationMaxIdle());

         assertEquals("person-addresses-cache", factory.getTypeOverrides().get(addresses).getCacheName());
         assertEquals(120000, factory.getTypeOverrides().get(addresses).getExpirationLifespan());
         assertEquals(60000, factory.getTypeOverrides().get(addresses).getExpirationMaxIdle());

         assertEquals("my-query-cache", factory.getTypeOverrides().get("query").getCacheName());
         assertEquals(EvictionStrategy.LIRS, factory.getTypeOverrides().get("query").getEvictionStrategy());
         assertEquals(3000, factory.getTypeOverrides().get("query").getEvictionWakeUpInterval());
         assertEquals(10000, factory.getTypeOverrides().get("query").getEvictionMaxEntries());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildEntityCollectionRegionsPersonPlusEntityCollectionOverrides() {
      final String person = "com.acme.Person";
      final String address = "com.acme.Address";
      final String car = "com.acme.Car";
      final String addresses = "com.acme.Person.addresses";
      final String parts = "com.acme.Car.parts";
      Properties p = new Properties();
      // First option, cache defined for entity and overrides for generic entity data type and entity itself.
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "20000");
   }
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "addresses-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.wake_up_interval", "2500");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.max_entries", "5500");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "65000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "35000");
      p.setProperty("hibernate.cache.infinispan.collection.cfg", "mycollection-cache");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "25000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertFalse(manager.getCacheManagerConfiguration()
               .globalJmxStatistics().enabled());
         assertNotNull(factory.getTypeOverrides().get(person));
         assertFalse(factory.getDefinedConfigurations().contains(person));
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertFalse(factory.getDefinedConfigurations().contains(addresses));
         AdvancedCache cache;

         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(2000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(5000, cacheCfg.eviction().maxEntries());
         assertEquals(60000, cacheCfg.expiration().lifespan());
         assertEquals(30000, cacheCfg.expiration().maxIdle());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion(address, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(20000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion(car, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(20000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion(addresses, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion .getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(2500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(5500, cacheCfg.eviction().maxEntries());
         assertEquals(65000, cacheCfg.expiration().lifespan());
         assertEquals(35000, cacheCfg.expiration().maxIdle());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(addresses));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(25000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(addresses));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(25000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildEntityCollectionRegionOverridesOnly() {
      AdvancedCache cache;
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "30000");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "35000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.getCacheManager();
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         assertNull(factory.getTypeOverrides().get("com.acme.Address"));
         cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(30000, cacheCfg.eviction().maxEntries());
         // Max idle value comes from base XML configuration
         assertEquals(100000, cacheCfg.expiration().maxIdle());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         assertNull(factory.getTypeOverrides().get("com.acme.Person.addresses"));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(35000, cacheCfg.eviction().maxEntries());
         assertEquals(100000, cacheCfg.expiration().maxIdle());
      } finally {
         factory.stop();
      }
   }
   @Test
   public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() {
      final String person = "com.acme.Person";
      Properties p = new Properties();
      // Third option, no cache defined for entity and overrides for generic entity data type and entity itself.
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.getCacheManager();
         assertNotNull(factory.getTypeOverrides().get(person));
         assertFalse(factory.getDefinedConfigurations().contains(person));
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(10000, cacheCfg.eviction().maxEntries());
         assertEquals(60000, cacheCfg.expiration().lifespan());
         assertEquals(30000, cacheCfg.expiration().maxIdle());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testTimestampValidation() {
      Properties p = new Properties();
      final DefaultCacheManager manager = new DefaultCacheManager();
      InfinispanRegionFactory factory = createRegionFactory(manager, p);
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.clustering().cacheMode(CacheMode.INVALIDATION_SYNC);
      manager.defineConfiguration("timestamps", builder.build());
      try {
         factory.start(null, p);
         fail("Should have failed saying that invalidation is not allowed for timestamp caches.");
      } catch(CacheException ce) {
      }

   @Test
   public void testBuildDefaultTimestampsRegion() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("timestamps"));
         assertTrue(factory.getTypeOverrides().get("timestamps")
               .getCacheName().equals("timestamps"));
         TimestampsRegionImpl region = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy());
         assertEquals(CacheMode.REPL_ASYNC, cacheCfg.clustering().cacheMode());
         assertTrue(cacheCfg.storeAsBinary().enabled());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildDiffCacheNameTimestampsRegion() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertFalse(factory.getDefinedConfigurations().contains("timestamp"));
         assertTrue(factory.getDefinedConfigurations().contains("unrecommended-timestamps"));
         assertTrue(factory.getTypeOverrides().get("timestamps").getCacheName().equals("unrecommended-timestamps"));
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         builder.clustering().cacheMode(CacheMode.REPL_SYNC);
         manager.defineConfiguration("unrecommended-timestamps", builder.build());
         TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy());
         assertEquals(CacheMode.REPL_SYNC, cacheCfg.clustering().cacheMode());
         assertFalse(cacheCfg.storeAsBinary().enabled());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithCacheNameOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache"));
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithFifoEvictionOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = null;
      try {
         factory = createRegionFactory(p);
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache"));
         fail("Should fail cos no eviction configurations are allowed for timestamp caches");
      } catch(CacheException ce) {
      } finally {
         if (factory != null) factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithNoneEvictionOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "timestamps-none-eviction");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "NONE");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "0");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("timestamps-none-eviction"));
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildQueryRegion() {
      final String query = "org.hibernate.cache.internal.StandardQueryCache";
      Properties p = new Properties();
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("local-query"));
         QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(CacheMode.LOCAL, cacheCfg.clustering().cacheMode());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildQueryRegionWithCustomRegionName() {
      final String queryRegionName = "myquery";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.myquery.cfg", "timestamps-none-eviction");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.wake_up_interval", "2222");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.max_entries", "11111");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("local-query"));
         QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(queryRegionName, p);
         assertNotNull(factory.getTypeOverrides().get(queryRegionName));
         assertTrue(factory.getDefinedConfigurations().contains(queryRegionName));
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(2222, cacheCfg.expiration().wakeUpInterval());
         assertEquals(11111, cacheCfg.eviction().maxEntries());
      } finally {
         factory.stop();
      }
   }
   @Test
   public void testEnableStatistics() {
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.statistics", "true");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertTrue(manager.getCacheManagerConfiguration().globalJmxStatistics().enabled());
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         AdvancedCache cache = region.getCache();
         assertTrue(factory.getTypeOverrides().get("entity").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
         cache = region.getCache();
         assertTrue(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String query = "org.hibernate.cache.internal.StandardQueryCache";
         QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl)
               factory.buildQueryResultsRegion(query, p);
         cache = queryRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("query").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         manager.defineConfiguration("timestamps", builder.build());
         TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         cache = timestampsRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         cache = collectionRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("collection").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testDisableStatistics() {
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.statistics", "false");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         AdvancedCache cache = region.getCache();
         assertFalse(factory.getTypeOverrides().get("entity").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
         cache = region.getCache();
         assertFalse(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String query = "org.hibernate.cache.internal.StandardQueryCache";
         QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
         cache = queryRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("query").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         factory.getCacheManager().defineConfiguration("timestamps", builder.build());
         TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         cache = timestampsRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         cache = collectionRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("collection").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   private InfinispanRegionFactory createRegionFactory(Properties p) {
      return createRegionFactory(null, p);
   }

   private InfinispanRegionFactory createRegionFactory(final EmbeddedCacheManager manager, Properties p) {
      final InfinispanRegionFactory factory = new SingleNodeTestCase.TestInfinispanRegionFactory() {

         @Override
         protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup(Settings settings, Properties properties) {
            return new HibernateTransactionManagerLookup(null, null) {
               @Override
               public TransactionManager getTransactionManager() throws Exception {
                  AbstractJtaPlatform jta = new JBossStandAloneJtaPlatform();
                  jta.injectServices(ServiceRegistryBuilder.buildServiceRegistry());
                  return jta.getTransactionManager();
               }
            };
         }

         @Override
         protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException {
            if (manager != null)
               return manager;
            else
               return super.createCacheManager(properties);
         }

      };

      factory.start(null, p);
      return factory;
   }
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

}
Solution content
 * @author Galder Zamarreño
 * @since 3.5
 */
public class InfinispanRegionFactoryTestCase  {

   @Test
   public void testConfigurationProcessing() {
      final String person = "com.acme.Person";
      final String addresses = "com.acme.Person.addresses";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "person-addresses-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "120000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "60000");
      p.setProperty("hibernate.cache.infinispan.query.cfg", "my-query-cache");
      p.setProperty("hibernate.cache.infinispan.query.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.query.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.query.eviction.max_entries", "10000");

      InfinispanRegionFactory factory = createRegionFactory(p);

      try {
         assertEquals("entity", factory.getTypeOverrides().get("entity").getCacheName());
         assertEquals("entity", factory.getTypeOverrides().get("collection").getCacheName());
         assertEquals("timestamps", factory.getTypeOverrides().get("timestamps").getCacheName());

         assertEquals("person-cache", factory.getTypeOverrides().get(person).getCacheName());
         assertEquals(EvictionStrategy.LRU, factory.getTypeOverrides().get(person).getEvictionStrategy());
         assertEquals(2000, factory.getTypeOverrides().get(person).getEvictionWakeUpInterval());
         assertEquals(5000, factory.getTypeOverrides().get(person).getEvictionMaxEntries());
         assertEquals(60000, factory.getTypeOverrides().get(person).getExpirationLifespan());
         assertEquals(30000, factory.getTypeOverrides().get(person).getExpirationMaxIdle());

         assertEquals("person-addresses-cache", factory.getTypeOverrides().get(addresses).getCacheName());
         assertEquals(120000, factory.getTypeOverrides().get(addresses).getExpirationLifespan());
         assertEquals(60000, factory.getTypeOverrides().get(addresses).getExpirationMaxIdle());

         assertEquals("my-query-cache", factory.getTypeOverrides().get("query").getCacheName());
         assertEquals(EvictionStrategy.LIRS, factory.getTypeOverrides().get("query").getEvictionStrategy());
         assertEquals(3000, factory.getTypeOverrides().get("query").getEvictionWakeUpInterval());
         assertEquals(10000, factory.getTypeOverrides().get("query").getEvictionMaxEntries());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildEntityCollectionRegionsPersonPlusEntityCollectionOverrides() {
      final String person = "com.acme.Person";
      final String address = "com.acme.Address";
      final String car = "com.acme.Car";
      final String addresses = "com.acme.Person.addresses";
      final String parts = "com.acme.Car.parts";
      Properties p = new Properties();
      // First option, cache defined for entity and overrides for generic entity data type and entity itself.
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.wake_up_interval", "2000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.max_entries", "5000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "20000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "addresses-cache");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.wake_up_interval", "2500");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.eviction.max_entries", "5500");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "65000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "35000");
      p.setProperty("hibernate.cache.infinispan.collection.cfg", "mycollection-cache");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "25000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertFalse(manager.getCacheManagerConfiguration()
               .globalJmxStatistics().enabled());
         assertNotNull(factory.getTypeOverrides().get(person));
         assertFalse(factory.getDefinedConfigurations().contains(person));
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertFalse(factory.getDefinedConfigurations().contains(addresses));
         AdvancedCache cache;

         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(2000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(5000, cacheCfg.eviction().maxEntries());
         assertEquals(60000, cacheCfg.expiration().lifespan());
         assertEquals(30000, cacheCfg.expiration().maxIdle());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion(address, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(20000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion(car, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(address));
         cache = region.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(20000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion(addresses, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion .getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(2500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(5500, cacheCfg.eviction().maxEntries());
         assertEquals(65000, cacheCfg.expiration().lifespan());
         assertEquals(35000, cacheCfg.expiration().maxIdle());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(addresses));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(25000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());

         collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
         assertNotNull(factory.getTypeOverrides().get(addresses));
         assertTrue(factory.getDefinedConfigurations().contains(addresses));
         assertNull(factory.getTypeOverrides().get(parts));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(25000, cacheCfg.eviction().maxEntries());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildEntityCollectionRegionOverridesOnly() {
      AdvancedCache cache;
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "30000");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500");
      p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "35000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.getCacheManager();
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         assertNull(factory.getTypeOverrides().get("com.acme.Address"));
         cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(30000, cacheCfg.eviction().maxEntries());
         // Max idle value comes from base XML configuration
         assertEquals(100000, cacheCfg.expiration().maxIdle());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         assertNull(factory.getTypeOverrides().get("com.acme.Person.addresses"));
         cache = collectionRegion.getCache();
         cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
         assertEquals(35000, cacheCfg.eviction().maxEntries());
         assertEquals(100000, cacheCfg.expiration().maxIdle());
      } finally {
         factory.stop();
      }
   }
   @Test
   public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() {
      final String person = "com.acme.Person";
      Properties p = new Properties();
      // Third option, no cache defined for entity and overrides for generic entity data type and entity itself.
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.getCacheManager();
         assertNotNull(factory.getTypeOverrides().get(person));
         assertFalse(factory.getDefinedConfigurations().contains(person));
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null);
         assertNotNull(factory.getTypeOverrides().get(person));
         assertTrue(factory.getDefinedConfigurations().contains(person));
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy());
         assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
         assertEquals(10000, cacheCfg.eviction().maxEntries());
         assertEquals(60000, cacheCfg.expiration().lifespan());
         assertEquals(30000, cacheCfg.expiration().maxIdle());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testTimestampValidation() {
      Properties p = new Properties();
      final DefaultCacheManager manager = new DefaultCacheManager();
      InfinispanRegionFactory factory = createRegionFactory(manager, p);
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.clustering().cacheMode(CacheMode.INVALIDATION_SYNC);
      manager.defineConfiguration("timestamps", builder.build());
      try {
         factory.start(null, p);
         fail("Should have failed saying that invalidation is not allowed for timestamp caches.");
      } catch(CacheException ce) {
      }
   }

   @Test
   public void testBuildDefaultTimestampsRegion() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("timestamps"));
         assertTrue(factory.getTypeOverrides().get("timestamps")
               .getCacheName().equals("timestamps"));
         TimestampsRegionImpl region = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy());
         assertEquals(CacheMode.REPL_ASYNC, cacheCfg.clustering().cacheMode());
         assertTrue(cacheCfg.storeAsBinary().enabled());
         @Override
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildDiffCacheNameTimestampsRegion() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "unrecommended-timestamps");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertFalse(factory.getDefinedConfigurations().contains("timestamp"));
         assertTrue(factory.getDefinedConfigurations().contains("unrecommended-timestamps"));
         assertTrue(factory.getTypeOverrides().get("timestamps").getCacheName().equals("unrecommended-timestamps"));
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         builder.clustering().cacheMode(CacheMode.REPL_SYNC);
         manager.defineConfiguration("unrecommended-timestamps", builder.build());
         TimestampsRegionImpl region = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.NONE, cacheCfg.eviction().strategy());
         assertEquals(CacheMode.REPL_SYNC, cacheCfg.clustering().cacheMode());
         assertFalse(cacheCfg.storeAsBinary().enabled());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithCacheNameOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache"));
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithFifoEvictionOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "mytimestamps-cache");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = null;
      try {
         factory = createRegionFactory(p);
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("mytimestamps-cache"));
         fail("Should fail cos no eviction configurations are allowed for timestamp caches");
      } catch(CacheException ce) {
      } finally {
         if (factory != null) factory.stop();
      }
   }

   @Test
   public void testBuildTimestamRegionWithNoneEvictionOverride() {
      final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.timestamps.cfg", "timestamps-none-eviction");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.strategy", "NONE");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.timestamps.eviction.max_entries", "0");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         factory.buildTimestampsRegion(timestamps, p);
         assertTrue(factory.getDefinedConfigurations().contains("timestamps-none-eviction"));
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildQueryRegion() {
      final String query = "org.hibernate.cache.internal.StandardQueryCache";
      Properties p = new Properties();
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("local-query"));
         QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(CacheMode.LOCAL, cacheCfg.clustering().cacheMode());
         assertFalse(cacheCfg.jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testBuildQueryRegionWithCustomRegionName() {
      final String queryRegionName = "myquery";
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.myquery.cfg", "timestamps-none-eviction");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.strategy", "LIRS");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.wake_up_interval", "2222");
      p.setProperty("hibernate.cache.infinispan.myquery.eviction.max_entries", "11111");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         assertTrue(factory.getDefinedConfigurations().contains("local-query"));
         QueryResultsRegionImpl region = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(queryRegionName, p);
         assertNotNull(factory.getTypeOverrides().get(queryRegionName));
         assertTrue(factory.getDefinedConfigurations().contains(queryRegionName));
         AdvancedCache cache = region.getCache();
         Configuration cacheCfg = cache.getCacheConfiguration();
         assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy());
         assertEquals(2222, cacheCfg.expiration().wakeUpInterval());
         assertEquals(11111, cacheCfg.eviction().maxEntries());
      } finally {
         factory.stop();
      }
   }
   @Test
   public void testEnableStatistics() {
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.statistics", "true");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EmbeddedCacheManager manager = factory.getCacheManager();
         assertTrue(manager.getCacheManagerConfiguration().globalJmxStatistics().enabled());
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         AdvancedCache cache = region.getCache();
         assertTrue(factory.getTypeOverrides().get("entity").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
         cache = region.getCache();
         assertTrue(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String query = "org.hibernate.cache.internal.StandardQueryCache";
         QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl)
               factory.buildQueryResultsRegion(query, p);
         cache = queryRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("query").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         manager.defineConfiguration("timestamps", builder.build());
         TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         cache = timestampsRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         cache = collectionRegion.getCache();
         assertTrue(factory.getTypeOverrides().get("collection").isExposeStatistics());
         assertTrue(cache.getCacheConfiguration().jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }

   @Test
   public void testDisableStatistics() {
      Properties p = new Properties();
      p.setProperty("hibernate.cache.infinispan.statistics", "false");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
      p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
      p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
      p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
      InfinispanRegionFactory factory = createRegionFactory(p);
      try {
         EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
         AdvancedCache cache = region.getCache();
         assertFalse(factory.getTypeOverrides().get("entity").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
         cache = region.getCache();
         assertFalse(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String query = "org.hibernate.cache.internal.StandardQueryCache";
         QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
         cache = queryRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("query").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
         ConfigurationBuilder builder = new ConfigurationBuilder();
         builder.clustering().stateTransfer().fetchInMemoryState(true);
         factory.getCacheManager().defineConfiguration("timestamps", builder.build());
         TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl)
               factory.buildTimestampsRegion(timestamps, p);
         cache = timestampsRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());

         CollectionRegionImpl collectionRegion = (CollectionRegionImpl)
               factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
         cache = collectionRegion.getCache();
         assertFalse(factory.getTypeOverrides().get("collection").isExposeStatistics());
         assertFalse(cache.getCacheConfiguration().jmxStatistics().enabled());
      } finally {
         factory.stop();
      }
   }
   private InfinispanRegionFactory createRegionFactory(Properties p) {
      return createRegionFactory(null, p);
   }

   private InfinispanRegionFactory createRegionFactory(final EmbeddedCacheManager manager, Properties p) {
      final InfinispanRegionFactory factory = new SingleNodeTestCase.TestInfinispanRegionFactory() {

         @Override
         protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup(ServiceRegistry sr) {
            return new HibernateTransactionManagerLookup(null, null) {
               @Override
               public TransactionManager getTransactionManager() throws Exception {
                  AbstractJtaPlatform jta = new JBossStandAloneJtaPlatform();
                  jta.injectServices(ServiceRegistryBuilder.buildServiceRegistry());
                  return jta.getTransactionManager();
               }
            };
         }

         protected EmbeddedCacheManager createCacheManager(Map properties) throws CacheException {
            if (manager != null)
               return manager;
            else
               return super.createCacheManager(properties);
         }

      };

      factory.start(null, p);
      return factory;
   }

}
File
InfinispanRegionFactoryTestCase.java
Developer's decision
Manual
Kind of conflict
Annotation
Class signature
Method declaration
Chunk
Conflicting content
 */
public class NodeEnvironment {

<<<<<<< HEAD
	private StandardServiceRegistryImpl serviceRegistry;
	private InfinispanRegionFactory regionFactory;
	private SessionFactoryImplementor sessionFactory;
=======
   private final Configuration configuration;

   private StandardServiceRegistryImpl serviceRegistry;
   private InfinispanRegionFactory regionFactory;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

   private Map entityRegionMap;
   private Map collectionRegionMap;
Solution content
 */
public class NodeEnvironment {

   private final Configuration configuration;
   private StandardServiceRegistryImpl serviceRegistry;
   private InfinispanRegionFactory regionFactory;

   private Map entityRegionMap;
   private Map collectionRegionMap;
File
NodeEnvironment.java
Developer's decision
Version 2
Kind of conflict
Attribute
Chunk
Conflicting content
      return region;
   }

<<<<<<< HEAD
	public void prepare() throws Exception {
		serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
				.applySettings( configuration.getProperties() )
				.build();
		sessionFactory = (SessionFactoryImplementor)configuration.buildSessionFactory( serviceRegistry );
		regionFactory = (InfinispanRegionFactory)sessionFactory.getServiceRegistry().getService( RegionFactory.class );
	}
=======
   public void prepare() throws Exception {
      serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .buildServiceRegistry();
      regionFactory = CacheTestUtil.startRegionFactory(serviceRegistry, configuration);
   }
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454

   public void release() throws Exception {
      try {
Solution content
      return region;
   }

   public void prepare() throws Exception {
      serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .build();
      regionFactory = CacheTestUtil.startRegionFactory(serviceRegistry, configuration);
   }

   public void release() throws Exception {
      try {
File
NodeEnvironment.java
Developer's decision
Combination
Kind of conflict
Method declaration
Chunk
Conflicting content
               } catch (Exception e) {
                  // Ignore...
               }
<<<<<<< HEAD
            });
				collectionRegion.getCacheAdapter().stop();
			}
			collectionRegionMap.clear();
		}
		if ( sessionFactory != null ) {
			sessionFactory.close();
		}
		if ( serviceRegistry != null ) {
			serviceRegistry.destroy();
		}
	}
=======
            }
            collectionRegionMap.clear();
         }
      } finally {
         try {
            if (regionFactory != null) {
               // Currently the RegionFactory is shutdown by its registration
               // with the CacheTestSetup from CacheTestUtil when built
               regionFactory.stop();
            }
         } finally {
            if (serviceRegistry != null) {
               serviceRegistry.destroy();
            }
         }
      }
   }
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
}
Solution content
               } catch (Exception e) {
                  // Ignore...
               }

            }
            collectionRegionMap.clear();
         }
      } finally {
         try {
            if (regionFactory != null) {
               // Currently the RegionFactory is shutdown by its registration
               // with the CacheTestSetup from CacheTestUtil when built
               regionFactory.stop();
            }
         } finally {
            if (serviceRegistry != null) {
               serviceRegistry.destroy();
            }
         }
      }
   }
}
File
NodeEnvironment.java
Developer's decision
Version 2
Kind of conflict
If statement
Method invocation
Try statement
Chunk
Conflicting content
   public static class MockInfinispanRegionFactory extends SingleNodeTestCase.TestInfinispanRegionFactory {

<<<<<<< HEAD
=======
      public MockInfinispanRegionFactory() {
      }

//      @Override
//      protected TimestampsRegionImpl createTimestampsRegion(CacheAdapter cacheAdapter, String regionName) {
//         return new MockTimestampsRegionImpl(cacheAdapter, regionName, getTransactionManager(), this);
//      }

>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
      @Override
      protected AdvancedCache createCacheWrapper(AdvancedCache cache) {
         return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()) {
Solution content
   public static class MockInfinispanRegionFactory extends SingleNodeTestCase.TestInfinispanRegionFactory {

      public MockInfinispanRegionFactory() {
      }

//      @Override
//      protected TimestampsRegionImpl createTimestampsRegion(CacheAdapter cacheAdapter, String regionName) {
//         return new MockTimestampsRegionImpl(cacheAdapter, regionName, getTransactionManager(), this);
//      }

      @Override
      protected AdvancedCache createCacheWrapper(AdvancedCache cache) {
         return new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()) {
File
TimestampsRegionImplTestCase.java
Developer's decision
Version 2
Kind of conflict
Comment
Method declaration
Chunk
Conflicting content
import javax.transaction.Status;
import javax.transaction.UserTransaction;

<<<<<<< HEAD
=======
import org.infinispan.configuration.cache.ConfigurationBuilder;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
Solution content
   }

   @Test
/**
import javax.transaction.Status;
import javax.transaction.UserTransaction;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.transaction.jta.platform.internal.JBossStandAloneJtaPlatform;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.stat.Statistics;
import org.hibernate.test.cache.infinispan.functional.Item;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.jta.JtaAwareConnectionProviderImpl;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jboss.util.naming.NonSerializableFactory;
import org.jnp.interfaces.NamingContext;
import org.jnp.server.Main;
import org.jnp.server.NamingServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 * This is an example test based on http://community.jboss.org/docs/DOC-14617 that shows how to interact with
 * Hibernate configured with Infinispan second level cache provider using JTA transactions.
 *
 * In this test, an XADataSource wrapper is in use where we have associated our transaction manager to it so that
 * commits/rollbacks are propagated to the database as well.
 *
 * @author Galder Zamarreño
 * @since 3.5
 */
public class JBossStandaloneJtaExampleTest {
   private static final Log log = LogFactory.getLog(JBossStandaloneJtaExampleTest.class);
   private static final JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup();
   Context ctx;
   Main jndiServer;
   private ServiceRegistry serviceRegistry;


   @Before
   public void setUp() throws Exception {
      jndiServer = startJndiServer();
      ctx = createJndiContext();
      // Inject configuration to initialise transaction manager from config classloader
      lookup.init(new ConfigurationBuilder().build());
      bindTransactionManager();
      bindUserTransaction();
   }

   @After
   public void tearDown() throws Exception {
      try {
         unbind("UserTransaction", ctx);
         unbind("java:/TransactionManager", ctx);
         ctx.close();
         jndiServer.stop();
	  }
	  finally {
		  if ( serviceRegistry != null ) {
			  ServiceRegistryBuilder.destroy( serviceRegistry );
		  }
	  }
   public void testPersistAndLoadUnderJta() throws Exception {
      Item item;
      SessionFactory sessionFactory = buildSessionFactory();
      try {
         UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
         ut.begin();
         try {
            Session session = sessionFactory.openSession();
            session.getTransaction().begin();
            item = new Item("anItem", "An item owned by someone");
            session.persist(item);
            session.getTransaction().commit();
            session.close();
         } catch(Exception e) {
            ut.setRollbackOnly();
            throw e;
         } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
               ut.commit();
            else
               ut.rollback();
         }

         ut = (UserTransaction) ctx.lookup("UserTransaction");
         ut.begin();
         try {
            Session session = sessionFactory.openSession();
            session.getTransaction().begin();
            Item found = (Item) session.load(Item.class, item.getId());
            Statistics stats = session.getSessionFactory().getStatistics();
            log.info(stats.toString());
            assertEquals(item.getDescription(), found.getDescription());
            assertEquals(0, stats.getSecondLevelCacheMissCount());
            assertEquals(1, stats.getSecondLevelCacheHitCount());
            session.delete(found);
            session.getTransaction().commit();
            session.close();
         } catch(Exception e) {
            ut.setRollbackOnly();
            throw e;
         } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
               ut.commit();
            else
               ut.rollback();
         }

         ut = (UserTransaction) ctx.lookup("UserTransaction");
         ut.begin();
         try {
            Session session = sessionFactory.openSession();
            session.getTransaction().begin();
            assertNull(session.get(Item.class, item.getId()));
            session.getTransaction().commit();
            session.close();
         } catch(Exception e) {
            ut.setRollbackOnly();
            throw e;
         } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
               ut.commit();
            else
               ut.rollback();
         }
      } finally {
         if (sessionFactory != null)
            sessionFactory.close();
      }

   }

   private Main startJndiServer() throws Exception {
      // Create an in-memory jndi
      NamingServer namingServer = new NamingServer();
      NamingContext.setLocal(namingServer);
      Main namingMain = new Main();
      namingMain.setInstallGlobalService(true);
      namingMain.setPort( -1 );
      namingMain.start();
      return namingMain;
   }

   private Context createJndiContext() throws Exception {
      Properties props = new Properties();
      props.put( Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory" );
      props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
      return new InitialContext(props);
   }

   private void bindTransactionManager() throws Exception {
      // as JBossTransactionManagerLookup extends JNDITransactionManagerLookup we must also register the TransactionManager
      bind("java:/TransactionManager", lookup.getTransactionManager(), lookup.getTransactionManager().getClass(), ctx);
   }

   private void bindUserTransaction() throws Exception {
      // also the UserTransaction must be registered on jndi: org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory#getUserTransaction() requires this
      bind( "UserTransaction", lookup.getUserTransaction(), lookup.getUserTransaction().getClass(), ctx );
   }

   /**
    * Helper method that binds the a non serializable object to the JNDI tree.
    *
    * @param jndiName  Name under which the object must be bound
    * @param who       Object to bind in JNDI
    * @param classType Class type under which should appear the bound object
    * @param ctx       Naming context under which we bind the object
    * @throws Exception Thrown if a naming exception occurs during binding
    */
   private void bind(String jndiName, Object who, Class classType, Context ctx) throws Exception {
      // Ah ! This service isn't serializable, so we use a helper class
      NonSerializableFactory.bind(jndiName, who);
      Name n = ctx.getNameParser("").parse(jndiName);
      while (n.size() > 1) {
         String ctxName = n.get(0);
         try {
            ctx = (Context) ctx.lookup(ctxName);
         } catch (NameNotFoundException e) {
            System.out.println("Creating subcontext:" + ctxName);
            ctx = ctx.createSubcontext(ctxName);
         }
         n = n.getSuffix(1);
      }

      // The helper class NonSerializableFactory uses address type nns, we go on to
      // use the helper class to bind the service object in JNDI
      StringRefAddr addr = new StringRefAddr("nns", jndiName);
      Reference ref = new Reference(classType.getName(), addr, NonSerializableFactory.class.getName(), null);
      ctx.rebind(n.get(0), ref);
   }

   private void unbind(String jndiName, Context ctx) throws Exception {
      NonSerializableFactory.unbind(jndiName);
      ctx.unbind(jndiName);
   }

   private SessionFactory buildSessionFactory() {
      // Extra options located in src/test/resources/hibernate.properties
      Configuration cfg = new Configuration();
      cfg.setProperty( Environment.DIALECT, "HSQL" );
      cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
      cfg.setProperty( Environment.CONNECTION_PROVIDER, JtaAwareConnectionProviderImpl.class.getName() );
      cfg.setProperty(Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory");
      cfg.setProperty(Environment.TRANSACTION_STRATEGY, "jta");
      cfg.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "jta");
      cfg.setProperty(Environment.RELEASE_CONNECTIONS, "auto");
      cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
      cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
      cfg.setProperty(Environment.CACHE_REGION_FACTORY,
            "org.hibernate.test.cache.infinispan.functional.SingleNodeTestCase$TestInfinispanRegionFactory");

      Properties envProps = Environment.getProperties();
      envProps.put(AvailableSettings.JTA_PLATFORM, new JBossStandAloneJtaPlatform());
	   envProps.putAll( cfg.getProperties() );
      serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(envProps);

      String[] mappings = new String[]{"org/hibernate/test/cache/infinispan/functional/Item.hbm.xml"};
      for (String mapping : mappings) {
         cfg.addResource(mapping, Thread.currentThread().getContextClassLoader());
      }
      cfg.buildMappings();
      Iterator iter = cfg.getClassMappings();
      while (iter.hasNext()) {
         PersistentClass clazz = (PersistentClass) iter.next();
         cfg.setCacheConcurrencyStrategy(clazz.getEntityName(), "transactional");
      }
      iter = cfg.getCollectionMappings();
      while (iter.hasNext()) {
         Collection coll = (Collection) iter.next();
         cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), "transactional");
      }
      return cfg.buildSessionFactory( serviceRegistry );
   }
}
File
JBossStandaloneJtaExampleTest.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
      return cfg;
   }

<<<<<<< HEAD


   public static InfinispanRegionFactory startRegionFactory(
		   ServiceRegistry serviceRegistry,
		   Configuration cfg,
		   CacheTestSupport testSupport) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

	   SessionFactoryImplementor sessionFactory =(SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry );
	   InfinispanRegionFactory factory =  (InfinispanRegionFactory) sessionFactory.getServiceRegistry().getService( RegionFactory.class );
      testSupport.registerFactory(factory, sessionFactory);
      return factory;
   }

   public static void stopRegionFactory(InfinispanRegionFactory factory, CacheTestSupport testSupport) {
      testSupport.unregisterFactory(factory).close();
=======
   public static InfinispanRegionFactory startRegionFactory(ServiceRegistry reg,
         Configuration cfg){
      try {
         Settings settings = cfg.buildSettings(reg);
         Properties properties = cfg.getProperties();

         String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY);
         Class clazz = Thread.currentThread()
               .getContextClassLoader().loadClass(factoryType);
         InfinispanRegionFactory regionFactory;
         if (clazz == InfinispanRegionFactory.class) {
            regionFactory = new SingleNodeTestCase.TestInfinispanRegionFactory();
         } else {
            regionFactory = (InfinispanRegionFactory) clazz.newInstance();
         }
         regionFactory.start(settings, properties);
         return regionFactory;
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   public static InfinispanRegionFactory startRegionFactory(ServiceRegistry reg,
         Configuration cfg, CacheTestSupport testSupport) {
      InfinispanRegionFactory factory = startRegionFactory(reg, cfg);
      testSupport.registerFactory(factory);
      return factory;
   }

   public static void stopRegionFactory(InfinispanRegionFactory factory,
         CacheTestSupport testSupport) {
      factory.stop();
      testSupport.unregisterFactory(factory);
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
   }

   /**
Solution content
      return cfg;
   }

   public static InfinispanRegionFactory startRegionFactory(ServiceRegistry reg,
         Configuration cfg){
      try {
         Settings settings = cfg.buildSettings(reg);
         Properties properties = cfg.getProperties();
         String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY);
         Class clazz = Thread.currentThread()
               .getContextClassLoader().loadClass(factoryType);
         InfinispanRegionFactory regionFactory;
         if (clazz == InfinispanRegionFactory.class) {
            regionFactory = new SingleNodeTestCase.TestInfinispanRegionFactory();
         } else {
            regionFactory = (InfinispanRegionFactory) clazz.newInstance();
         }
         regionFactory.start(settings, properties);
         return regionFactory;
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   public static InfinispanRegionFactory startRegionFactory(ServiceRegistry reg,
         Configuration cfg, CacheTestSupport testSupport) {
	SessionFactoryImplementor sessionFactory =(SessionFactoryImplementor) cfg.buildSessionFactory( reg );  
	InfinispanRegionFactory factory = startRegionFactory(reg, cfg);
      testSupport.registerFactory(factory, sessionFactory);
      return factory;
   }

   public static void stopRegionFactory(InfinispanRegionFactory factory,
         CacheTestSupport testSupport) {
      factory.stop();
      testSupport.unregisterFactory(factory);
   }

   /**
File
CacheTestUtil.java
Developer's decision
Manual
Kind of conflict
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
	private static final CoreMessageLogger LOG = Logger.getMessageLogger(
			CoreMessageLogger.class, CachingRegionFactory.class.getName()
	);
<<<<<<< HEAD
=======
	public static String DEFAULT_ACCESSTYPE = "DefaultAccessType";
	private Settings settings;
	private Properties properties;
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	public CachingRegionFactory() {
		LOG.warn( "CachingRegionFactory should be only used for testing." );
	}
Solution content
	private static final CoreMessageLogger LOG = Logger.getMessageLogger(
			CoreMessageLogger.class, CachingRegionFactory.class.getName()
	);

	public static String DEFAULT_ACCESSTYPE = "DefaultAccessType";
	
	private Properties properties;
	
	public CachingRegionFactory() {
		LOG.warn( "CachingRegionFactory should be only used for testing." );
	}
File
CachingRegionFactory.java
Developer's decision
Combination
Kind of conflict
Attribute
Chunk
Conflicting content
	@Override
<<<<<<< HEAD
	public void start() {
=======
	public void start(Settings settings, Properties properties) throws CacheException {
		this.settings=settings;
		this.properties=properties; 
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	}

	@Override
Solution content
	@Override
	public void start() {
	}

	@Override
File
CachingRegionFactory.java
Developer's decision
Version 1
Kind of conflict
Attribute
Method signature
Chunk
Conflicting content
			sessionFactory.getCache().evictNaturalIdRegions();
		}
	}
<<<<<<< HEAD

	protected boolean isCleanupTestDataRequired() {
		return false;
	}

=======
	
	protected boolean isCleanupTestDataRequired() { return false; }
	
>>>>>>> b0fa122cfc4abdd25aea51ad622ac4c4f4833454
	protected void cleanupTestData() throws Exception {
		Session s = openSession();
		s.beginTransaction();
Solution content
			sessionFactory.getCache().evictNaturalIdRegions();
		}
	}
	
	protected boolean isCleanupTestDataRequired() { return false; }

	protected void cleanupTestData() throws Exception {
		Session s = openSession();
		s.beginTransaction();
File
BaseCoreFunctionalTestCase.java
Developer's decision
Version 1
Kind of conflict
Method declaration