From 88543c7a585dbafe6d2f5e2824a9754ec419655f Mon Sep 17 00:00:00 2001 From: Gail Badner Date: Tue, 30 Nov 2010 11:38:53 -0800 Subject: [PATCH] HHH-5765 : Wire in connection provider from service registry --- .../src/main/java/org/hibernate/Session.java | 2 +- .../java/org/hibernate/SessionFactory.java | 8 +- .../cfg/AnnotationConfiguration.java | 4 - .../java/org/hibernate/cfg/Configuration.java | 20 +- .../java/org/hibernate/cfg/Environment.java | 2 +- .../main/java/org/hibernate/cfg/Settings.java | 6 +- .../org/hibernate/cfg/SettingsFactory.java | 12 +- .../connection/ConnectionProvider.java | 94 ------- .../connection/ConnectionProviderFactory.java | 235 ------------------ .../DatasourceConnectionProvider.java | 116 --------- .../DriverManagerConnectionProvider.java | 199 --------------- .../UserSuppliedConnectionProvider.java | 80 ------ .../org/hibernate/connection/package.html | 38 --- .../engine/SessionFactoryImplementor.java | 2 +- .../hibernate/impl/SessionFactoryImpl.java | 30 ++- .../org/hibernate/jmx/HibernateService.java | 7 +- .../internal/ConnectionProviderInitiator.java | 2 +- .../hibernate/stat/StatisticsImplementor.java | 2 +- .../ManagedProviderConnectionHelper.java | 13 +- .../hibernate/tool/hbm2ddl/SchemaExport.java | 19 +- .../hibernate/tool/hbm2ddl/SchemaUpdate.java | 13 +- .../tool/hbm2ddl/SchemaValidator.java | 7 +- ...iedConnectionProviderConnectionHelper.java | 2 +- .../util/ExternalSessionFactoryConfig.java | 2 + hibernate-core/src/main/javadoc/package.html | 2 +- .../hibernate/connection/PropertiesTest.java | 4 +- .../SequenceHiLoGeneratorNoIncrementTest.java | 11 +- .../id/SequenceHiLoGeneratorTest.java | 10 +- .../hibernate/id/TableHiLoGeneratorTest.java | 9 +- .../SubclassProxyInterfaceTest.java | 5 +- .../test/annotations/ConfigurationTest.java | 25 +- .../test/annotations/SafeMappingTest.java | 10 +- .../test/annotations/SecuredBindingTest.java | 10 +- .../hibernate/test/annotations/TestCase.java | 4 +- .../access/jpa/AccessMappingTest.java | 34 ++- .../annotations/access/xml/XmlAccessTest.java | 16 +- .../annotations/backquotes/BackquoteTest.java | 19 +- .../duplicatedgenerator/DuplicateTest.java | 10 +- .../entity/BasicHibernateAnnotationsTest.java | 2 +- .../fetchprofile/FetchProfileTest.java | 34 ++- .../fkcircularity/FkCircularityTest.java | 19 +- .../id/JoinColumnOverrideTest.java | 2 +- .../id/sequences/JoinColumnOverrideTest.java | 2 +- .../annotations/immutable/ImmutableTest.java | 2 +- .../namingstrategy/NamingStrategyTest.java | 21 +- .../onetoone/OneToOneErrorTest.java | 10 +- .../primarykey/NullablePrimaryKeyTest.java | 13 +- .../cfg/ConfigurationSerializationTest.java | 19 +- .../test/common/ServiceRegistryHolder.java | 81 ++++++ .../connections/SuppliedConnectionTest.java | 16 +- .../test/extendshbm/ExtendsTest.java | 6 +- .../instrument/cases/AbstractExecutable.java | 8 +- .../org/hibernate/test/legacy/FooBarTest.java | 8 +- .../test/schemaupdate/MigrationTest.java | 6 +- .../org/hibernate/test/stats/StatsTest.java | 4 +- .../hibernate/testing/junit/UnitTestCase.java | 30 +++ .../functional/ExecutionEnvironment.java | 44 +++- .../junit/functional/FunctionalTestCase.java | 7 +- .../FunctionalTestClassTestSuite.java | 9 +- .../annotations/HibernateTestCase.java | 27 +- .../testing/tm/ConnectionProviderImpl.java | 11 +- .../org/hibernate/ejb/Ejb3Configuration.java | 28 ++- .../ejb/EntityManagerFactoryImpl.java | 21 +- .../hibernate/ejb/HibernatePersistence.java | 2 + .../ejb/InjectionSettingsFactory.java | 53 ---- .../InjectedDataSourceConnectionProvider.java | 7 +- .../java/org/hibernate/ejb/test/TestCase.java | 1 + .../ejb/test/metadata/MetadataTest.java | 2 +- .../envers/test/AbstractSessionTest.java | 17 +- ...bstractEntityCollectionRegionTestCase.java | 16 +- .../AbstractGeneralDataRegionTestCase.java | 16 +- .../AbstractNonFunctionalTestCase.java | 4 + ...ollectionRegionAccessStrategyTestCase.java | 30 ++- .../TransactionalExtraAPITestCase.java | 4 +- ...actEntityRegionAccessStrategyTestCase.java | 30 ++- .../entity/TransactionalExtraAPITestCase.java | 4 +- .../functional/ConcurrentWriteTest.java | 9 +- .../functional/JndiRegionFactoryTestCase.java | 2 +- .../functional/SingleNodeTestCase.java | 2 +- .../bulk/BulkOperationsTestCase.java | 2 +- .../DualNodeConnectionProviderImpl.java | 20 +- .../functional/cluster/DualNodeTestCase.java | 21 +- .../query/QueryRegionImplTestCase.java | 7 +- .../TimestampsRegionImplTestCase.java | 8 +- .../tm/JBossStandaloneJtaExampleTest.java | 19 +- .../infinispan/tm/XaConnectionProvider.java | 11 +- .../cache/infinispan/util/CacheTestUtil.java | 15 +- 87 files changed, 768 insertions(+), 1048 deletions(-) delete mode 100644 hibernate-core/src/main/java/org/hibernate/connection/ConnectionProvider.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/connection/ConnectionProviderFactory.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/connection/UserSuppliedConnectionProvider.java delete mode 100755 hibernate-core/src/main/java/org/hibernate/connection/package.html create mode 100644 hibernate-core/src/test/java/org/hibernate/test/common/ServiceRegistryHolder.java delete mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/ejb/InjectionSettingsFactory.java diff --git a/hibernate-core/src/main/java/org/hibernate/Session.java b/hibernate-core/src/main/java/org/hibernate/Session.java index 74a327666e..003c55764f 100644 --- a/hibernate-core/src/main/java/org/hibernate/Session.java +++ b/hibernate-core/src/main/java/org/hibernate/Session.java @@ -929,7 +929,7 @@ public interface Session extends Serializable { *

* Note that disconnect() called on a session where the connection was * retrieved by Hibernate through its configured - * {@link org.hibernate.connection.ConnectionProvider} has no effect, + * {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} has no effect, * provided {@link ConnectionReleaseMode#ON_CLOSE} is not in effect. * * @return the application-supplied connection or null diff --git a/hibernate-core/src/main/java/org/hibernate/SessionFactory.java b/hibernate-core/src/main/java/org/hibernate/SessionFactory.java index b8e22606fc..af193fc35e 100644 --- a/hibernate-core/src/main/java/org/hibernate/SessionFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/SessionFactory.java @@ -57,7 +57,7 @@ public interface SessionFactory extends Referenceable, Serializable { * Open a {@link Session}. *

* JDBC {@link Connection connection(s} will be obtained from the - * configured {@link org.hibernate.connection.ConnectionProvider} as needed + * configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed * to perform requested work. * * @return The created session. @@ -70,7 +70,7 @@ public interface SessionFactory extends Referenceable, Serializable { * Open a {@link Session}, utilizing the specified {@link Interceptor}. *

* JDBC {@link Connection connection(s} will be obtained from the - * configured {@link org.hibernate.connection.ConnectionProvider} as needed + * configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed * to perform requested work. * * @param interceptor a session-scoped interceptor @@ -87,7 +87,7 @@ public interface SessionFactory extends Referenceable, Serializable { * Note that the second-level cache will be disabled if you supply a JDBC * connection. Hibernate will not be able to track any statements you might * have executed in the same transaction. Consider implementing your own - * {@link org.hibernate.connection.ConnectionProvider} instead as a highly + * {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly * recommended alternative. * * @param connection a connection provided by the application. @@ -103,7 +103,7 @@ public interface SessionFactory extends Referenceable, Serializable { * Note that the second-level cache will be disabled if you supply a JDBC * connection. Hibernate will not be able to track any statements you might * have executed in the same transaction. Consider implementing your own - * {@link org.hibernate.connection.ConnectionProvider} instead as a highly + * {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly * recommended alternative. * * @param connection a connection provided by the application. diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java index e318381634..534c52e218 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java @@ -74,10 +74,6 @@ public class AnnotationConfiguration extends Configuration { super(); } - public AnnotationConfiguration(SettingsFactory sf) { - super( sf ); - } - /** * {@inheritDoc} */ diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index ad86e8fb9f..d8051cd5e3 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -94,6 +94,7 @@ import org.hibernate.engine.Mapping; import org.hibernate.engine.NamedQueryDefinition; import org.hibernate.engine.NamedSQLQueryDefinition; import org.hibernate.engine.ResultSetMappingDefinition; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.event.AutoFlushEventListener; import org.hibernate.event.DeleteEventListener; import org.hibernate.event.DirtyCheckEventListener; @@ -151,6 +152,8 @@ import org.hibernate.mapping.TypeDef; import org.hibernate.mapping.UniqueKey; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.JACCConfiguration; +import org.hibernate.service.spi.ServicesRegistry; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.tool.hbm2ddl.DatabaseMetadata; import org.hibernate.tool.hbm2ddl.IndexMetadata; import org.hibernate.tool.hbm2ddl.TableMetadata; @@ -1820,7 +1823,7 @@ public class Configuration implements Serializable { * * @throws HibernateException usually indicates an invalid configuration or invalid mapping information */ - public SessionFactory buildSessionFactory() throws HibernateException { + public SessionFactory buildSessionFactory(ServicesRegistry serviceRegistry) throws HibernateException { log.debug( "Preparing to build session factory with filters : " + filterDefinitions ); secondPassCompile(); @@ -1837,11 +1840,12 @@ public class Configuration implements Serializable { Properties copy = new Properties(); copy.putAll( properties ); ConfigurationHelper.resolvePlaceHolders( copy ); - Settings settings = buildSettings( copy ); + Settings settings = buildSettings( copy, serviceRegistry.getService( JdbcServices.class ).getConnectionProvider() ); return new SessionFactoryImpl( this, mapping, + serviceRegistry, settings, getInitializedEventListeners(), sessionFactoryObserver @@ -2819,18 +2823,18 @@ public class Configuration implements Serializable { * * @return The build settings */ - public Settings buildSettings() { + public Settings buildSettings(ConnectionProvider connectionProvider) { Properties clone = ( Properties ) properties.clone(); ConfigurationHelper.resolvePlaceHolders( clone ); - return buildSettingsInternal( clone ); + return buildSettingsInternal( clone, connectionProvider ); } - public Settings buildSettings(Properties props) throws HibernateException { - return buildSettingsInternal( props ); + public Settings buildSettings(Properties props, ConnectionProvider connectionProvider) throws HibernateException { + return buildSettingsInternal( props, connectionProvider ); } - private Settings buildSettingsInternal(Properties props) { - final Settings settings = settingsFactory.buildSettings( props ); + private Settings buildSettingsInternal(Properties props, ConnectionProvider connectionProvider) { + final Settings settings = settingsFactory.buildSettings( props, connectionProvider ); settings.setEntityTuplizerFactory( this.getEntityTuplizerFactory() ); // settings.setComponentTuplizerFactory( this.getComponentTuplizerFactory() ); return settings; diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java index 562639cb50..89b456467c 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -82,7 +82,7 @@ import org.hibernate.util.ConfigHelper; * * * hibernate.connection.provider_class - * classname of org.hibernate.connection.ConnectionProvider + * classname of org.hibernate.service.jdbc.connections.spi.ConnectionProvider * subclass (if not specified hueristics are used) * * hibernate.connection.usernamedatabase username diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java b/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java index dd252ce8d1..31bf6beba1 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Settings.java @@ -29,7 +29,7 @@ import org.hibernate.ConnectionReleaseMode; import org.hibernate.EntityMode; import org.hibernate.cache.QueryCacheFactory; import org.hibernate.cache.RegionFactory; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.JdbcSupport; import org.hibernate.exception.SQLExceptionConverter; @@ -172,10 +172,6 @@ public final class Settings { return jdbcFetchSize; } - public ConnectionProvider getConnectionProvider() { - return connectionProvider; - } - public TransactionFactory getTransactionFactory() { return transactionFactory; } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java index 3401260bad..b6321e8b7b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java @@ -43,8 +43,7 @@ import org.hibernate.cache.QueryCacheFactory; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.impl.NoCachingRegionFactory; import org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.resolver.DialectFactory; import org.hibernate.exception.SQLExceptionConverter; @@ -76,7 +75,7 @@ public class SettingsFactory implements Serializable { protected SettingsFactory() { } - public Settings buildSettings(Properties props) { + public Settings buildSettings(Properties props, ConnectionProvider connections) { Settings settings = new Settings(); //SessionFactory name: @@ -86,9 +85,6 @@ public class SettingsFactory implements Serializable { //JDBC and connection settings: - ConnectionProvider connections = createConnectionProvider(props); - settings.setConnectionProvider(connections); - //Interrogate JDBC metadata boolean metaSupportsScrollable = false; @@ -449,10 +445,6 @@ public class SettingsFactory implements Serializable { } } - protected ConnectionProvider createConnectionProvider(Properties properties) { - return ConnectionProviderFactory.newConnectionProvider(properties); - } - protected TransactionFactory createTransactionFactory(Properties properties) { return TransactionFactoryFactory.buildTransactionFactory(properties); } diff --git a/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProvider.java deleted file mode 100644 index e05b6ab2dc..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProvider.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2008, Red Hat Middleware LLC 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 Middleware LLC. - * - * 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.connection; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; - -import org.hibernate.HibernateException; - -/** - * A strategy for obtaining JDBC connections. - *

- * Implementors might also implement connection pooling.
- *
- * The ConnectionProvider interface is not intended to be - * exposed to the application. Instead it is used internally by - * Hibernate to obtain connections.
- *
- * Implementors should provide a public default constructor. - * - * @see ConnectionProviderFactory - * @author Gavin King - */ -public interface ConnectionProvider { - /** - * Initialize the connection provider from given properties. - * @param props SessionFactory properties - */ - public void configure(Properties props) throws HibernateException; - /** - * Grab a connection, with the autocommit mode specified by - * hibernate.connection.autocommit. - * @return a JDBC connection - * @throws SQLException - */ - public Connection getConnection() throws SQLException; - /** - * Dispose of a used connection. - * @param conn a JDBC connection - * @throws SQLException - */ - public void closeConnection(Connection conn) throws SQLException; - - /** - * Release all resources held by this provider. JavaDoc requires a second sentence. - * @throws HibernateException - */ - public void close() throws HibernateException; - - /** - * Does this connection provider support aggressive release of JDBC - * connections and re-acquistion of those connections (if need be) later? - *

- * This is used in conjunction with {@link org.hibernate.cfg.Environment.RELEASE_CONNECTIONS} - * to aggressively release JDBC connections. However, the configured ConnectionProvider - * must support re-acquisition of the same underlying connection for that semantic to work. - *

- * Typically, this is only true in managed environments where a container - * tracks connections by transaction or thread. - * - * Note that JTA semantic depends on the fact that the underlying connection provider does - * support aggressive release. - */ - public boolean supportsAggressiveRelease(); -} - - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProviderFactory.java b/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProviderFactory.java deleted file mode 100644 index f2116bc230..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/ConnectionProviderFactory.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2010, 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.connection; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.HibernateException; -import org.hibernate.cfg.Environment; -import org.hibernate.util.ReflectHelper; - -/** - * Instantiates a connection provider given either System properties or - * a java.util.Properties instance. The ConnectionProviderFactory - * first attempts to find a name of a ConnectionProvider subclass in the - * property hibernate.connection.provider_class. If missing, heuristics are used - * to choose either DriverManagerConnectionProvider, - * DatasourceConnectionProvider, C3P0ConnectionProvider or - * DBCPConnectionProvider. - * - * @author Gavin King - * @see ConnectionProvider - */ - -public final class ConnectionProviderFactory { - - private static final Logger log = LoggerFactory.getLogger( ConnectionProviderFactory.class ); - - /** - * Instantiate a ConnectionProvider using System properties. - * - * @return The created connection provider. - * - * @throws HibernateException - */ - public static ConnectionProvider newConnectionProvider() throws HibernateException { - return newConnectionProvider( Environment.getProperties() ); - } - - /** - * Instantiate a ConnectionProvider using given properties. - * Method newConnectionProvider. - * - * @param properties hibernate SessionFactory properties - * - * @return ConnectionProvider - * - * @throws HibernateException - */ - public static ConnectionProvider newConnectionProvider(Properties properties) throws HibernateException { - return newConnectionProvider( properties, null ); - } - - /** - * Create a connection provider based on the given information. - * - * @param properties Properties being used to build the {@link org.hibernate.SessionFactory}. - * @param connectionProviderInjectionData Something to be injected in the connection provided - * - * @return The created connection provider - * - * @throws HibernateException - */ - public static ConnectionProvider newConnectionProvider(Properties properties, Map connectionProviderInjectionData) - throws HibernateException { - ConnectionProvider connections; - String providerClass = properties.getProperty( Environment.CONNECTION_PROVIDER ); - if ( providerClass != null ) { - connections = initializeConnectionProviderFromConfig( providerClass ); - } - else if ( c3p0ConfigDefined( properties ) && c3p0ProviderPresent() ) { - connections = initializeConnectionProviderFromConfig("org.hibernate.connection.C3P0ConnectionProvider"); - } - else if ( properties.getProperty( Environment.DATASOURCE ) != null ) { - connections = new DatasourceConnectionProvider(); - } - else if ( properties.getProperty( Environment.URL ) != null ) { - connections = new DriverManagerConnectionProvider(); - } - else { - connections = new UserSuppliedConnectionProvider(); - } - - if ( connectionProviderInjectionData != null && connectionProviderInjectionData.size() != 0 ) { - //inject the data - try { - BeanInfo info = Introspector.getBeanInfo( connections.getClass() ); - PropertyDescriptor[] descritors = info.getPropertyDescriptors(); - int size = descritors.length; - for ( int index = 0; index < size; index++ ) { - String propertyName = descritors[index].getName(); - if ( connectionProviderInjectionData.containsKey( propertyName ) ) { - Method method = descritors[index].getWriteMethod(); - method.invoke( - connections, new Object[] { connectionProviderInjectionData.get( propertyName ) } - ); - } - } - } - catch ( IntrospectionException e ) { - throw new HibernateException( "Unable to inject objects into the connection provider", e ); - } - catch ( IllegalAccessException e ) { - throw new HibernateException( "Unable to inject objects into the connection provider", e ); - } - catch ( InvocationTargetException e ) { - throw new HibernateException( "Unable to inject objects into the connection provider", e ); - } - } - connections.configure( properties ); - return connections; - } - - private static boolean c3p0ProviderPresent() { - try { - ReflectHelper.classForName( "org.hibernate.connection.C3P0ConnectionProvider" ); - } - catch ( ClassNotFoundException e ) { - log.warn( "c3p0 properties is specificed, but could not find org.hibernate.connection.C3P0ConnectionProvider from the classpath, " + - "these properties are going to be ignored." ); - return false; - } - return true; - } - - private static boolean c3p0ConfigDefined(Properties properties) { - Iterator iter = properties.keySet().iterator(); - while ( iter.hasNext() ) { - String property = (String) iter.next(); - if ( property.startsWith( "hibernate.c3p0" ) ) { - return true; - } - } - return false; - } - - private static ConnectionProvider initializeConnectionProviderFromConfig(String providerClass) { - ConnectionProvider connections; - try { - log.info( "Initializing connection provider: " + providerClass ); - connections = (ConnectionProvider) ReflectHelper.classForName( providerClass ).newInstance(); - } - catch ( Exception e ) { - log.error( "Could not instantiate connection provider", e ); - throw new HibernateException( "Could not instantiate connection provider: " + providerClass ); - } - return connections; - } - - // cannot be instantiated - - private ConnectionProviderFactory() { - throw new UnsupportedOperationException(); - } - - /** - * Transform JDBC connection properties. - * - * Passed in the form hibernate.connection.* to the - * format accepted by DriverManager by trimming the leading "hibernate.connection". - */ - public static Properties getConnectionProperties(Properties properties) { - - Iterator iter = properties.keySet().iterator(); - Properties result = new Properties(); - while ( iter.hasNext() ) { - String prop = (String) iter.next(); - if ( prop.startsWith( Environment.CONNECTION_PREFIX ) && !SPECIAL_PROPERTIES.contains( prop ) ) { - result.setProperty( - prop.substring( Environment.CONNECTION_PREFIX.length() + 1 ), - properties.getProperty( prop ) - ); - } - } - String userName = properties.getProperty( Environment.USER ); - if ( userName != null ) { - result.setProperty( "user", userName ); - } - return result; - } - - private static final Set SPECIAL_PROPERTIES; - - static { - SPECIAL_PROPERTIES = new HashSet(); - SPECIAL_PROPERTIES.add( Environment.DATASOURCE ); - SPECIAL_PROPERTIES.add( Environment.URL ); - SPECIAL_PROPERTIES.add( Environment.CONNECTION_PROVIDER ); - SPECIAL_PROPERTIES.add( Environment.POOL_SIZE ); - SPECIAL_PROPERTIES.add( Environment.ISOLATION ); - SPECIAL_PROPERTIES.add( Environment.DRIVER ); - SPECIAL_PROPERTIES.add( Environment.USER ); - - } - -} - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java deleted file mode 100644 index a10ab53489..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2008, Red Hat Middleware LLC 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 Middleware LLC. - * - * 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.connection; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; - -import javax.sql.DataSource; - -import org.hibernate.HibernateException; -import org.hibernate.cfg.Environment; -import org.hibernate.internal.util.jndi.JndiHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A connection provider that uses a DataSource registered with JNDI. - * Hibernate will use this ConnectionProvider by default if the - * property hibernate.connection.datasource is set. - * @see ConnectionProvider - * @author Gavin King - */ -public class DatasourceConnectionProvider implements ConnectionProvider { - private DataSource ds; - private String user; - private String pass; - - private static final Logger log = LoggerFactory.getLogger(DatasourceConnectionProvider.class); - - public DataSource getDataSource() { - return ds; - } - - public void setDataSource(DataSource ds) { - this.ds = ds; - } - - public void configure(Properties props) throws HibernateException { - - String jndiName = props.getProperty( Environment.DATASOURCE ); - if ( jndiName == null ) { - String msg = "datasource JNDI name was not specified by property " + Environment.DATASOURCE; - log.error( msg ); - throw new HibernateException( msg ); - } - - user = props.getProperty( Environment.USER ); - pass = props.getProperty( Environment.PASS ); - - try { - ds = ( DataSource ) JndiHelper.getInitialContext( props ).lookup( jndiName ); - } - catch ( Exception e ) { - log.error( "Could not find datasource: " + jndiName, e ); - throw new HibernateException( "Could not find datasource", e ); - } - if ( ds == null ) { - throw new HibernateException( "Could not find datasource: " + jndiName ); - } - log.info( "Using datasource: " + jndiName ); - } - - public Connection getConnection() throws SQLException { - if (user != null || pass != null) { - return ds.getConnection(user, pass); - } - else { - return ds.getConnection(); - } - } - - public void closeConnection(Connection conn) throws SQLException { - conn.close(); - } - - public void close() {} - - /** - * @see ConnectionProvider#supportsAggressiveRelease() - */ - public boolean supportsAggressiveRelease() { - return true; - } - -} - - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java deleted file mode 100644 index 046d33d3a7..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2008, Red Hat Middleware LLC 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 Middleware LLC. - * - * 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.connection; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.HibernateException; -import org.hibernate.cfg.Environment; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.util.ReflectHelper; - -/** - * A connection provider that uses java.sql.DriverManager. This provider - * also implements a very rudimentary connection pool. - * @see ConnectionProvider - * @author Gavin King - */ -public class DriverManagerConnectionProvider implements ConnectionProvider { - - private String url; - private Properties connectionProps; - private Integer isolation; - private final ArrayList pool = new ArrayList(); - private int poolSize; - private int checkedOut = 0; - private boolean autocommit; - - private static final Logger log = LoggerFactory.getLogger(DriverManagerConnectionProvider.class); - - public void configure(Properties props) throws HibernateException { - - String driverClass = props.getProperty(Environment.DRIVER); - - poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, props, 20); //default pool size 20 - log.info("Using Hibernate built-in connection pool (not for production use!)"); - log.info("Hibernate connection pool size: " + poolSize); - - autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props); - log.info("autocommit mode: " + autocommit); - - isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props); - if (isolation!=null) - log.info( "JDBC isolation level: " + Environment.isolationLevelToString( isolation.intValue() ) ); - - if (driverClass==null) { - log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER); - } - else { - try { - // trying via forName() first to be as close to DriverManager's semantics - Class.forName(driverClass); - } - catch (ClassNotFoundException cnfe) { - try { - ReflectHelper.classForName(driverClass); - } - catch (ClassNotFoundException e) { - String msg = "JDBC Driver class not found: " + driverClass; - log.error( msg, e ); - throw new HibernateException(msg, e); - } - } - } - - url = props.getProperty( Environment.URL ); - if ( url == null ) { - String msg = "JDBC URL was not specified by property " + Environment.URL; - log.error( msg ); - throw new HibernateException( msg ); - } - - connectionProps = ConnectionProviderFactory.getConnectionProperties( props ); - - log.info( "using driver: " + driverClass + " at URL: " + url ); - // if debug level is enabled, then log the password, otherwise mask it - if ( log.isDebugEnabled() ) { - log.info( "connection properties: " + connectionProps ); - } - else if ( log.isInfoEnabled() ) { - log.info( "connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password") ); - } - - } - - public Connection getConnection() throws SQLException { - - if ( log.isTraceEnabled() ) log.trace( "total checked-out connections: " + checkedOut ); - - synchronized (pool) { - if ( !pool.isEmpty() ) { - int last = pool.size() - 1; - if ( log.isTraceEnabled() ) { - log.trace("using pooled JDBC connection, pool size: " + last); - checkedOut++; - } - Connection pooled = (Connection) pool.remove(last); - if (isolation!=null) pooled.setTransactionIsolation( isolation.intValue() ); - if ( pooled.getAutoCommit()!=autocommit ) pooled.setAutoCommit(autocommit); - return pooled; - } - } - - log.debug("opening new JDBC connection"); - Connection conn = DriverManager.getConnection(url, connectionProps); - if (isolation!=null) conn.setTransactionIsolation( isolation.intValue() ); - if ( conn.getAutoCommit()!=autocommit ) conn.setAutoCommit(autocommit); - - if ( log.isDebugEnabled() ) { - log.debug( "created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation() ); - } - if ( log.isTraceEnabled() ) checkedOut++; - - return conn; - } - - public void closeConnection(Connection conn) throws SQLException { - - if ( log.isDebugEnabled() ) checkedOut--; - - synchronized (pool) { - int currentSize = pool.size(); - if ( currentSize < poolSize ) { - if ( log.isTraceEnabled() ) log.trace("returning connection to pool, pool size: " + (currentSize + 1) ); - pool.add(conn); - return; - } - } - - log.debug("closing JDBC connection"); - - conn.close(); - - } - - protected void finalize() { - close(); - } - - public void close() { - - log.info("cleaning up connection pool: " + url); - - Iterator iter = pool.iterator(); - while ( iter.hasNext() ) { - try { - ( (Connection) iter.next() ).close(); - } - catch (SQLException sqle) { - log.warn("problem closing pooled connection", sqle); - } - } - pool.clear(); - - } - - /** - * @see ConnectionProvider#supportsAggressiveRelease() - */ - public boolean supportsAggressiveRelease() { - return false; - } - -} - - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/connection/UserSuppliedConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/UserSuppliedConnectionProvider.java deleted file mode 100644 index b676676bf6..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/UserSuppliedConnectionProvider.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2008, Red Hat Middleware LLC 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 Middleware LLC. - * - * 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.connection; - -import java.sql.Connection; -import java.util.Properties; - -import org.slf4j.LoggerFactory; -import org.hibernate.HibernateException; - -/** - * An implementation of the ConnectionProvider interface that - * simply throws an exception when a connection is requested. This implementation - * indicates that the user is expected to supply a JDBC connection. - * @see ConnectionProvider - * @author Gavin King - */ -public class UserSuppliedConnectionProvider implements ConnectionProvider { - - /** - * @see org.hibernate.connection.ConnectionProvider#configure(Properties) - */ - public void configure(Properties props) throws HibernateException { - LoggerFactory.getLogger( UserSuppliedConnectionProvider.class ) - .warn( "No connection properties specified - the user must supply JDBC connections" ); - } - - /** - * @see org.hibernate.connection.ConnectionProvider#getConnection() - */ - public Connection getConnection() { - throw new UnsupportedOperationException("The user must supply a JDBC connection"); - } - - /** - * @see org.hibernate.connection.ConnectionProvider#closeConnection(Connection) - */ - public void closeConnection(Connection conn) { - throw new UnsupportedOperationException("The user must supply a JDBC connection"); - } - - public void close() { - } - - /** - * @see ConnectionProvider#supportsAggressiveRelease() - */ - public boolean supportsAggressiveRelease() { - return false; - } - -} - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/connection/package.html b/hibernate-core/src/main/java/org/hibernate/connection/package.html deleted file mode 100755 index ebe7d7f74d..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/connection/package.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - -

- This package abstracts the mechanism for obtaining - a JDBC connection. -

-

- A concrete implementation of ConnectionProvider may be - selected by specifying hibernate.connection.provider_class. -

- - diff --git a/hibernate-core/src/main/java/org/hibernate/engine/SessionFactoryImplementor.java b/hibernate-core/src/main/java/org/hibernate/engine/SessionFactoryImplementor.java index 23e2470918..026285a19c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/SessionFactoryImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/SessionFactoryImplementor.java @@ -45,7 +45,7 @@ import org.hibernate.cache.QueryCache; import org.hibernate.cache.UpdateTimestampsCache; import org.hibernate.cache.Region; import org.hibernate.cfg.Settings; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.function.SQLFunctionRegistry; import org.hibernate.exception.SQLExceptionConverter; diff --git a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java index fbda191f57..9baccd21ff 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java @@ -74,7 +74,8 @@ import org.hibernate.cache.impl.CacheDataDescriptionImpl; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.context.CurrentSessionContext; import org.hibernate.context.JTASessionContext; import org.hibernate.context.ManagedSessionContext; @@ -110,6 +111,7 @@ import org.hibernate.persister.entity.Loadable; import org.hibernate.persister.entity.Queryable; import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.EntityNotFoundDelegate; +import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.stat.ConcurrentStatisticsImpl; import org.hibernate.stat.Statistics; import org.hibernate.stat.StatisticsImplementor; @@ -142,7 +144,7 @@ import org.hibernate.util.ReflectHelper; * and pooling under the covers. It is crucial that the class is not only thread * safe, but also highly concurrent. Synchronization must be used extremely sparingly. * - * @see org.hibernate.connection.ConnectionProvider + * @see org.hibernate.service.jdbc.connections.spi.ConnectionProvider * @see org.hibernate.classic.Session * @see org.hibernate.hql.QueryTranslator * @see org.hibernate.persister.entity.EntityPersister @@ -170,6 +172,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI private final transient Map fetchProfiles; private final transient Map imports; private final transient Interceptor interceptor; + private final transient ServicesRegistry serviceRegistry; private final transient Settings settings; private final transient Properties properties; private transient SchemaExport schemaExport; @@ -194,6 +197,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public SessionFactoryImpl( Configuration cfg, Mapping mapping, + ServicesRegistry serviceRegistry, Settings settings, EventListeners listeners, SessionFactoryObserver observer) throws HibernateException { @@ -206,6 +210,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI this.properties = new Properties(); this.properties.putAll( cfg.getProperties() ); this.interceptor = cfg.getInterceptor(); + this.serviceRegistry = serviceRegistry; this.settings = settings; this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.getDialect(), cfg.getSqlFunctions()); this.eventListeners = listeners; @@ -367,16 +372,16 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI log.debug("instantiated session factory"); if ( settings.isAutoCreateSchema() ) { - new SchemaExport( cfg, settings ).create( false, true ); + new SchemaExport( getJdbcServices(), cfg ).create( false, true ); } if ( settings.isAutoUpdateSchema() ) { - new SchemaUpdate( cfg, settings ).execute( false, true ); + new SchemaUpdate( getJdbcServices(), cfg ).execute( false, true ); } if ( settings.isAutoValidateSchema() ) { - new SchemaValidator( cfg, settings ).validate(); + new SchemaValidator( getJdbcServices(), cfg ).validate(); } if ( settings.isAutoDropSchema() ) { - schemaExport = new SchemaExport( cfg, settings ); + schemaExport = new SchemaExport( getJdbcServices(), cfg ); } if ( settings.getTransactionManagerLookup()!=null ) { @@ -897,8 +902,12 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI return getEntityPersister(className).getPropertyType(propertyName); } + private JdbcServices getJdbcServices() { + return serviceRegistry.getService( JdbcServices.class ); + } + public ConnectionProvider getConnectionProvider() { - return settings.getConnectionProvider(); + return serviceRegistry.getService( JdbcServices.class ).getConnectionProvider(); } /** @@ -959,12 +968,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI schemaExport.drop( false, true ); } - try { - settings.getConnectionProvider().close(); - } - finally { - SessionFactoryObjectFactory.removeInstance(uuid, name, properties); - } + SessionFactoryObjectFactory.removeInstance(uuid, name, properties); observer.sessionFactoryClosed( this ); eventListeners.destroyListeners(); diff --git a/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java b/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java index efb936c83e..a4946c1398 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java @@ -12,6 +12,8 @@ import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Environment; +import org.hibernate.cfg.internal.ServicesRegistryBootstrap; +import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.internal.util.jndi.JndiHelper; import org.hibernate.util.ExternalSessionFactoryConfig; @@ -33,7 +35,6 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi private String boundName; private Properties properties = new Properties(); - public void start() throws HibernateException { boundName = getJndiName(); try { @@ -61,7 +62,9 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi SessionFactory buildSessionFactory() throws HibernateException { log.info( "starting service at JNDI name: " + boundName ); log.info( "service properties: " + properties ); - return buildConfiguration().buildSessionFactory(); + return buildConfiguration().buildSessionFactory( + new ServicesRegistryBootstrap().initiateServicesRegistry( properties ) + ); } protected Map getExtraProperties() { diff --git a/hibernate-core/src/main/java/org/hibernate/service/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/service/jdbc/connections/internal/ConnectionProviderInitiator.java index 38317d408a..3a33891dac 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/jdbc/connections/internal/ConnectionProviderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/service/jdbc/connections/internal/ConnectionProviderInitiator.java @@ -255,7 +255,7 @@ public class ConnectionProviderInitiator implements ServiceInitiator properties) { Properties result = new Properties(); for ( Map.Entry entry : properties.entrySet() ) { - if ( ! ( String.class.isInstance( entry.getKey() ) ) && String.class.isInstance( entry.getValue() ) ) { + if ( ! ( String.class.isInstance( entry.getKey() ) ) || ! String.class.isInstance( entry.getValue() ) ) { continue; } final String key = (String) entry.getKey(); diff --git a/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImplementor.java b/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImplementor.java index 3fd65db8d7..a7de6b929a 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImplementor.java @@ -46,7 +46,7 @@ public interface StatisticsImplementor { public void flush(); /** - * Callback about a connection being obtained from {@link org.hibernate.connection.ConnectionProvider} + * Callback about a connection being obtained from {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} */ public void connect(); diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/ManagedProviderConnectionHelper.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/ManagedProviderConnectionHelper.java index 87cc8d58e9..df8c354881 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/ManagedProviderConnectionHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/ManagedProviderConnectionHelper.java @@ -24,8 +24,8 @@ */ package org.hibernate.tool.hbm2ddl; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Stoppable; import org.hibernate.util.JDBCExceptionReporter; import java.util.Properties; @@ -48,12 +48,14 @@ class ManagedProviderConnectionHelper implements ConnectionHelper { } public void prepare(boolean needsAutoCommit) throws SQLException { - connectionProvider = ConnectionProviderFactory.newConnectionProvider( cfgProperties ); + /* TEMP TEMP TEMP + connectionProvider = ConnectionProviderBuilder.buildConnectionProvider(); connection = connectionProvider.getConnection(); if ( needsAutoCommit && !connection.getAutoCommit() ) { connection.commit(); connection.setAutoCommit( true ); } + */ } public Connection getConnection() throws SQLException { @@ -67,7 +69,10 @@ class ManagedProviderConnectionHelper implements ConnectionHelper { connectionProvider.closeConnection( connection ); } finally { - connectionProvider.close(); + if ( connectionProvider instanceof Stoppable ) { + ( ( Stoppable ) connectionProvider ).stop(); + } + connectionProvider = null; } } connection = null; diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExport.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExport.java index 6d7256b533..4916f13734 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExport.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExport.java @@ -49,12 +49,12 @@ import org.hibernate.JDBCException; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; -import org.hibernate.cfg.Settings; import org.hibernate.dialect.Dialect; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.jdbc.util.Formatter; -import org.hibernate.jdbc.util.SQLStatementLogger; import org.hibernate.util.ConfigHelper; import org.hibernate.util.JDBCExceptionReporter; import org.hibernate.util.ReflectHelper; @@ -99,14 +99,17 @@ public class SchemaExport { * @param settings The 'parsed' settings. * @throws HibernateException Indicates problem preparing for schema export. */ - public SchemaExport(Configuration cfg, Settings settings) throws HibernateException { - dialect = settings.getDialect(); - connectionHelper = new SuppliedConnectionProviderConnectionHelper( settings.getConnectionProvider() ); + public SchemaExport(JdbcServices jdbcServices, Configuration cfg) throws HibernateException { + dialect = jdbcServices.getDialect(); + connectionHelper = new SuppliedConnectionProviderConnectionHelper( jdbcServices.getConnectionProvider() ); dropSQL = cfg.generateDropSchemaScript( dialect ); createSQL = cfg.generateSchemaCreationScript( dialect ); - sqlStatementLogger = settings.getSqlStatementLogger(); - formatter = ( sqlStatementLogger.isFormatSql() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); - importFiles = settings.getImportFiles() != null ? settings.getImportFiles() : DEFAULT_IMPORT_FILE; + sqlStatementLogger = jdbcServices.getSqlStatementLogger(); + formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); + importFiles = ConfigurationHelper.getString( + Environment.HBM2DDL_IMPORT_FILES, cfg.getProperties(), + DEFAULT_IMPORT_FILE + ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java index 07298c9947..09bf4db55c 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java @@ -41,9 +41,10 @@ import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.Settings; import org.hibernate.dialect.Dialect; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.jdbc.util.Formatter; -import org.hibernate.jdbc.util.SQLStatementLogger; +import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.util.ReflectHelper; import org.slf4j.Logger; @@ -84,15 +85,15 @@ public class SchemaUpdate { formatter = ( ConfigurationHelper.getBoolean( Environment.FORMAT_SQL, props ) ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); } - public SchemaUpdate(Configuration cfg, Settings settings) throws HibernateException { + public SchemaUpdate(JdbcServices jdbcServices, Configuration cfg) throws HibernateException { this.configuration = cfg; - dialect = settings.getDialect(); + dialect = jdbcServices.getDialect(); connectionHelper = new SuppliedConnectionProviderConnectionHelper( - settings.getConnectionProvider() + jdbcServices.getConnectionProvider() ); exceptions = new ArrayList(); - sqlStatementLogger = settings.getSqlStatementLogger(); - formatter = ( sqlStatementLogger.isFormatSql() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); + sqlStatementLogger = jdbcServices.getSqlStatementLogger(); + formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); } public static void main(String[] args) { diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaValidator.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaValidator.java index a2711d434e..04f9985220 100755 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaValidator.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaValidator.java @@ -36,6 +36,7 @@ import org.hibernate.cfg.Configuration; import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.Settings; import org.hibernate.dialect.Dialect; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.util.ReflectHelper; /** @@ -64,11 +65,11 @@ public class SchemaValidator { connectionHelper = new ManagedProviderConnectionHelper( props ); } - public SchemaValidator(Configuration cfg, Settings settings) throws HibernateException { + public SchemaValidator(JdbcServices jdbcServices, Configuration cfg ) throws HibernateException { this.configuration = cfg; - dialect = settings.getDialect(); + dialect = jdbcServices.getDialect(); connectionHelper = new SuppliedConnectionProviderConnectionHelper( - settings.getConnectionProvider() + jdbcServices.getConnectionProvider() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.java index 41fc7792be..903dace8f0 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.java @@ -24,7 +24,7 @@ */ package org.hibernate.tool.hbm2ddl; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.util.JDBCExceptionReporter; import java.sql.Connection; diff --git a/hibernate-core/src/main/java/org/hibernate/util/ExternalSessionFactoryConfig.java b/hibernate-core/src/main/java/org/hibernate/util/ExternalSessionFactoryConfig.java index 6eb711e683..3db5f4e3e5 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/ExternalSessionFactoryConfig.java +++ b/hibernate-core/src/main/java/org/hibernate/util/ExternalSessionFactoryConfig.java @@ -24,8 +24,10 @@ */ package org.hibernate.util; +import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.cfg.internal.ServicesRegistryBootstrap; import org.hibernate.internal.util.config.ConfigurationHelper; import java.util.Properties; diff --git a/hibernate-core/src/main/javadoc/package.html b/hibernate-core/src/main/javadoc/package.html index 521ff379a9..19bd6c8223 100644 --- a/hibernate-core/src/main/javadoc/package.html +++ b/hibernate-core/src/main/javadoc/package.html @@ -40,7 +40,7 @@ Note that there is a large degree of crossover between the notion of extension p Hibernate provides a number of SPIs intended to integrate itself with various third party frameworks or application code to provide additional capabilities. The SPIs fall mainly into 2 categories: Certainly {@link org.hibernate.dialect.Dialect} could fit in here as well, though we chose to list it under extensions since application developers tend to provide extended dialects rather frequently for various reasons. diff --git a/hibernate-core/src/test/java/org/hibernate/connection/PropertiesTest.java b/hibernate-core/src/test/java/org/hibernate/connection/PropertiesTest.java index 60a2759c0b..9d7c6a7a31 100644 --- a/hibernate-core/src/test/java/org/hibernate/connection/PropertiesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/connection/PropertiesTest.java @@ -28,6 +28,8 @@ import java.util.Properties; import junit.framework.TestCase; +import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; + /** * Undocumented * @@ -46,7 +48,7 @@ public class PropertiesTest extends TestCase { props.put("rpt.6.hibernate.connection.password_enc", "76f271db3661fd50082e68d4b953fbee"); props.put("hibernate.connection.create", "true"); - final Properties outputProps = ConnectionProviderFactory.getConnectionProperties(props); + final Properties outputProps = ConnectionProviderInitiator.getConnectionProperties( props ); assertEquals(1, outputProps.size()); assertEquals("true", outputProps.get("create")); } diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java index 60080ecd46..30da3a4d36 100644 --- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java @@ -44,7 +44,8 @@ import org.hibernate.impl.SessionImpl; import org.hibernate.jdbc.Work; import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject; import org.hibernate.TestingDatabaseInfo; - +import org.hibernate.test.common.ServiceRegistryHolder; + /** * I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this * unit test so that we can make sure the value keep being generated in the expected manner @@ -56,6 +57,7 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase { private static final String TEST_SEQUENCE = "test_sequence"; private Configuration cfg; + ServiceRegistryHolder serviceRegistryHolder; private SessionFactoryImplementor sessionFactory; private SequenceHiLoGenerator generator; @@ -95,7 +97,8 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase { ) ); - sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } @Override @@ -103,7 +106,9 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase { if ( sessionFactory != null ) { sessionFactory.close(); } - + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } super.tearDown(); } diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java index 4dd89a75c9..e8f3385ac4 100644 --- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java @@ -44,6 +44,7 @@ import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.impl.SessionImpl; import org.hibernate.jdbc.Work; import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject; +import org.hibernate.test.common.ServiceRegistryHolder; /** * I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this @@ -56,6 +57,7 @@ public class SequenceHiLoGeneratorTest extends TestCase { private static final String TEST_SEQUENCE = "test_sequence"; private Configuration cfg; + private ServiceRegistryHolder serviceRegistryHolder; private SessionFactoryImplementor sessionFactory; private SequenceHiLoGenerator generator; @@ -94,8 +96,10 @@ public class SequenceHiLoGeneratorTest extends TestCase { generator.sqlDropStrings( dialect )[0] ) ); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); - sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(); + sessionFactory = + (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } @Override @@ -103,7 +107,9 @@ public class SequenceHiLoGeneratorTest extends TestCase { if ( sessionFactory != null ) { sessionFactory.close(); } - + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } super.tearDown(); } diff --git a/hibernate-core/src/test/java/org/hibernate/id/TableHiLoGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/id/TableHiLoGeneratorTest.java index 7a18842231..64c79612e0 100644 --- a/hibernate-core/src/test/java/org/hibernate/id/TableHiLoGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/id/TableHiLoGeneratorTest.java @@ -44,6 +44,7 @@ import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.impl.SessionImpl; import org.hibernate.jdbc.Work; import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject; +import org.hibernate.test.common.ServiceRegistryHolder; /** * I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this @@ -57,6 +58,7 @@ public class TableHiLoGeneratorTest extends TestCase { private static final String GEN_COLUMN = TableHiLoGenerator.DEFAULT_COLUMN_NAME; private Configuration cfg; + private ServiceRegistryHolder serviceRegistryHolder; private SessionFactoryImplementor sessionFactory; private TableHiLoGenerator generator; @@ -104,7 +106,9 @@ public class TableHiLoGeneratorTest extends TestCase { ) ); - sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + sessionFactory = + (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } @Override @@ -112,6 +116,9 @@ public class TableHiLoGeneratorTest extends TestCase { if ( sessionFactory != null ) { sessionFactory.close(); } + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } super.tearDown(); } diff --git a/hibernate-core/src/test/java/org/hibernate/subclassProxyInterface/SubclassProxyInterfaceTest.java b/hibernate-core/src/test/java/org/hibernate/subclassProxyInterface/SubclassProxyInterfaceTest.java index fa0af592a6..df79682885 100644 --- a/hibernate-core/src/test/java/org/hibernate/subclassProxyInterface/SubclassProxyInterfaceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/subclassProxyInterface/SubclassProxyInterfaceTest.java @@ -28,6 +28,7 @@ import junit.framework.TestCase; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; +import org.hibernate.test.common.ServiceRegistryHolder; /** * TODO : javadoc @@ -39,6 +40,8 @@ public class SubclassProxyInterfaceTest extends TestCase { final Configuration cfg = new Configuration() .setProperty( Environment.DIALECT, H2Dialect.class.getName() ); cfg.addClass( Person.class ); - cfg.buildSessionFactory().close(); + ServiceRegistryHolder serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ).close(); + serviceRegistryHolder.destroy(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java index 2b10a83ad1..f836ef7660 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java @@ -10,16 +10,29 @@ import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Emmanuel Bernard */ public class ConfigurationTest extends junit.framework.TestCase { + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testDeclarativeMix() throws Exception { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); @@ -37,7 +50,7 @@ public class ConfigurationTest extends junit.framework.TestCase { cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); cfg.setProperty( AnnotationConfiguration.ARTEFACT_PROCESSING_ORDER, "class" ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); @@ -61,7 +74,7 @@ public class ConfigurationTest extends junit.framework.TestCase { cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); cfg.addAnnotatedClass( Boat.class ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); s.getTransaction().begin(); @@ -87,7 +100,7 @@ public class ConfigurationTest extends junit.framework.TestCase { cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); cfg.setProperty( AnnotationConfiguration.ARTEFACT_PROCESSING_ORDER, "class, hbm" ); cfg.addAnnotatedClass( Boat.class ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); s.getTransaction().begin(); @@ -111,7 +124,7 @@ public class ConfigurationTest extends junit.framework.TestCase { cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.addClass( Ferry.class ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); @@ -129,7 +142,7 @@ public class ConfigurationTest extends junit.framework.TestCase { cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); cfg.addAnnotatedClass( Port.class ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); - SessionFactory sf = cfg.buildSessionFactory(); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); assertNotNull( sf ); Session s = sf.openSession(); Transaction tx = s.beginTransaction(); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java index c691fc0f90..45ada004b1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java @@ -5,6 +5,7 @@ import org.hibernate.AnnotationException; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Emmanuel Bernard @@ -14,12 +15,19 @@ public class SafeMappingTest extends junit.framework.TestCase { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.addAnnotatedClass( IncorrectEntity.class ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); + ServiceRegistryHolder serviceRegistryHolder = null; try { - SessionFactory sf = cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "Entity wo id should fail" ); } catch (AnnotationException e) { //success } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java index f45537f4bf..88b071dac9 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java @@ -8,6 +8,7 @@ import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Emmanuel Bernard @@ -30,14 +31,21 @@ public class SecuredBindingTest extends TestCase { ac.setProperties( p ); ac.addAnnotatedClass( Plane.class ); SessionFactory sf; + ServiceRegistryHolder serviceRegistryHolder = null; try { - sf = ac.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( p ); + sf = ac.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "Driver property overriding should work" ); sf.close(); } catch (HibernateException he) { //success } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/TestCase.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/TestCase.java index f36b80fdca..72c38f9983 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/TestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/TestCase.java @@ -33,6 +33,7 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.testing.junit.functional.annotations.HibernateTestCase; /** @@ -103,7 +104,7 @@ public abstract class TestCase extends HibernateTestCase { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } - sessions = getCfg().buildSessionFactory(); + sessions = getCfg().buildSessionFactory( getServiceRegistry() ); } catch ( Exception e ) { e.printStackTrace(); @@ -146,5 +147,6 @@ public abstract class TestCase extends HibernateTestCase { } catch ( Exception ignore ) { } + super.closeResources(); } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/access/jpa/AccessMappingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/access/jpa/AccessMappingTest.java index 9a8807274b..d26c4f37da 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/access/jpa/AccessMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/access/jpa/AccessMappingTest.java @@ -29,9 +29,11 @@ import junit.framework.TestCase; import org.hibernate.EntityMode; import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.property.BasicPropertyAccessor; import org.hibernate.property.DirectPropertyAccessor; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; @@ -43,12 +45,24 @@ import org.hibernate.tuple.entity.PojoEntityTuplizer; */ public class AccessMappingTest extends TestCase { + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testInconsistentAnnotationPlacement() throws Exception { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.addAnnotatedClass( Course1.class ); cfg.addAnnotatedClass( Student.class ); try { - cfg.buildSessionFactory(); + cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." ); } catch ( MappingException e ) { @@ -61,7 +75,7 @@ public class AccessMappingTest extends TestCase { Class classUnderTest = Course6.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -76,7 +90,7 @@ public class AccessMappingTest extends TestCase { Class classUnderTest = Course7.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -91,7 +105,7 @@ public class AccessMappingTest extends TestCase { Class classUnderTest = Course2.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -106,7 +120,7 @@ public class AccessMappingTest extends TestCase { cfg.addAnnotatedClass( Course4.class ); cfg.addAnnotatedClass( Student.class ); try { - cfg.buildSessionFactory(); + cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." ); } catch ( MappingException e ) { @@ -119,7 +133,7 @@ public class AccessMappingTest extends TestCase { Class classUnderTest = Course3.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -139,7 +153,7 @@ public class AccessMappingTest extends TestCase { Class classUnderTest = Course5.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -160,7 +174,7 @@ public class AccessMappingTest extends TestCase { cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Person.class ); cfg.addAnnotatedClass( Being.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -175,7 +189,7 @@ public class AccessMappingTest extends TestCase { cfg.addAnnotatedClass( Horse.class ); cfg.addAnnotatedClass( Animal.class ); - SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); EntityMetamodel metaModel = factory.getEntityPersister( Animal.class.getName() ) .getEntityMetamodel(); PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO ); @@ -200,6 +214,6 @@ public class AccessMappingTest extends TestCase { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.addAnnotatedClass( Course8.class ); cfg.addAnnotatedClass( Student.class ); - cfg.buildSessionFactory(); + cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } } \ No newline at end of file diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/access/xml/XmlAccessTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/access/xml/XmlAccessTest.java index 2dfaa5522c..b36f503a52 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/access/xml/XmlAccessTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/access/xml/XmlAccessTest.java @@ -34,9 +34,11 @@ import junit.framework.TestCase; import org.hibernate.EntityMode; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.property.BasicPropertyAccessor; import org.hibernate.property.DirectPropertyAccessor; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.PojoEntityTuplizer; @@ -48,6 +50,18 @@ import org.hibernate.tuple.entity.PojoEntityTuplizer; */ public class XmlAccessTest extends TestCase { + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testAccessOnBasicXmlElement() throws Exception { Class classUnderTest = Tourist.class; List> classes = new ArrayList>(); @@ -170,7 +184,7 @@ public class XmlAccessTest extends TestCase { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( configFile ); cfg.addInputStream( is ); } - return ( SessionFactoryImplementor ) cfg.buildSessionFactory(); + return ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } // uses the first getter of the tupelizer for the assertions diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java index 9fd2fae88a..fbb81ff83a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java @@ -8,6 +8,9 @@ import junit.framework.TestCase; import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,12 +24,24 @@ public class BackquoteTest extends TestCase { private Logger log = LoggerFactory.getLogger(BackquoteTest.class); + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testBackquotes() { try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Bug.class); config.addAnnotatedClass(Category.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } catch( Exception e ) { StringWriter writer = new StringWriter(); @@ -48,7 +63,7 @@ public class BackquoteTest extends TestCase { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Printer.class); config.addAnnotatedClass(PrinterCable.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail("expected MappingException to be thrown"); } //we WANT MappingException to be thrown diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java index 2a219aeb77..926b17c592 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java @@ -5,6 +5,7 @@ import junit.framework.TestCase; import org.hibernate.AnnotationException; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Emmanuel Bernard @@ -13,16 +14,23 @@ public class DuplicateTest extends TestCase { public void testDuplicateEntityName() throws Exception { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); + ServiceRegistryHolder serviceRegistryHolder = null; try { cfg.addAnnotatedClass( Flight.class ); cfg.addAnnotatedClass( org.hibernate.test.annotations.Flight.class ); cfg.addResource( "org/hibernate/test/annotations/orm.xml" ); cfg.addResource( "org/hibernate/test/annotations/duplicatedgenerator/orm.xml" ); - cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "Should not be able to map the same entity name twice" ); } catch (AnnotationException ae) { //success } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java index 11e705e964..3492e4df3b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java @@ -637,7 +637,7 @@ public class BasicHibernateAnnotationsTest extends TestCase { try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(LocalContactDetails.class); - config.buildSessionFactory(); + config.buildSessionFactory( getServiceRegistry() ); fail("Did not throw expected exception"); } catch( AnnotationException ex ) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/fetchprofile/FetchProfileTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/fetchprofile/FetchProfileTest.java index b32b6118d5..9872013b99 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/fetchprofile/FetchProfileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/fetchprofile/FetchProfileTest.java @@ -33,7 +33,9 @@ import org.slf4j.LoggerFactory; import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.test.common.ServiceRegistryHolder; /** * Test case for HHH-4812 @@ -44,13 +46,27 @@ public class FetchProfileTest extends TestCase { private Logger log = LoggerFactory.getLogger( FetchProfileTest.class ); + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testFetchProfileConfigured() { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass( Customer.class ); config.addAnnotatedClass( Order.class ); config.addAnnotatedClass( SupportTickets.class ); config.addAnnotatedClass( Country.class ); - SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(); + SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory( + serviceRegistryHolder.getServiceRegistry() + ); assertTrue( "fetch profile not parsed properly", @@ -69,7 +85,7 @@ public class FetchProfileTest extends TestCase { config.addAnnotatedClass( Country.class ); try { - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail(); } catch ( MappingException e ) { @@ -84,7 +100,7 @@ public class FetchProfileTest extends TestCase { config.addAnnotatedClass( Country.class ); try { - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail(); } catch ( MappingException e ) { @@ -99,7 +115,7 @@ public class FetchProfileTest extends TestCase { config.addAnnotatedClass( Country.class ); try { - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail(); } catch ( MappingException e ) { @@ -116,7 +132,9 @@ public class FetchProfileTest extends TestCase { .getContextClassLoader() .getResourceAsStream( "org/hibernate/test/annotations/fetchprofile/mappings.hbm.xml" ); config.addInputStream( is ); - SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(); + SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory( + serviceRegistryHolder.getServiceRegistry() + ); assertTrue( "fetch profile not parsed properly", @@ -129,7 +147,7 @@ public class FetchProfileTest extends TestCase { config.addAnnotatedClass( Order.class ); config.addAnnotatedClass( Country.class ); try { - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail(); } catch ( MappingException e ) { @@ -144,7 +162,9 @@ public class FetchProfileTest extends TestCase { config.addAnnotatedClass( SupportTickets.class ); config.addAnnotatedClass( Country.class ); config.addPackage( Customer.class.getPackage().getName() ); - SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(); + SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory( + serviceRegistryHolder.getServiceRegistry() + ); assertTrue( "fetch profile not parsed properly", diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java index f5c6cbd368..91165f18b7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java @@ -7,8 +7,11 @@ import java.io.StringWriter; import junit.framework.TestCase; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.SQLServerDialect; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,6 +24,18 @@ public class FkCircularityTest extends TestCase { private Logger log = LoggerFactory.getLogger(FkCircularityTest.class); + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testJoinedSublcassesInPK() { try { AnnotationConfiguration config = new AnnotationConfiguration(); @@ -28,7 +43,7 @@ public class FkCircularityTest extends TestCase { config.addAnnotatedClass(B.class); config.addAnnotatedClass(C.class); config.addAnnotatedClass(D.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { @@ -50,7 +65,7 @@ public class FkCircularityTest extends TestCase { config.addAnnotatedClass(ClassB.class); config.addAnnotatedClass(ClassC.class); config.addAnnotatedClass(ClassD.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); String[] schema = config .generateSchemaCreationScript(new HSQLDialect()); for (String s : schema) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java index 73b2f763c3..ef34357258 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java @@ -34,7 +34,7 @@ public class JoinColumnOverrideTest extends TestCase { config.addAnnotatedClass(Bunny.class); config.addAnnotatedClass(PointyTooth.class); config.addAnnotatedClass(TwinkleToes.class); - config.buildSessionFactory(); + config.buildSessionFactory( getServiceRegistry() ); String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java index f4091c1d05..772107f8a2 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java @@ -34,7 +34,7 @@ public class JoinColumnOverrideTest extends TestCase { config.addAnnotatedClass(Bunny.class); config.addAnnotatedClass(PointyTooth.class); config.addAnnotatedClass(TwinkleToes.class); - config.buildSessionFactory(); + config.buildSessionFactory( getServiceRegistry() ); String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java index 6786d5cead..5f0d6a5f16 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java @@ -143,7 +143,7 @@ public class ImmutableTest extends TestCase { try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Foobar.class); - config.buildSessionFactory(); + config.buildSessionFactory( getServiceRegistry() ); fail(); } catch (AnnotationException ae) { log.debug("succes"); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java index 0b8ceac840..29c423dfeb 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java @@ -9,8 +9,11 @@ import junit.framework.TestCase; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.EJB3NamingStrategy; +import org.hibernate.cfg.Environment; import org.hibernate.cfg.Mappings; import org.hibernate.mapping.Table; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,13 +26,25 @@ public class NamingStrategyTest extends TestCase { private Logger log = LoggerFactory.getLogger(NamingStrategyTest.class); + private ServiceRegistryHolder serviceRegistryHolder; + + protected void setUp() { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + + protected void tearDown() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } + public void testWithCustomNamingStrategy() throws Exception { try { AnnotationConfiguration config = new AnnotationConfiguration(); config.setNamingStrategy(new DummyNamingStrategy()); config.addAnnotatedClass(Address.class); config.addAnnotatedClass(Person.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } catch( Exception e ) { StringWriter writer = new StringWriter(); @@ -45,7 +60,7 @@ public class NamingStrategyTest extends TestCase { config.setNamingStrategy(EJB3NamingStrategy.INSTANCE); config.addAnnotatedClass(A.class); config.addAnnotatedClass(AddressEntry.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); Mappings mappings = config.createMappings(); boolean foundIt = false; @@ -73,7 +88,7 @@ public class NamingStrategyTest extends TestCase { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Address.class); config.addAnnotatedClass(Person.class); - config.buildSessionFactory(); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } catch( Exception e ) { StringWriter writer = new StringWriter(); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java index 34f39bb40b..a630cceed4 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java @@ -5,6 +5,7 @@ import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.SessionFactory; import org.hibernate.AnnotationException; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Emmanuel Bernard @@ -15,12 +16,19 @@ public class OneToOneErrorTest extends junit.framework.TestCase { cfg.addAnnotatedClass( Show.class ) .addAnnotatedClass( ShowDescription.class ); cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); + ServiceRegistryHolder serviceRegistryHolder = null; try { - SessionFactory sf = cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); fail( "Wrong mappedBy does not fail property" ); } catch (AnnotationException e) { //success } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } \ No newline at end of file diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java index da238e10df..692534beed 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java @@ -4,7 +4,10 @@ package org.hibernate.test.annotations.onetoone.primarykey; import junit.framework.TestCase; import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Environment; import org.hibernate.dialect.SQLServerDialect; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,11 +22,14 @@ public class NullablePrimaryKeyTest extends TestCase { private Logger log = LoggerFactory.getLogger(NullablePrimaryKeyTest.class); public void testGeneratedSql() { + + ServiceRegistryHolder serviceRegistryHolder = null; try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Address.class); config.addAnnotatedClass(Person.class); - config.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { @@ -35,5 +41,10 @@ public class NullablePrimaryKeyTest extends TestCase { } catch (Exception e) { fail(e.getMessage()); } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java b/hibernate-core/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java index 3315044324..f3a9932299 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import junit.framework.Test; import junit.framework.TestSuite; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.testing.junit.UnitTestCase; import org.hibernate.cfg.Configuration; import org.hibernate.util.SerializationHelper; @@ -103,9 +104,21 @@ public class ConfigurationSerializationTest extends UnitTestCase { byte[] bytes = SerializationHelper.serialize( cfg ); cfg = ( Configuration ) SerializationHelper.deserialize( bytes ); - // try to build SF - SessionFactory factory = cfg.buildSessionFactory(); - factory.close(); + SessionFactory factory = null; + ServiceRegistryHolder serviceRegistryHolder = null; + try { + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + // try to build SF + factory = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry()); + } + finally { + if ( factory != null ) { + factory.close(); + } + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/test/common/ServiceRegistryHolder.java b/hibernate-core/src/test/java/org/hibernate/test/common/ServiceRegistryHolder.java new file mode 100644 index 0000000000..c9850fc169 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/common/ServiceRegistryHolder.java @@ -0,0 +1,81 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2010, 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.common; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.cfg.Environment; +import org.hibernate.cfg.internal.ServicesRegistryBootstrap; +import org.hibernate.engine.jdbc.internal.JdbcServicesImpl; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.internal.util.config.ConfigurationHelper; +import org.hibernate.service.classloading.spi.ClassLoaderService; +import org.hibernate.service.internal.ServicesRegistryImpl; +import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; +import org.hibernate.service.spi.ServicesRegistry; + +/** + * @author Gail Badner + */ +public class ServiceRegistryHolder { + private final ServicesRegistryImpl serviceRegistry; + private final Properties properties; + + public ServiceRegistryHolder(Map props) { + properties = new Properties(); + properties.putAll( props ); + Environment.verifyProperties( properties ); + ConfigurationHelper.resolvePlaceHolders( properties ); + serviceRegistry = new ServicesRegistryBootstrap().initiateServicesRegistry( properties ); + properties.putAll( serviceRegistry.getService( JdbcServices.class ).getDialect().getDefaultProperties() ); + } + + public Properties getProperties() { + return properties; + } + + public ServicesRegistry getServiceRegistry() { + return serviceRegistry; + } + + public JdbcServices getJdbcServices() { + return serviceRegistry.getService( JdbcServices.class ); + } + + public JdbcServicesImpl getJdbcServicesImpl() { + return ( JdbcServicesImpl ) getJdbcServices(); + } + + public ClassLoaderService getClassLoaderService() { + return serviceRegistry.getService( ClassLoaderService.class ); + } + + public void destroy() { + if ( serviceRegistry != null ) { + serviceRegistry.destroy(); + } + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/connections/SuppliedConnectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/connections/SuppliedConnectionTest.java index a577c266e5..9bd7e49b12 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/connections/SuppliedConnectionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/connections/SuppliedConnectionTest.java @@ -10,9 +10,10 @@ import org.hibernate.ConnectionReleaseMode; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; -import org.hibernate.connection.UserSuppliedConnectionProvider; +import org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Stoppable; +import org.hibernate.test.common.ConnectionProviderBuilder; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.tool.hbm2ddl.SchemaExport; @@ -23,7 +24,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport; */ public class SuppliedConnectionTest extends ConnectionManagementTestCase { - private ConnectionProvider cp = ConnectionProviderFactory.newConnectionProvider(); + private ConnectionProvider cp = ConnectionProviderBuilder.buildConnectionProvider(); private Connection connectionUnderTest; public SuppliedConnectionTest(String name) { @@ -50,7 +51,7 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase { public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString() ); - cfg.setProperty( Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProvider.class.getName() ); + cfg.setProperty( Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProviderImpl.class.getName() ); boolean supportsScroll = true; Connection conn = null; try { @@ -112,7 +113,10 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase { } } try { - cp.close(); + if ( cp instanceof Stoppable ) { + ( ( Stoppable ) cp ).stop(); + } + cp = null; } catch( Throwable ignore ) { } diff --git a/hibernate-core/src/test/java/org/hibernate/test/extendshbm/ExtendsTest.java b/hibernate-core/src/test/java/org/hibernate/test/extendshbm/ExtendsTest.java index e1f1cdb94b..fa4c222168 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/extendshbm/ExtendsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/extendshbm/ExtendsTest.java @@ -47,7 +47,7 @@ public class ExtendsTest extends UnitTestCase { cfg.addResource( getBaseForMappings() + "extendshbm/Person.hbm.xml" ); cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" ); - cfg.buildSessionFactory(); + cfg.buildSessionFactory( getServiceRegistry() ); assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) ); assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) ); @@ -103,7 +103,7 @@ public class ExtendsTest extends UnitTestCase { ); cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" ); - cfg.buildSessionFactory(); + cfg.buildSessionFactory( getServiceRegistry() ); fail( "Should not be able to build sessionfactory without a Person" ); } @@ -119,7 +119,7 @@ public class ExtendsTest extends UnitTestCase { try { cfg.addResource( getBaseForMappings() + "extendshbm/allseparateinone.hbm.xml" ); - cfg.buildSessionFactory(); + cfg.buildSessionFactory( getServiceRegistry() ); assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) ); assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java index 87f006dd88..70a64e26fb 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java +++ b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java @@ -3,12 +3,14 @@ package org.hibernate.test.instrument.cases; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.test.common.ServiceRegistryHolder; /** * @author Steve Ebersole */ public abstract class AbstractExecutable implements Executable { + private ServiceRegistryHolder serviceRegistryHolder; private SessionFactory factory; public final void prepare() { @@ -17,7 +19,8 @@ public abstract class AbstractExecutable implements Executable { for ( int i = 0; i < resources.length; i++ ) { cfg.addResource( resources[i] ); } - factory = cfg.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() ); + factory = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } public final void complete() { @@ -26,6 +29,9 @@ public abstract class AbstractExecutable implements Executable { } finally { factory.close(); + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java index 595081c4d9..c63b5391fa 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/FooBarTest.java @@ -34,10 +34,8 @@ import org.hibernate.Query; import org.hibernate.QueryException; import org.hibernate.ScrollableResults; import org.hibernate.Transaction; -import org.hibernate.cfg.Environment; import org.hibernate.classic.Session; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.DriverManagerConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; @@ -57,6 +55,7 @@ import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.TimesTenDialect; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.test.common.ConnectionProviderBuilder; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.proxy.HibernateProxy; import org.hibernate.util.JoinedIterator; @@ -4346,8 +4345,7 @@ public class FooBarTest extends LegacyTestCase { } public void testUserProvidedConnection() throws Exception { - ConnectionProvider dcp = new DriverManagerConnectionProvider(); - dcp.configure( Environment.getProperties() ); + ConnectionProvider dcp = ConnectionProviderBuilder.buildConnectionProvider(); Session s = getSessions().openSession( dcp.getConnection() ); Transaction tx = s.beginTransaction(); s.createQuery( "from Fo" ).list(); diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java index 0c3f58860b..808c7fe050 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java @@ -29,7 +29,7 @@ public class MigrationTest extends UnitTestCase { v1cfg.addResource( resource1 ); new SchemaExport( v1cfg ).execute( false, true, true, false ); - SchemaUpdate v1schemaUpdate = new SchemaUpdate( v1cfg ); + SchemaUpdate v1schemaUpdate = new SchemaUpdate( getJdbcServices(), v1cfg ); v1schemaUpdate.execute( true, true ); assertEquals( 0, v1schemaUpdate.getExceptions().size() ); @@ -37,11 +37,11 @@ public class MigrationTest extends UnitTestCase { Configuration v2cfg = new Configuration(); v2cfg.addResource( resource2 ); - SchemaUpdate v2schemaUpdate = new SchemaUpdate( v2cfg ); + SchemaUpdate v2schemaUpdate = new SchemaUpdate( getJdbcServices(), v2cfg ); v2schemaUpdate.execute( true, true ); assertEquals( 0, v2schemaUpdate.getExceptions().size() ); - new SchemaExport( v2cfg ).drop( false, true ); + new SchemaExport( getJdbcServices(), v2cfg ).drop( false, true ); } diff --git a/hibernate-core/src/test/java/org/hibernate/test/stats/StatsTest.java b/hibernate-core/src/test/java/org/hibernate/test/stats/StatsTest.java index 528b678628..6815c2f6ee 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/stats/StatsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/stats/StatsTest.java @@ -86,7 +86,7 @@ public class StatsTest extends FunctionalTestCase { Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries"); coll.setFetchMode(FetchMode.JOIN); coll.setLazy(false); - SessionFactory sf = getCfg().buildSessionFactory(); + SessionFactory sf = getCfg().buildSessionFactory( getServiceRegistry() ); stats = sf.getStatistics(); stats.clear(); stats.setStatisticsEnabled(true); @@ -108,7 +108,7 @@ public class StatsTest extends FunctionalTestCase { coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries"); coll.setFetchMode(FetchMode.SELECT); coll.setLazy(false); - sf = getCfg().buildSessionFactory(); + sf = getCfg().buildSessionFactory( getServiceRegistry() ); stats = sf.getStatistics(); stats.clear(); stats.setStatisticsEnabled(true); diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/UnitTestCase.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/UnitTestCase.java index b500632d17..0726cc837a 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/UnitTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/UnitTestCase.java @@ -35,6 +35,11 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.hibernate.cfg.Environment; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.ServicesRegistry; +import org.hibernate.test.common.ServiceRegistryHolder; /** * A basic JUnit {@link junit.framework.TestCase} subclass for @@ -46,6 +51,8 @@ public abstract class UnitTestCase extends junit.framework.TestCase { private static final Logger log = LoggerFactory.getLogger( UnitTestCase.class ); + private ServiceRegistryHolder serviceRegistryHolder; + public UnitTestCase(String string) { super( string ); } @@ -81,6 +88,29 @@ public abstract class UnitTestCase extends junit.framework.TestCase { } } + @Override + protected void tearDown() throws Exception { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + serviceRegistryHolder = null; + } + } + + protected ServicesRegistry getServiceRegistry() { + if ( serviceRegistryHolder == null ) { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + return serviceRegistryHolder.getServiceRegistry(); + } + + protected JdbcServices getJdbcServices() { + return getServiceRegistry().getService( JdbcServices.class ); + } + + protected ConnectionProvider getConnectionProvider() { + return getJdbcServices().getConnectionProvider(); + } + private static class FailureExpectedTestPassedException extends Exception { public FailureExpectedTestPassedException() { super( "Test marked as FailureExpected, but did not fail!" ); diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/ExecutionEnvironment.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/ExecutionEnvironment.java index dc843ff239..32992cade3 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/ExecutionEnvironment.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/ExecutionEnvironment.java @@ -23,9 +23,11 @@ */ package org.hibernate.testing.junit.functional; +import java.util.HashMap; import java.util.Iterator; import java.sql.Blob; import java.sql.Clob; +import java.util.Map; import org.hibernate.dialect.Dialect; import org.hibernate.cfg.Configuration; @@ -37,6 +39,9 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Collection; +import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; +import org.hibernate.service.spi.ServicesRegistry; +import org.hibernate.test.common.ServiceRegistryHolder; /** * {@inheritDoc} @@ -49,6 +54,8 @@ public class ExecutionEnvironment { private final ExecutionEnvironment.Settings settings; + private Map conectionProviderInjectionProperties; + private ServiceRegistryHolder serviceRegistryHolder; private Configuration configuration; private SessionFactory sessionFactory; private boolean allowRebuild; @@ -73,11 +80,15 @@ public class ExecutionEnvironment { return configuration; } + public ServicesRegistry getServiceRegistry() { + return serviceRegistryHolder.getServiceRegistry(); + } + public SessionFactory getSessionFactory() { return sessionFactory; } - public void initialize() { + public void initialize(Map conectionProviderInjectionProperties) { if ( sessionFactory != null ) { throw new IllegalStateException( "attempt to initialize already initialized ExecutionEnvironment" ); } @@ -85,6 +96,7 @@ public class ExecutionEnvironment { return; } + this.conectionProviderInjectionProperties = conectionProviderInjectionProperties; Configuration configuration = new Configuration(); configuration.setProperty( Environment.CACHE_PROVIDER, "org.hibernate.cache.HashtableCacheProvider" ); @@ -103,13 +115,28 @@ public class ExecutionEnvironment { applyCacheSettings( configuration ); settings.afterConfigurationBuilt( configuration.createMappings(), getDialect() ); - SessionFactory sessionFactory = configuration.buildSessionFactory(); this.configuration = configuration; - this.sessionFactory = sessionFactory; + + serviceRegistryHolder = new ServiceRegistryHolder( getServiceRegistryProperties() ); + sessionFactory = configuration.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); settings.afterSessionFactoryBuilt( ( SessionFactoryImplementor ) sessionFactory ); } + private Map getServiceRegistryProperties() { + Map serviceRegistryProperties = configuration.getProperties(); + if ( conectionProviderInjectionProperties != null && conectionProviderInjectionProperties.size() > 0 ) { + serviceRegistryProperties = new HashMap( + configuration.getProperties().size() + conectionProviderInjectionProperties.size() + ); + serviceRegistryProperties.putAll( configuration.getProperties() ); + serviceRegistryProperties.put( + ConnectionProviderInitiator.INJECTION_DATA, conectionProviderInjectionProperties + ); + } + return serviceRegistryProperties; + } + private void applyMappings(Configuration configuration) { String[] mappings = settings.getMappings(); for ( String mapping : mappings ) { @@ -159,7 +186,12 @@ public class ExecutionEnvironment { sessionFactory.close(); sessionFactory = null; } - sessionFactory = configuration.buildSessionFactory(); + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + serviceRegistryHolder = null; + } + serviceRegistryHolder = new ServiceRegistryHolder( getServiceRegistryProperties() ); + sessionFactory = configuration.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); settings.afterSessionFactoryBuilt( ( SessionFactoryImplementor ) sessionFactory ); } @@ -168,6 +200,10 @@ public class ExecutionEnvironment { sessionFactory.close(); sessionFactory = null; } + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + serviceRegistryHolder = null; + } configuration = null; } diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestCase.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestCase.java index aa4ec014f3..da2d44e80d 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestCase.java @@ -23,6 +23,7 @@ */ package org.hibernate.testing.junit.functional; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.HashMap; @@ -90,11 +91,15 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi log.info( "Building locally managed execution env" ); isEnvironmentLocallyManaged = true; environment = new ExecutionEnvironment( this ); - environment.initialize(); + environment.initialize( getConnectionProviderInjectionProperties() ); } prepareTest(); } + protected Map getConnectionProviderInjectionProperties() { + return Collections.EMPTY_MAP; + } + /** * Override {@link junit.framework.TestCase#tearDown()} to tear down * the execution environment if it is locally managed. diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestClassTestSuite.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestClassTestSuite.java index 3b2999082a..1796cf7203 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestClassTestSuite.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/FunctionalTestClassTestSuite.java @@ -23,6 +23,9 @@ */ package org.hibernate.testing.junit.functional; +import java.util.Collections; +import java.util.Map; + import junit.framework.TestSuite; import junit.framework.Test; import junit.framework.TestResult; @@ -127,13 +130,17 @@ public class FunctionalTestClassTestSuite extends TestSuite { log.info( "Building aggregated execution environment" ); try { environment = new ExecutionEnvironment( settings ); - environment.initialize(); + environment.initialize( getConnectionProviderInjectionProperties() ); } catch( Throwable t ) { environmentSetupError = t; } } + protected Map getConnectionProviderInjectionProperties() { + return Collections.EMPTY_MAP; + } + protected void tearDown() { if ( environment != null ) { log.info( "Destroying aggregated execution environment" ); diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/annotations/HibernateTestCase.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/annotations/HibernateTestCase.java index 34bee3d876..7e2fe5be78 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/annotations/HibernateTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/annotations/HibernateTestCase.java @@ -38,8 +38,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.jdbc.Work; +import org.hibernate.service.spi.ServicesRegistry; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.testing.junit.DialectChecks; import org.hibernate.testing.junit.FailureExpected; import org.hibernate.testing.junit.RequiresDialect; @@ -61,6 +65,7 @@ public abstract class HibernateTestCase extends TestCase { protected static Configuration cfg; private static Class lastTestClass; + private ServiceRegistryHolder serviceRegistryHolder; public HibernateTestCase() { super(); @@ -147,6 +152,17 @@ public abstract class HibernateTestCase extends TestCase { handleUnclosedResources(); } + protected ServicesRegistry getServiceRegistry() { + if ( serviceRegistryHolder == null ) { + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + } + return serviceRegistryHolder.getServiceRegistry(); + } + + protected JdbcServices getJdbcServices() { + return getServiceRegistry().getService( JdbcServices.class ); + } + protected static class Skip { private final String reason; private final String testDescription; @@ -265,7 +281,12 @@ public abstract class HibernateTestCase extends TestCase { protected abstract void handleUnclosedResources(); - protected abstract void closeResources(); + protected void closeResources() { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + serviceRegistryHolder = null; + } + } protected String[] getAnnotatedPackages() { return new String[] { }; @@ -295,12 +316,12 @@ public abstract class HibernateTestCase extends TestCase { } protected void runSchemaGeneration() { - SchemaExport export = new SchemaExport( cfg ); + SchemaExport export = new SchemaExport( getJdbcServices(), cfg ); export.create( true, true ); } protected void runSchemaDrop() { - SchemaExport export = new SchemaExport( cfg ); + SchemaExport export = new SchemaExport( getJdbcServices(), cfg ); export.drop( true, true ); } diff --git a/hibernate-core/src/test/java/org/hibernate/testing/tm/ConnectionProviderImpl.java b/hibernate-core/src/test/java/org/hibernate/testing/tm/ConnectionProviderImpl.java index 9c73a197d0..3afb91af59 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/tm/ConnectionProviderImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/tm/ConnectionProviderImpl.java @@ -28,8 +28,9 @@ import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Stoppable; +import org.hibernate.test.common.ConnectionProviderBuilder; /** * A {@link ConnectionProvider} implementation adding JTA-style transactionality @@ -39,7 +40,7 @@ import org.hibernate.connection.ConnectionProviderFactory; * @author Steve Ebersole */ public class ConnectionProviderImpl implements ConnectionProvider { - private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider(); + private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider(); private boolean isTransactional; @@ -74,7 +75,9 @@ public class ConnectionProviderImpl implements ConnectionProvider { } public void close() throws HibernateException { - actualConnectionProvider.close(); + if ( actualConnectionProvider instanceof Stoppable ) { + ( ( Stoppable ) actualConnectionProvider ).stop(); + } } public boolean supportsAggressiveRelease() { diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java index 95dd417454..ca53cc4ec3 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java @@ -74,7 +74,6 @@ import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.Settings; -import org.hibernate.cfg.SettingsFactory; import org.hibernate.cfg.annotations.reflection.XMLContext; import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider; import org.hibernate.ejb.instrument.InterceptFieldClassFileTransformer; @@ -94,6 +93,9 @@ import org.hibernate.mapping.AuxiliaryDatabaseObject; import org.hibernate.mapping.PersistentClass; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.JACCConfiguration; +import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.transaction.JDBCTransactionFactory; import org.hibernate.util.CollectionHelper; import org.hibernate.util.ReflectHelper; @@ -142,7 +144,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { private String cfgXmlResource; private AnnotationConfiguration cfg; - private SettingsFactory settingsFactory; + private final Map connectionProviderInjectionData; //made transient and not restored in deserialization on purpose, should no longer be called after restoration private transient EventListenerConfigurator listenerConfigurator; private PersistenceUnitTransactionType transactionType; @@ -153,8 +155,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { public Ejb3Configuration() { - settingsFactory = new InjectionSettingsFactory(); - cfg = new AnnotationConfiguration( settingsFactory ); + connectionProviderInjectionData = new HashMap(); + cfg = new AnnotationConfiguration(); cfg.setEntityNotFoundDelegate( ejb3EntityNotFoundDelegate ); listenerConfigurator = new EventListenerConfigurator( this ); } @@ -169,7 +171,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { if ( ds != null ) { Map cpInjection = new HashMap(); cpInjection.put( "dataSource", ds ); - ( (InjectionSettingsFactory) settingsFactory ).setConnectionProviderInjectionData( cpInjection ); + connectionProviderInjectionData.put( ConnectionProviderInitiator.INJECTION_DATA, cpInjection ); this.setProperty( Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName() ); } } @@ -900,11 +902,11 @@ public class Ejb3Configuration implements Serializable, Referenceable { configure( (Properties)null, null ); NamingHelper.bind(this); return new EntityManagerFactoryImpl( - cfg.buildSessionFactory(), transactionType, discardOnClose, getSessionInterceptorClass( cfg.getProperties() ), - cfg + cfg, + connectionProviderInjectionData ); } catch (HibernateException e) { @@ -1350,8 +1352,9 @@ public class Ejb3Configuration implements Serializable, Referenceable { } } - - public Settings buildSettings() throws HibernateException { + /* + TODO: not needed any more? + public Settings buildSettings(ConnectionProvider connectionProvider) throws HibernateException { Thread thread = null; ClassLoader contextClassLoader = null; if (overridenClassLoader != null) { @@ -1360,12 +1363,13 @@ public class Ejb3Configuration implements Serializable, Referenceable { thread.setContextClassLoader( overridenClassLoader ); } try { - return settingsFactory.buildSettings( cfg.getProperties() ); + return settingsFactory.buildSettings( cfg.getProperties(), connectionProvider ); } finally { if (thread != null) thread.setContextClassLoader( contextClassLoader ); } } + */ public Ejb3Configuration addProperties(Properties props) { cfg.addProperties( props ); @@ -1501,8 +1505,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { return cfg.getEventListeners(); } - SessionFactory buildSessionFactory() throws HibernateException { - return cfg.buildSessionFactory(); + SessionFactory buildSessionFactory(ServicesRegistry serviceRegistry) throws HibernateException { + return cfg.buildSessionFactory( serviceRegistry ); } public Iterator getTableMappings() { diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerFactoryImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerFactoryImpl.java index 3d096c8dab..ee1e4b6a71 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerFactoryImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerFactoryImpl.java @@ -41,6 +41,7 @@ import org.hibernate.SessionFactory; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.EntityMode; +import org.hibernate.cfg.internal.ServicesRegistryBootstrap; import org.hibernate.metadata.ClassMetadata; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.mapping.PersistentClass; @@ -48,6 +49,8 @@ import org.hibernate.cfg.Configuration; import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.metamodel.MetamodelImpl; import org.hibernate.ejb.util.PersistenceUtilHelper; +import org.hibernate.service.internal.ServicesRegistryImpl; +import org.hibernate.service.spi.ServicesRegistry; /** * Actual Hiberate implementation of {@link javax.persistence.EntityManagerFactory}. @@ -57,6 +60,7 @@ import org.hibernate.ejb.util.PersistenceUtilHelper; * @author Steve Ebersole */ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory { + private final transient ServicesRegistryImpl serviceRegistry; private final SessionFactory sessionFactory; private final PersistenceUnitTransactionType transactionType; private final boolean discardOnClose; @@ -65,16 +69,25 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory { private final Metamodel metamodel; private final HibernatePersistenceUnitUtil util; private final Map properties; + private final Map connectionProviderInjectionData; + private final PersistenceUtilHelper.MetadataCache cache = new PersistenceUtilHelper.MetadataCache(); @SuppressWarnings( "unchecked" ) public EntityManagerFactoryImpl( - SessionFactory sessionFactory, PersistenceUnitTransactionType transactionType, boolean discardOnClose, Class sessionInterceptorClass, - Configuration cfg) { - this.sessionFactory = sessionFactory; + Configuration cfg, + Map connectionProviderInjectionData) { + // FIXME: Get rid of this temporary way of creating the service registry for EM + Map serviceRegistryProperties = new HashMap( + cfg.getProperties().size() + connectionProviderInjectionData.size() + ); + serviceRegistryProperties.putAll( cfg.getProperties() ); + serviceRegistryProperties.putAll( connectionProviderInjectionData ); + this.serviceRegistry = new ServicesRegistryBootstrap().initiateServicesRegistry( serviceRegistryProperties ); + this.sessionFactory = cfg.buildSessionFactory( serviceRegistry ); this.transactionType = transactionType; this.discardOnClose = discardOnClose; this.sessionInterceptorClass = sessionInterceptorClass; @@ -93,6 +106,7 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory { addAll( props, ( (SessionFactoryImplementor) sessionFactory ).getProperties() ); addAll( props, cfg.getProperties() ); this.properties = Collections.unmodifiableMap( props ); + this.connectionProviderInjectionData = new HashMap(); } private static void addAll(HashMap propertyMap, Properties properties) { @@ -125,6 +139,7 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory { public void close() { sessionFactory.close(); + serviceRegistry.destroy(); } public Map getProperties() { diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java index 63817d1085..7271e4dbd8 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java @@ -24,12 +24,14 @@ package org.hibernate.ejb; import java.util.Map; +import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.LoadState; import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.ProviderUtil; +import org.hibernate.cfg.internal.ServicesRegistryBootstrap; import org.hibernate.ejb.util.PersistenceUtilHelper; /** diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/InjectionSettingsFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/InjectionSettingsFactory.java deleted file mode 100644 index 670f84de76..0000000000 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/InjectionSettingsFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009, Red Hat Middleware LLC 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 Middleware LLC. - * - * 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 - */ - -//$Id$ -package org.hibernate.ejb; - -import java.util.Map; -import java.util.Properties; - -import org.hibernate.cfg.SettingsFactory; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; - -/** - * @author Emmanuel Bernard - */ -public class InjectionSettingsFactory extends SettingsFactory { - private Map connectionProviderInjectionData; - - /** - * Map where the key represents the javabean property in witch - * Object will be injected - * - * @param connectionProviderInjectionData - * - */ - public void setConnectionProviderInjectionData(Map connectionProviderInjectionData) { - this.connectionProviderInjectionData = connectionProviderInjectionData; - } - - protected ConnectionProvider createConnectionProvider(Properties properties) { - return ConnectionProviderFactory.newConnectionProvider( properties, connectionProviderInjectionData ); - } -} diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/connection/InjectedDataSourceConnectionProvider.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/connection/InjectedDataSourceConnectionProvider.java index 3e4494bcb5..8bcb156daa 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/connection/InjectedDataSourceConnectionProvider.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/connection/InjectedDataSourceConnectionProvider.java @@ -28,12 +28,13 @@ import javax.sql.DataSource; import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; -import org.hibernate.connection.DatasourceConnectionProvider; +import org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl; + import org.slf4j.LoggerFactory; import org.slf4j.Logger; /** - * A specialization of {@link DatasourceConnectionProvider} which uses the {@link DataSource} specified vi + * A specialization of {@link DatasourceConnectionProviderImpl} which uses the {@link DataSource} specified vi * {@link #setDataSource} rather than locating it from JNDI. *

* NOTE : {@link #setDataSource} must be called prior to {@link #configure}. @@ -42,7 +43,7 @@ import org.slf4j.Logger; * * @author Emmanuel Bernard */ -public class InjectedDataSourceConnectionProvider extends DatasourceConnectionProvider { +public class InjectedDataSourceConnectionProvider extends DatasourceConnectionProviderImpl { private final Logger log = LoggerFactory.getLogger( InjectedDataSourceConnectionProvider.class ); private String user; diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java index 1f80cfab52..fceafbe65b 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java @@ -118,6 +118,7 @@ public abstract class TestCase extends HibernateTestCase { if ( factory != null ) { factory.close(); } + super.closeResources(); } protected EntityManager getOrCreateEntityManager() { diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/MetadataTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/MetadataTest.java index bb2cf6443e..c988686377 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/MetadataTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/metadata/MetadataTest.java @@ -61,7 +61,7 @@ public class MetadataTest extends TestCase { configure( cfg ); cfg.addAnnotatedClass( WithGenericCollection.class ); cfg.buildMappings(); - SessionFactoryImplementor sfi = (SessionFactoryImplementor) cfg.buildSessionFactory(); + SessionFactoryImplementor sfi = (SessionFactoryImplementor) cfg.buildSessionFactory( getServiceRegistry() ); MetamodelImpl.buildMetamodel( cfg.getClassMappings(), sfi ); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractSessionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractSessionTest.java index d8488b3fbe..6f3d205719 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractSessionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractSessionTest.java @@ -9,8 +9,11 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.testng.annotations.*; /** @@ -22,6 +25,7 @@ import org.testng.annotations.*; public abstract class AbstractSessionTest { protected Configuration config; + private ServiceRegistryHolder serviceRegistryHolder; private SessionFactory sessionFactory; private Session session ; private AuditReader auditReader; @@ -40,7 +44,8 @@ public abstract class AbstractSessionTest { this.initMappings(); - sessionFactory = config.buildSessionFactory(); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + sessionFactory = config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } protected abstract void initMappings() throws MappingException, URISyntaxException ; @@ -60,7 +65,15 @@ public abstract class AbstractSessionTest { @AfterClass public void closeSessionFactory() { - sessionFactory.close(); + try { + sessionFactory.close(); + } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + serviceRegistryHolder = null; + } + } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractEntityCollectionRegionTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractEntityCollectionRegionTestCase.java index c196a1e9dc..d029b99e1a 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractEntityCollectionRegionTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractEntityCollectionRegionTestCase.java @@ -64,7 +64,9 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); String entityCfg = "entity"; cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, entityCfg); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); supportedAccessTypeTest(regionFactory, cfg.getProperties()); } @@ -82,14 +84,18 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg */ public void testIsTransactionAware() throws Exception { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); assertTrue("Region is transaction-aware", region.isTransactionAware()); CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport()); cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); // Make it non-transactional cfg.getProperties().remove(Environment.TRANSACTION_MANAGER_STRATEGY); - regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); assertFalse("Region is not transaction-aware", region.isTransactionAware()); CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport()); @@ -97,7 +103,9 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg public void testGetCacheDataDescription() throws Exception { Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription()); CacheDataDescription cdd = region.getCacheDataDescription(); assertNotNull(cdd); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractGeneralDataRegionTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractGeneralDataRegionTestCase.java index 4d69d2887c..1cb2e9661f 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractGeneralDataRegionTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractGeneralDataRegionTestCase.java @@ -72,7 +72,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm private void evictOrRemoveTest() throws Exception { Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); CacheAdapter localCache = getInfinispanCache(regionFactory); boolean invalidation = localCache.isClusteredInvalidation(); @@ -83,7 +85,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); cfg = createConfiguration(); - regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory, getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); @@ -121,7 +125,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm private void evictOrRemoveAllTest(String configName) throws Exception { Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); CacheAdapter localCache = getInfinispanCache(regionFactory); // Sleep a bit to avoid concurrent FLUSH problem @@ -131,7 +137,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); cfg = createConfiguration(); - regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); CacheAdapter remoteCache = getInfinispanCache(regionFactory); // Sleep a bit to avoid concurrent FLUSH problem diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractNonFunctionalTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractNonFunctionalTestCase.java index acf3f93eee..84ffd1264b 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractNonFunctionalTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/AbstractNonFunctionalTestCase.java @@ -27,6 +27,10 @@ import java.util.Set; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.util.CacheHelper; +import org.hibernate.cfg.Environment; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.testing.junit.UnitTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestSupport; import org.infinispan.Cache; diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java index 0c77292874..5b6c30ca7b 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/AbstractCollectionRegionAccessStrategyTestCase.java @@ -53,9 +53,11 @@ import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.util.ComparableComparator; import org.infinispan.Cache; import org.infinispan.transaction.tm.BatchModeTransactionManager; @@ -522,6 +524,7 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs private final String configResource; private final String configName; private String preferIPv4Stack; + private ServiceRegistryHolder serviceRegistryHolder; public AccessStrategyTestSetup(Test test, String configName) { this(test, configName, null); @@ -541,11 +544,19 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + localCfg = createConfiguration(configName, configResource); - localRegionFactory = CacheTestUtil.startRegionFactory(localCfg); + localRegionFactory = CacheTestUtil.startRegionFactory( + serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(), + localCfg + ); remoteCfg = createConfiguration(configName, configResource); - remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg); + remoteRegionFactory = CacheTestUtil.startRegionFactory( + serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(), + remoteCfg + ); } @Override @@ -559,11 +570,18 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); } - if (localRegionFactory != null) - localRegionFactory.stop(); + try { + if (localRegionFactory != null) + localRegionFactory.stop(); - if (remoteRegionFactory != null) - remoteRegionFactory.stop(); + if (remoteRegionFactory != null) + remoteRegionFactory.stop(); + } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/TransactionalExtraAPITestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/TransactionalExtraAPITestCase.java index e77ccd204b..755de34c89 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/TransactionalExtraAPITestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/collection/TransactionalExtraAPITestCase.java @@ -54,7 +54,9 @@ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase if (getCollectionAccessStrategy() == null) { Configuration cfg = createConfiguration(); - InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.java index b65ae2d767..be99245d70 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.java @@ -41,8 +41,10 @@ import org.hibernate.cache.infinispan.impl.BaseRegion; import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.FlagAdapter; import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; +import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.util.ComparableComparator; import org.infinispan.transaction.tm.BatchModeTransactionManager; @@ -637,6 +639,7 @@ public abstract class AbstractEntityRegionAccessStrategyTestCase extends Abstrac private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; private final String configName; private String preferIPv4Stack; + private ServiceRegistryHolder serviceRegistryHolder; public AccessStrategyTestSetup(Test test, String configName) { super(test); @@ -658,22 +661,37 @@ public abstract class AbstractEntityRegionAccessStrategyTestCase extends Abstrac preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); + localCfg = createConfiguration(configName); - localRegionFactory = CacheTestUtil.startRegionFactory(localCfg); + localRegionFactory = CacheTestUtil.startRegionFactory( + serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(), + localCfg + ); remoteCfg = createConfiguration(configName); - remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg); + remoteRegionFactory = CacheTestUtil.startRegionFactory( + serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(), + remoteCfg + ); } @Override protected void tearDown() throws Exception { super.tearDown(); - if (localRegionFactory != null) - localRegionFactory.stop(); + try { + if (localRegionFactory != null) + localRegionFactory.stop(); - if (remoteRegionFactory != null) - remoteRegionFactory.stop(); + if (remoteRegionFactory != null) + remoteRegionFactory.stop(); + } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/TransactionalExtraAPITestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/TransactionalExtraAPITestCase.java index 4996bca881..3079be28e5 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/TransactionalExtraAPITestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/TransactionalExtraAPITestCase.java @@ -60,7 +60,9 @@ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase if (getEntityAccessStrategy() == null) { Configuration cfg = createConfiguration(); - InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java index 2feceed6db..7b188b615d 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/ConcurrentWriteTest.java @@ -26,8 +26,10 @@ package org.hibernate.test.cache.infinispan.functional; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; @@ -44,7 +46,7 @@ import org.hibernate.Session; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeConnectionProviderImpl; @@ -148,6 +150,11 @@ public class ConcurrentWriteTest extends SingleNodeTestCase { cfg.setProperty(DualNodeTestCase.NODE_ID_PROP, DualNodeTestCase.LOCAL); } + @Override + protected Map getConnectionProviderInjectionProperties() { + return Collections.singletonMap( DualNodeTestCase.NODE_ID_FIELD, DualNodeTestCase.LOCAL ); + } + @Override protected boolean getUseQueryCache() { return true; diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/JndiRegionFactoryTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/JndiRegionFactoryTestCase.java index 7ea83aee06..274e526945 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/JndiRegionFactoryTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/JndiRegionFactoryTestCase.java @@ -98,7 +98,7 @@ public class JndiRegionFactoryTestCase extends SingleNodeTestCase { getEnvironment().getSessionFactory().close(); bindToJndi = false; ExecutionEnvironment environment = new ExecutionEnvironment( this ); - environment.initialize(); + environment.initialize( getConnectionProviderInjectionProperties() ); setEnvironment(environment); addEntityCheckCache(); JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) ((SessionFactoryImplementor) diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/SingleNodeTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/SingleNodeTestCase.java index 8e40eafa9e..88ad695cfb 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/SingleNodeTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/SingleNodeTestCase.java @@ -7,7 +7,7 @@ import org.hibernate.cache.RegionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/BulkOperationsTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/BulkOperationsTestCase.java index b638497534..d737cd6c4c 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/BulkOperationsTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/bulk/BulkOperationsTestCase.java @@ -34,7 +34,7 @@ import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.classic.Session; -import org.hibernate.connection.ConnectionProvider; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.test.cache.infinispan.functional.Contact; diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeConnectionProviderImpl.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeConnectionProviderImpl.java index e6c735d793..ef97c350b2 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeConnectionProviderImpl.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeConnectionProviderImpl.java @@ -28,8 +28,9 @@ import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Stoppable; +import org.hibernate.test.common.ConnectionProviderBuilder; /** * A {@link ConnectionProvider} implementation adding JTA-style transactionality around the returned @@ -38,7 +39,7 @@ import org.hibernate.connection.ConnectionProviderFactory; * @author Brian Stansberry */ public class DualNodeConnectionProviderImpl implements ConnectionProvider { - private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider(); + private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider(); private String nodeId; private boolean isTransactional; @@ -46,10 +47,11 @@ public class DualNodeConnectionProviderImpl implements ConnectionProvider { return actualConnectionProvider; } - public void configure(Properties props) throws HibernateException { - nodeId = props.getProperty(DualNodeTestCase.NODE_ID_PROP); - if (nodeId == null) - throw new HibernateException(DualNodeTestCase.NODE_ID_PROP + " not configured"); + public void setNodeId(String nodeId) throws HibernateException { + if (nodeId == null) { + throw new HibernateException( "nodeId not configured" ); + } + this.nodeId = nodeId; } public Connection getConnection() throws SQLException { @@ -76,7 +78,9 @@ public class DualNodeConnectionProviderImpl implements ConnectionProvider { } public void close() throws HibernateException { - actualConnectionProvider.close(); + if ( actualConnectionProvider instanceof Stoppable ) { + ( ( Stoppable ) actualConnectionProvider ).stop(); + } } public boolean supportsAggressiveRelease() { diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTestCase.java index a8cc2d7ae1..a63d0ea325 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/DualNodeTestCase.java @@ -21,6 +21,9 @@ */ package org.hibernate.test.cache.infinispan.functional.cluster; +import java.util.Collections; +import java.util.Map; + import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; @@ -43,6 +46,7 @@ public abstract class DualNodeTestCase extends FunctionalTestCase { private static final Log log = LogFactory.getLog(DualNodeTestCase.class); public static final String NODE_ID_PROP = "hibernate.test.cluster.node.id"; + public static final String NODE_ID_FIELD = "nodeId"; public static final String LOCAL = "local"; public static final String REMOTE = "remote"; private ExecutionEnvironment secondNodeEnvironment; @@ -71,11 +75,16 @@ public abstract class DualNodeTestCase extends FunctionalTestCase { configureFirstNode(cfg); } + @Override + protected Map getConnectionProviderInjectionProperties() { + return getFirstNodeConnectionProviderInjectionProperties(); + } + @Override protected void prepareTest() throws Exception { log.info("Building second node locally managed execution env"); secondNodeEnvironment = new ExecutionEnvironment(new SecondNodeSettings()); - secondNodeEnvironment.initialize(); + secondNodeEnvironment.initialize( getSecondNodeConnectionProviderInjectionProperties() ); super.prepareTest(); } @@ -142,6 +151,10 @@ public abstract class DualNodeTestCase extends FunctionalTestCase { cfg.setProperty(NODE_ID_PROP, LOCAL); } + protected Map getFirstNodeConnectionProviderInjectionProperties() { + return Collections.singletonMap( NODE_ID_FIELD, LOCAL ); + } + /** * Apply any node-specific configurations to our second node. * @@ -151,7 +164,11 @@ public abstract class DualNodeTestCase extends FunctionalTestCase { protected void configureSecondNode(Configuration cfg) { cfg.setProperty(NODE_ID_PROP, REMOTE); } - + + protected Map getSecondNodeConnectionProviderInjectionProperties() { + return Collections.singletonMap( NODE_ID_FIELD, REMOTE ); + } + protected void sleep(long ms) { try { Thread.sleep(ms); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/QueryRegionImplTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/QueryRegionImplTestCase.java index e0565d4041..a9b49acec0 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/QueryRegionImplTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/query/QueryRegionImplTestCase.java @@ -90,7 +90,8 @@ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase { private void putDoesNotBlockGetTest() throws Exception { Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport()); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); @@ -175,7 +176,9 @@ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase { private void getDoesNotBlockPutTest() throws Exception { Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/TimestampsRegionImplTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/TimestampsRegionImplTestCase.java index ff8cdd4379..8d2c572e12 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/TimestampsRegionImplTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/timestamp/TimestampsRegionImplTestCase.java @@ -86,12 +86,16 @@ public class TimestampsRegionImplTestCase extends AbstractGeneralDataRegionTestC public void testClearTimestampsRegionInIsolated() throws Exception { Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport()); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg, getCacheTestSupport() + ); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); Configuration cfg2 = createConfiguration(); - InfinispanRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory(cfg2, getCacheTestSupport()); + InfinispanRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory( + getConnectionProvider(), cfg2, getCacheTestSupport() + ); // Sleep a bit to avoid concurrent FLUSH problem avoidConcurrentFlush(); diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java index b8b4082f01..3b3ce958f9 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java @@ -33,6 +33,8 @@ import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; import org.hibernate.stat.Statistics; import org.hibernate.test.cache.infinispan.functional.Item; +import org.hibernate.test.common.ServiceRegistryHolder; + import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; @@ -70,10 +72,12 @@ public class JBossStandaloneJtaExampleTest extends TestCase { private static final JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup(); Context ctx; Main jndiServer; + private ServiceRegistryHolder serviceRegistryHolder; @Override protected void setUp() throws Exception { super.setUp(); + serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); jndiServer = startJndiServer(); ctx = createJndiContext(); bindTransactionManager(); @@ -83,9 +87,16 @@ public class JBossStandaloneJtaExampleTest extends TestCase { @Override protected void tearDown() throws Exception { - super.tearDown(); - ctx.close(); - jndiServer.stop(); + try { + super.tearDown(); + ctx.close(); + jndiServer.stop(); + } + finally { + if ( serviceRegistryHolder != null ) { + serviceRegistryHolder.destroy(); + } + } } public void testPersistAndLoadUnderJta() throws Exception { @@ -290,6 +301,6 @@ public class JBossStandaloneJtaExampleTest extends TestCase { Collection coll = (Collection) iter.next(); cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), "transactional"); } - return cfg.buildSessionFactory(); + return cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ); } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaConnectionProvider.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaConnectionProvider.java index b9af7ea892..45bfcb1611 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaConnectionProvider.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/XaConnectionProvider.java @@ -26,8 +26,9 @@ import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Stoppable; +import org.hibernate.test.common.ConnectionProviderBuilder; /** * XaConnectionProvider. @@ -36,7 +37,7 @@ import org.hibernate.connection.ConnectionProviderFactory; * @since 3.5 */ public class XaConnectionProvider implements ConnectionProvider { - private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider(); + private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider(); private boolean isTransactional; public static ConnectionProvider getActualConnectionProvider() { @@ -69,7 +70,9 @@ public class XaConnectionProvider implements ConnectionProvider { } public void close() throws HibernateException { - actualConnectionProvider.close(); + if ( actualConnectionProvider instanceof Stoppable ) { + ( ( Stoppable ) actualConnectionProvider ).stop(); + } } public boolean supportsAggressiveRelease() { diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestUtil.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestUtil.java index e614bb6b4a..152854f26d 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestUtil.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestUtil.java @@ -36,6 +36,8 @@ import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.ServicesRegistry; /** * Utilities for cache testing. @@ -71,10 +73,11 @@ public class CacheTestUtil { return cfg; } - public static InfinispanRegionFactory startRegionFactory(Configuration cfg) throws ClassNotFoundException, - InstantiationException, IllegalAccessException { + public static InfinispanRegionFactory startRegionFactory(ConnectionProvider connectionProvider, + Configuration cfg) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Settings settings = cfg.buildSettings(); + Settings settings = cfg.buildSettings( connectionProvider ); Properties properties = cfg.getProperties(); String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY); @@ -86,9 +89,11 @@ public class CacheTestUtil { return regionFactory; } - public static InfinispanRegionFactory startRegionFactory(Configuration cfg, CacheTestSupport testSupport) + public static InfinispanRegionFactory startRegionFactory(ConnectionProvider connectionProvider, + Configuration cfg, + CacheTestSupport testSupport) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - InfinispanRegionFactory factory = startRegionFactory(cfg); + InfinispanRegionFactory factory = startRegionFactory(connectionProvider, cfg); testSupport.registerFactory(factory); return factory; }