From 3712e1ad7efccd2ba0c24b3d7d3b23f84d948b9d Mon Sep 17 00:00:00 2001 From: JPAV Date: Mon, 17 Jan 2011 23:49:48 -0600 Subject: [PATCH] Give each project a single logger --- .../internal/C3P0ConnectionProvider.java | 55 +- .../java/org/hibernate/AssertionFailure.java | 17 - .../bytecode/cglib/BytecodeProviderImpl.java | 26 +- .../bytecode/cglib/CglibClassTransformer.java | 4 +- .../javassist/BytecodeProviderImpl.java | 18 +- .../javassist/JavassistClassTransformer.java | 4 +- .../cache/AbstractJndiBoundCacheProvider.java | 1 + .../main/java/org/hibernate/cache/Logger.java | 218 ---- .../cache/NonstrictReadWriteCache.java | 23 +- .../org/hibernate/cache/ReadOnlyCache.java | 9 +- .../org/hibernate/cache/ReadWriteCache.java | 52 +- .../hibernate/cache/StandardQueryCache.java | 85 +- .../hibernate/cache/TransactionalCache.java | 19 +- .../cache/UpdateTimestampsCache.java | 10 +- .../impl/bridge/CollectionRegionAdapter.java | 1 + .../impl/bridge/EntityRegionAdapter.java | 1 + .../hibernate/cache/impl/bridge/Logger.java | 29 - .../RegionFactoryCacheProviderBridge.java | 4 +- .../org/hibernate/cfg/AnnotationBinder.java | 190 +--- .../java/org/hibernate/cfg/BinderHelper.java | 23 +- .../hibernate/cfg/CollectionSecondPass.java | 25 +- .../java/org/hibernate/cfg/Configuration.java | 325 +----- .../hibernate/cfg/EJB3DTDEntityResolver.java | 38 +- .../java/org/hibernate/cfg/Ejb3Column.java | 31 +- .../java/org/hibernate/cfg/Environment.java | 85 +- .../java/org/hibernate/cfg/HbmBinder.java | 109 +- .../cfg/NamedSQLQuerySecondPass.java | 20 +- .../org/hibernate/cfg/PropertyContainer.java | 17 +- .../org/hibernate/cfg/SettingsFactory.java | 199 +--- .../cfg/annotations/CollectionBinder.java | 56 +- .../cfg/annotations/EntityBinder.java | 43 +- .../hibernate/cfg/annotations/ListBinder.java | 21 +- .../cfg/annotations/PropertyBinder.java | 34 +- .../cfg/annotations/QueryBinder.java | 23 +- .../ResultsetMappingSecondPass.java | 17 +- .../hibernate/cfg/annotations/SetBinder.java | 17 +- .../cfg/annotations/SimpleValueBinder.java | 25 +- .../cfg/annotations/TableBinder.java | 26 +- .../JPAOverridenAnnotationReader.java | 17 +- .../annotations/reflection/XMLContext.java | 35 +- .../BeanValidationEventListener.java | 19 +- .../cfg/beanvalidation/TypeSafeActivator.java | 17 - .../HibernateSearchEventListenerRegister.java | 28 +- .../collection/PersistentArrayHolder.java | 17 +- .../hibernate/context/JTASessionContext.java | 19 +- .../context/ThreadLocalSessionContext.java | 59 +- .../org/hibernate/dialect/DerbyDialect.java | 17 +- .../java/org/hibernate/dialect/Dialect.java | 19 +- .../java/org/hibernate/dialect/H2Dialect.java | 19 +- .../org/hibernate/dialect/HSQLDialect.java | 17 +- .../org/hibernate/dialect/Oracle9Dialect.java | 17 +- .../org/hibernate/dialect/OracleDialect.java | 17 +- .../hibernate/dialect/RDMSOS2200Dialect.java | 17 +- .../dialect/function/TemplateRenderer.java | 18 +- .../org/hibernate/dialect/lock/Logger.java | 25 - .../PessimisticReadUpdateLockingStrategy.java | 1 + ...PessimisticWriteUpdateLockingStrategy.java | 1 + .../dialect/lock/UpdateLockingStrategy.java | 1 + .../resolver/AbstractDialectResolver.java | 23 +- .../resolver/BasicSQLExceptionConverter.java | 14 +- .../dialect/resolver/DialectFactory.java | 21 +- .../dialect/resolver/DialectResolverSet.java | 17 +- .../resolver/StandardDialectResolver.java | 29 +- .../org/hibernate/engine/ActionQueue.java | 109 +- .../java/org/hibernate/engine/Cascade.java | 61 +- .../org/hibernate/engine/CascadingAction.java | 73 +- .../org/hibernate/engine/CollectionEntry.java | 22 +- .../org/hibernate/engine/Collections.java | 73 +- .../org/hibernate/engine/IdentifierValue.java | 31 +- .../org/hibernate/engine/ParameterBinder.java | 21 +- .../org/hibernate/engine/QueryParameters.java | 27 +- .../engine/StatefulPersistenceContext.java | 156 +-- .../org/hibernate/engine/TwoPhaseLoad.java | 43 +- .../org/hibernate/engine/VersionValue.java | 29 +- .../java/org/hibernate/engine/Versioning.java | 38 +- .../engine/jdbc/ResultSetWrapperProxy.java | 18 +- .../batch/internal/AbstractBatchImpl.java | 2 +- .../jdbc/batch/internal/BatchBuilder.java | 2 +- .../jdbc/batch/internal/BatchingBatch.java | 22 +- .../jdbc/batch/internal/NonBatchingBatch.java | 1 + .../jdbc/internal/ConnectionManagerImpl.java | 35 +- .../engine/jdbc/internal/JDBCContextImpl.java | 68 +- .../internal/JdbcResourceRegistryImpl.java | 90 +- .../jdbc/internal/JdbcServicesImpl.java | 63 +- .../jdbc/internal/LogicalConnectionImpl.java | 125 +- .../jdbc/internal/StatementPreparer.java | 31 +- .../proxy/AbstractResultSetProxyHandler.java | 29 +- .../proxy/AbstractStatementProxyHandler.java | 19 +- .../proxy/ConnectionProxyHandler.java | 34 +- .../proxy/PreparedStatementProxyHandler.java | 13 +- .../engine/jdbc/spi/SQLExceptionHelper.java | 66 +- .../engine/jdbc/spi/SQLStatementLogger.java | 19 +- .../engine/loading/CollectionLoadContext.java | 153 +-- .../engine/loading/EntityLoadContext.java | 17 +- .../engine/loading/LoadContexts.java | 76 +- .../engine/profile/FetchProfile.java | 28 +- .../hibernate/engine/query/HQLQueryPlan.java | 50 +- .../engine/query/NativeSQLQueryPlan.java | 21 +- .../engine/query/QueryPlanCache.java | 52 +- .../engine/transaction/Isolater.java | 50 +- .../transaction/SynchronizationRegistry.java | 23 +- .../def/AbstractFlushingEventListener.java | 96 +- .../def/AbstractLockUpgradeEventListener.java | 23 +- .../def/AbstractReassociateEventListener.java | 22 +- .../event/def/AbstractSaveEventListener.java | 107 +- .../def/DefaultAutoFlushEventListener.java | 39 +- .../event/def/DefaultDeleteEventListener.java | 66 +- .../def/DefaultDirtyCheckEventListener.java | 25 +- .../event/def/DefaultEvictEventListener.java | 19 +- .../def/DefaultFlushEntityEventListener.java | 55 +- ...aultInitializeCollectionEventListener.java | 54 +- .../event/def/DefaultLoadEventListener.java | 156 +-- .../event/def/DefaultMergeEventListener.java | 168 +-- .../def/DefaultPersistEventListener.java | 32 +- .../def/DefaultRefreshEventListener.java | 33 +- .../def/DefaultReplicateEventListener.java | 52 +- .../def/DefaultSaveOrUpdateEventListener.java | 82 +- .../org/hibernate/event/def/EvictVisitor.java | 24 +- .../hibernate/event/def/ReattachVisitor.java | 22 +- .../org/hibernate/event/def/WrapVisitor.java | 19 +- .../SQLExceptionConverterFactory.java | 34 +- .../java/org/hibernate/hql/QuerySplitter.java | 17 +- .../hql/ast/ASTQueryTranslatorFactory.java | 17 +- .../org/hibernate/hql/ast/ErrorCounter.java | 19 +- .../java/org/hibernate/hql/ast/HqlParser.java | 32 +- .../org/hibernate/hql/ast/HqlSqlWalker.java | 74 +- .../hql/ast/QueryTranslatorImpl.java | 34 +- .../org/hibernate/hql/ast/SqlGenerator.java | 17 +- .../ast/exec/AbstractStatementExecutor.java | 3 +- .../org/hibernate/hql/ast/exec/Logger.java | 48 - .../ast/exec/MultiTableDeleteExecutor.java | 3 +- .../ast/exec/MultiTableUpdateExecutor.java | 3 +- .../tree/AbstractRestrictableStatement.java | 1 + .../hibernate/hql/ast/tree/AggregateNode.java | 17 +- .../hql/ast/tree/DeleteStatement.java | 1 + .../org/hibernate/hql/ast/tree/DotNode.java | 22 +- .../hibernate/hql/ast/tree/FromClause.java | 7 +- .../hibernate/hql/ast/tree/FromElement.java | 11 +- .../hql/ast/tree/FromElementFactory.java | 14 +- .../hql/ast/tree/FromElementType.java | 5 +- .../hql/ast/tree/FromReferenceNode.java | 3 +- .../org/hibernate/hql/ast/tree/IndexNode.java | 7 +- .../org/hibernate/hql/ast/tree/Logger.java | 169 --- .../hibernate/hql/ast/tree/MethodNode.java | 5 +- .../org/hibernate/hql/ast/tree/QueryNode.java | 3 +- .../hql/ast/tree/UpdateStatement.java | 1 + .../hibernate/hql/ast/util/JoinProcessor.java | 61 +- .../hql/ast/util/LiteralProcessor.java | 48 +- .../hibernate/hql/ast/util/PathHelper.java | 20 +- .../hql/ast/util/SyntheticAndFactory.java | 25 +- .../hql/classic/QueryTranslatorImpl.java | 24 +- .../java/org/hibernate/id/GUIDGenerator.java | 22 +- .../id/IdentifierGeneratorHelper.java | 19 +- .../org/hibernate/id/IncrementGenerator.java | 25 +- .../id/MultipleHiLoPerTableGenerator.java | 17 +- .../org/hibernate/id/SequenceGenerator.java | 20 +- .../id/SequenceIdentityGenerator.java | 17 +- .../java/org/hibernate/id/TableGenerator.java | 20 +- .../java/org/hibernate/id/UUIDGenerator.java | 21 +- .../org/hibernate/id/UUIDHexGenerator.java | 18 +- .../id/enhanced/OptimizerFactory.java | 55 +- .../id/enhanced/SequenceStructure.java | 19 +- .../id/enhanced/SequenceStyleGenerator.java | 24 +- .../hibernate/id/enhanced/TableGenerator.java | 25 +- .../hibernate/id/enhanced/TableStructure.java | 20 +- .../DefaultIdentifierGeneratorFactory.java | 30 +- .../impl/AbstractScrollableResults.java | 19 +- .../java/org/hibernate/impl/IteratorImpl.java | 58 +- .../hibernate/impl/NonFlushedChangesImpl.java | 19 +- .../hibernate/impl/SessionFactoryImpl.java | 188 +-- .../impl/SessionFactoryObjectFactory.java | 121 +- .../java/org/hibernate/impl/SessionImpl.java | 176 +-- .../hibernate/impl/StatelessSessionImpl.java | 19 +- .../internal/util/jdbc/TypeInfoExtracter.java | 25 +- .../internal/util/jndi/JndiHelper.java | 76 +- .../org/hibernate/jdbc/AbstractBatcher.java | 714 ------------ .../org/hibernate/jdbc/BatchingBatcher.java | 87 -- .../java/org/hibernate/jdbc/Expectations.java | 19 +- .../jdbc/util/SQLStatementLogger.java | 10 +- .../org/hibernate/jmx/HibernateService.java | 36 +- .../org/hibernate/jmx/SessionFactoryStub.java | 25 +- .../org/hibernate/jmx/StatisticsService.java | 20 +- .../java/org/hibernate/loader/Loader.java | 214 +--- .../collection/BasicCollectionLoader.java | 20 +- .../loader/collection/OneToManyLoader.java | 20 +- .../loader/custom/sql/SQLCustomQuery.java | 19 +- .../custom/sql/SQLQueryReturnProcessor.java | 27 +- .../loader/entity/CascadeEntityLoader.java | 2 +- .../entity/CollectionElementLoader.java | 20 +- .../hibernate/loader/entity/EntityLoader.java | 5 +- .../relational/AbstractSimpleValue.java | 12 +- .../metamodel/relational/ForeignKey.java | 27 +- .../AbstractCollectionPersister.java | 120 +- .../NamedQueryCollectionInitializer.java | 20 +- .../entity/AbstractEntityPersister.java | 220 +--- .../entity/AbstractPropertyMapping.java | 22 +- .../persister/entity/NamedQueryLoader.java | 26 +- .../java/org/hibernate/pretty/Printer.java | 25 +- .../property/BasicPropertyAccessor.java | 28 +- .../hibernate/secure/JACCConfiguration.java | 20 +- .../service/internal/ServicesInitializer.java | 19 +- .../internal/ServicesRegistryImpl.java | 18 +- .../internal/ConnectionProviderInitiator.java | 31 +- .../DriverManagerConnectionProviderImpl.java | 92 +- .../internal/AbstractDialectResolver.java | 18 +- .../dialect/internal/DialectResolverSet.java | 17 +- .../internal/StandardDialectResolver.java | 28 - .../service/jmx/internal/JmxServiceImpl.java | 42 +- .../jndi/internal/JndiServiceImpl.java | 17 +- .../ordering/antlr/OrderByFragmentParser.java | 10 +- .../antlr/OrderByFragmentRenderer.java | 10 +- .../antlr/OrderByFragmentTranslator.java | 16 +- .../stat/ConcurrentStatisticsImpl.java | 1 + .../main/java/org/hibernate/stat/Logger.java | 252 ----- .../org/hibernate/stat/StatisticsImpl.java | 1 + .../tool/hbm2ddl/DatabaseMetadata.java | 17 +- .../hibernate/tool/hbm2ddl/SchemaExport.java | 71 +- .../hibernate/tool/hbm2ddl/SchemaUpdate.java | 50 +- .../tool/hbm2ddl/SchemaValidator.java | 34 +- .../hibernate/tool/hbm2ddl/TableMetadata.java | 30 +- .../hibernate/transaction/CMTTransaction.java | 7 +- .../transaction/CacheSynchronization.java | 13 +- .../transaction/JDBCTransaction.java | 17 +- .../hibernate/transaction/JTATransaction.java | 15 +- .../transaction/JTATransactionFactory.java | 7 +- .../org/hibernate/transaction/Logger.java | 182 --- .../TransactionFactoryFactory.java | 1 + .../TransactionManagerLookupFactory.java | 1 + .../WebSphereTransactionManagerLookup.java | 1 + .../synchronization/CallbackCoordinator.java | 49 +- .../HibernateSynchronizationImpl.java | 25 +- .../transform/DistinctResultTransformer.java | 20 +- .../org/hibernate/tuple/PojoInstantiator.java | 17 +- .../tuple/entity/AbstractEntityTuplizer.java | 19 +- .../tuple/entity/Dom4jEntityTuplizer.java | 14 +- .../entity/DynamicMapEntityTuplizer.java | 14 +- .../tuple/entity/EntityMetamodel.java | 22 +- .../tuple/entity/PojoEntityTuplizer.java | 26 +- .../org/hibernate/type/BasicTypeRegistry.java | 31 +- .../org/hibernate/type/DbTimestampType.java | 42 +- .../java/org/hibernate/type/EnumType.java | 13 +- .../main/java/org/hibernate/type/Logger.java | 72 -- .../java/org/hibernate/type/NullableType.java | 9 +- .../java/org/hibernate/type/TypeFactory.java | 3 +- .../type/descriptor/JdbcTypeNameMapper.java | 19 +- .../type/descriptor/java/DataHelper.java | 26 +- .../type/descriptor/sql/BasicBinder.java | 10 +- .../type/descriptor/sql/BasicExtractor.java | 26 +- .../java/org/hibernate/util/ConfigHelper.java | 14 +- .../org/hibernate/util/DTDEntityResolver.java | 64 +- .../hibernate/util/JDBCExceptionReporter.java | 28 +- .../hibernate/util/SerializationHelper.java | 53 +- .../java/org/hibernate/util/XMLHelper.java | 26 +- .../org/hibernate/util/xml/ErrorLogger.java | 23 +- .../org/hibernate/util/xml/MappingReader.java | 25 +- .../src/test/java/org/hibernate/Logger.java | 17 - .../annotations/backquotes/BackquoteTest.java | 4 +- .../fetchprofile/FetchProfileTest.java | 10 +- .../fkcircularity/FkCircularityTest.java | 3 +- .../test/annotations/id/EnumIdTest.java | 1 + .../id/JoinColumnOverrideTest.java | 1 + .../annotations/id/sequences/EnumIdTest.java | 1 + .../id/sequences/JoinColumnOverrideTest.java | 1 + .../annotations/immutable/ImmutableTest.java | 1 + .../namingstrategy/NamingStrategyTest.java | 3 +- .../NaturalIdOnSingleManyToOneTest.java | 1 + .../primarykey/NullablePrimaryKeyTest.java | 5 +- .../annotations/reflection/LogListener.java | 4 +- .../reflection/OtherLogListener.java | 4 +- .../cache/SQLFunctionsInterSystemsTest.java | 7 +- .../test/filter/DynamicFilterTest.java | 1 + .../test/hql/ASTParserLoadingTest.java | 1 + .../test/hql/BulkManipulationTest.java | 1 + .../jdbc/proxies/AggressiveReleaseTest.java | 22 +- .../test/jpa/cascade/CascadeTest.java | 1 + .../org/hibernate/test/legacy/FooBarTest.java | 1 + .../test/legacy/SQLFunctionsTest.java | 1 + .../StatelessSessionFetchingTest.java | 1 + .../org/hibernate/testing/junit/SkipLog.java | 36 - .../hibernate/testing/junit/UnitTestCase.java | 7 +- .../DatabaseSpecificFunctionalTestCase.java | 8 +- .../junit/functional/FunctionalTestCase.java | 1 + .../FunctionalTestClassTestSuite.java | 3 +- .../annotations/HibernateTestCase.java | 9 +- .../testing/tm/SimpleJtaTransactionImpl.java | 4 +- hibernate-ehcache/hibernate-ehcache.gradle | 2 +- .../java/org/hibernate/cache/EhCache.java | 36 +- .../org/hibernate/cache/EhCacheProvider.java | 28 +- .../ejb/AbstractEntityManagerImpl.java | 47 +- .../org/hibernate/ejb/AbstractQueryImpl.java | 33 +- .../org/hibernate/ejb/Ejb3Configuration.java | 95 +- .../org/hibernate/ejb/EntityManagerImpl.java | 49 +- .../java/org/hibernate/ejb/QueryImpl.java | 72 +- .../main/java/org/hibernate/ejb/Version.java | 9 +- .../InjectedDataSourceConnectionProvider.java | 28 +- .../ejb/criteria/CriteriaQueryCompiler.java | 30 +- .../hibernate/ejb/event/CallbackResolver.java | 28 +- .../ejb/metamodel/AttributeFactory.java | 169 ++- .../ejb/metamodel/MetadataContext.java | 39 +- .../ejb/packaging/AbstractJarVisitor.java | 16 +- .../ejb/packaging/ExplodedJarVisitor.java | 22 +- .../ejb/packaging/FileZippedJarVisitor.java | 22 +- .../InputStreamZippedJarVisitor.java | 16 +- .../ejb/packaging/JarVisitorFactory.java | 10 +- .../ejb/packaging/PersistenceXmlLoader.java | 17 +- .../org/hibernate/ejb/util/NamingHelper.java | 30 +- .../hibernate/engine/EJB3CascadingAction.java | 31 +- .../test/java/org/hibernate/ejb/test/Cat.java | 26 +- .../java/org/hibernate/ejb/test/TestCase.java | 27 +- .../hibernate/ejb/test/emops/RemoveTest.java | 20 +- .../ejb/test/exception/ExceptionTest.java | 11 +- .../org/hibernate/ejb/test/lock/LockTest.java | 116 +- .../configuration/ClassesAuditingData.java | 25 +- .../metadata/AuditMetadataGenerator.java | 26 +- .../metadata/CollectionMetadataGenerator.java | 63 +- .../envers/reader/FirstLevelCache.java | 63 +- .../strategy/ValidTimeAuditStrategy.java | 13 +- .../components/DefaultValueComponents.java | 70 +- .../AbstractGeneralDataRegionTestCase.java | 248 ++-- .../AbstractNonFunctionalTestCase.java | 26 +- ...ollectionRegionAccessStrategyTestCase.java | 924 ++++++++------- ...actEntityRegionAccessStrategyTestCase.java | 1003 ++++++++--------- .../AbstractTransactionalAccessTestCase.java | 136 +-- .../classloader/CacheAccessListener.java | 128 ++- .../classloader/IsolatedClassLoaderTest.java | 435 ++++--- .../SelectedClassnameClassLoader.java | 329 +++--- .../cluster/SessionRefreshTestCase.java | 164 ++- .../query/QueryRegionImplTestCase.java | 413 +++---- .../infinispan/util/CacheTestSupport.java | 56 +- .../internal/ProxoolConnectionProvider.java | 56 +- 330 files changed, 3874 insertions(+), 12025 deletions(-) delete mode 100644 hibernate-core/src/main/java/org/hibernate/cache/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/dialect/lock/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/hql/ast/exec/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/hql/ast/tree/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/jdbc/AbstractBatcher.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/jdbc/BatchingBatcher.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/stat/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/transaction/Logger.java delete mode 100644 hibernate-core/src/main/java/org/hibernate/type/Logger.java delete mode 100644 hibernate-core/src/test/java/org/hibernate/Logger.java delete mode 100644 hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java index ba4f48ca52..36ce88526d 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java @@ -27,19 +27,13 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.Properties; - import javax.sql.DataSource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.mchange.v2.c3p0.DataSources; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.util.ReflectHelper; +import com.mchange.v2.c3p0.DataSources; /** * A connection provider that uses a C3P0 connection pool. Hibernate will use this by @@ -50,7 +44,7 @@ import org.hibernate.util.ReflectHelper; */ public class C3P0ConnectionProvider implements ConnectionProvider { - private static final Logger log = LoggerFactory.getLogger( C3P0ConnectionProvider.class ); + private static final C3P0Logger LOG = org.jboss.logging.Logger.getMessageLogger(C3P0Logger.class, C3P0Logger.class.getPackage().getName()); //swaldman 2006-08-28: define c3p0-style configuration parameters for properties with // hibernate-specific overrides to detect and warn about conflicting @@ -61,7 +55,7 @@ public class C3P0ConnectionProvider implements ConnectionProvider { private final static String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements"; private final static String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement"; private final static String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod"; - private final static String C3P0_STYLE_TEST_CONNECTION_ON_CHECKOUT = "c3p0.testConnectionOnCheckout"; + // private final static String C3P0_STYLE_TEST_CONNECTION_ON_CHECKOUT = "c3p0.testConnectionOnCheckout"; //swaldman 2006-08-28: define c3p0-style configuration parameters for initialPoolSize, which // hibernate sensibly lets default to minPoolSize, but we'll let users @@ -93,23 +87,22 @@ public class C3P0ConnectionProvider implements ConnectionProvider { conn.close(); } - /** - * {@inheritDoc} - */ + /** + * @param props + * @throws HibernateException + */ public void configure(Properties props) throws HibernateException { String jdbcDriverClass = props.getProperty( Environment.DRIVER ); String jdbcUrl = props.getProperty( Environment.URL ); Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props ); - log.info( "C3P0 using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl ); - log.info( "Connection properties: " + ConfigurationHelper.maskOut( connectionProps, "password" ) ); + LOG.c3p0UsingDriver(jdbcDriverClass, jdbcUrl); + LOG.connectionProperties(ConfigurationHelper.maskOut(connectionProps, "password")); autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props ); - log.info( "autocommit mode: " + autocommit ); + LOG.autoCommitMode(autocommit); - if ( jdbcDriverClass == null ) { - log.warn( "No JDBC Driver class was specified by property " + Environment.DRIVER ); - } + if (jdbcDriverClass == null) LOG.jdbcDriverNotSpecified(Environment.DRIVER); else { try { Class.forName( jdbcDriverClass ); @@ -119,8 +112,8 @@ public class C3P0ConnectionProvider implements ConnectionProvider { ReflectHelper.classForName( jdbcDriverClass ); } catch ( ClassNotFoundException e ) { - String msg = "JDBC Driver class not found: " + jdbcDriverClass; - log.error( msg, e ); + String msg = LOG.jdbcDriverNotFound(jdbcDriverClass); + LOG.error(msg, e); throw new HibernateException( msg, e ); } } @@ -182,30 +175,28 @@ public class C3P0ConnectionProvider implements ConnectionProvider { ds = DataSources.pooledDataSource( unpooled, allProps ); } catch ( Exception e ) { - log.error( "could not instantiate C3P0 connection pool", e ); + LOG.error(LOG.unableToInstantiateC3p0ConnectionPool(), e); throw new HibernateException( "Could not instantiate C3P0 connection pool", e ); } String i = props.getProperty( Environment.ISOLATION ); - if ( i == null ) { - isolation = null; - } + if (i == null) isolation = null; else { isolation = new Integer( i ); - log.info( "JDBC isolation level: " + Environment.isolationLevelToString( isolation.intValue() ) ); + LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation.intValue())); } } - /** - * {@inheritDoc} + /** + * */ public void close() { try { DataSources.destroy( ds ); } catch ( SQLException sqle ) { - log.warn( "could not destroy C3P0 connection pool", sqle ); + LOG.warn(LOG.unableToDestroyC3p0ConnectionPool(), sqle); } } @@ -230,12 +221,6 @@ public class C3P0ConnectionProvider implements ConnectionProvider { } private void warnPropertyConflict(String hibernateStyle, String c3p0Style) { - log.warn( - "Both hibernate-style property '" + hibernateStyle + - "' and c3p0-style property '" + c3p0Style + - "' have been set in hibernate.properties. " + - "Hibernate-style property '" + hibernateStyle + "' will be used " + - "and c3p0-style property '" + c3p0Style + "' will be ignored!" - ); + LOG.bothHibernateAndC3p0StylesSet(hibernateStyle, c3p0Style, hibernateStyle, c3p0Style); } } diff --git a/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java b/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java index 179b893803..30a1c7044b 100644 --- a/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java +++ b/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java @@ -24,11 +24,6 @@ */ package org.hibernate; -import static org.jboss.logging.Logger.Level.ERROR; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - /** * Indicates failure of an assertion: a possible bug in Hibernate. * @@ -50,16 +45,4 @@ public class AssertionFailure extends RuntimeException { super(s, t); LOG.failed(t); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger { - - @LogMessage( level = ERROR ) - @Message( value = "an assertion failure occured" + " (this may indicate a bug in Hibernate, but is more likely due" - + " to unsafe use of the session): %s" ) - void failed( Throwable throwable ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/BytecodeProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/BytecodeProviderImpl.java index 661b80aa3c..0051d7a9d5 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/BytecodeProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/BytecodeProviderImpl.java @@ -28,8 +28,8 @@ import java.lang.reflect.Modifier; import net.sf.cglib.beans.BulkBean; import net.sf.cglib.beans.BulkBeanException; import net.sf.cglib.reflect.FastClass; +import org.hibernate.Logger; import org.hibernate.bytecode.BytecodeProvider; -import org.hibernate.bytecode.Logger; import org.hibernate.bytecode.ProxyFactoryFactory; import org.hibernate.bytecode.ReflectionOptimizer; import org.hibernate.bytecode.util.FieldFilter; @@ -82,25 +82,17 @@ public class BytecodeProviderImpl implements BytecodeProvider { if (LOG.isDebugEnabled()) { int index = 0; if (t instanceof BulkBeanException) index = ((BulkBeanException)t).getIndex(); - if (index >= 0) LOG.reflectionOptimizerDisabledForBulkException(clazz.getName(), - StringHelper.unqualify(t.getClass().getName()), - t.getMessage(), - setterNames[index]); - else LOG.reflectionOptimizerDisabled(clazz.getName(), - StringHelper.unqualify(t.getClass().getName()), - t.getMessage()); + if (index >= 0) LOG.debug("Reflection optimizer disabled for: " + clazz.getName() + " [" + + StringHelper.unqualify(t.getClass().getName()) + ": " + t.getMessage() + " (property " + + setterNames[index] + ")"); + else LOG.debug("Reflection optimizer disabled for: " + clazz.getName() + " [" + + StringHelper.unqualify(t.getClass().getName()) + ": " + t.getMessage()); } } - if ( fastClass != null && bulkBean != null ) { - return new ReflectionOptimizerImpl( - new InstantiationOptimizerAdapter( fastClass ), - new AccessOptimizerAdapter( bulkBean, clazz ) - ); - } - else { - return null; - } + if (fastClass != null && bulkBean != null) return new ReflectionOptimizerImpl(new InstantiationOptimizerAdapter(fastClass), + new AccessOptimizerAdapter(bulkBean, clazz)); + return null; } public org.hibernate.bytecode.ClassTransformer getTransformer(org.hibernate.bytecode.util.ClassFilter classFilter, FieldFilter fieldFilter) { diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/CglibClassTransformer.java b/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/CglibClassTransformer.java index 5f82735c10..c48321e1b1 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/CglibClassTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/cglib/CglibClassTransformer.java @@ -37,8 +37,8 @@ import net.sf.cglib.transform.impl.InterceptFieldEnabled; import net.sf.cglib.transform.impl.InterceptFieldFilter; import net.sf.cglib.transform.impl.InterceptFieldTransformer; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.bytecode.AbstractClassTransformerImpl; -import org.hibernate.bytecode.Logger; import org.hibernate.bytecode.util.ClassFilter; import org.hibernate.bytecode.util.FieldFilter; import org.objectweb.asm.ClassReader; @@ -82,7 +82,7 @@ public class CglibClassTransformer extends AbstractClassTransformerImpl { ClassWriter w = new DebuggingClassWriter( ClassWriter.COMPUTE_MAXS ); ClassTransformer t = getClassTransformer( names ); if ( t != null ) { - LOG.enhancingClass(className); + LOG.debug("Enhancing " + className); ByteArrayOutputStream out; byte[] result; try { diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/BytecodeProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/BytecodeProviderImpl.java index 47dc683df3..a159463c3a 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/BytecodeProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/BytecodeProviderImpl.java @@ -25,9 +25,9 @@ package org.hibernate.bytecode.javassist; import java.lang.reflect.Modifier; +import org.hibernate.Logger; import org.hibernate.bytecode.BytecodeProvider; import org.hibernate.bytecode.ClassTransformer; -import org.hibernate.bytecode.Logger; import org.hibernate.bytecode.ProxyFactoryFactory; import org.hibernate.bytecode.ReflectionOptimizer; import org.hibernate.bytecode.util.ClassFilter; @@ -74,13 +74,11 @@ public class BytecodeProviderImpl implements BytecodeProvider { if (LOG.isDebugEnabled()) { int index = 0; if (t instanceof BulkAccessorException) index = ((BulkAccessorException)t).getIndex(); - if (index >= 0) LOG.reflectionOptimizerDisabledForBulkException(clazz.getName(), - StringHelper.unqualify(t.getClass().getName()), - t.getMessage(), - setterNames[index]); - else LOG.reflectionOptimizerDisabled(clazz.getName(), - StringHelper.unqualify(t.getClass().getName()), - t.getMessage()); + if (index >= 0) LOG.debug("Reflection optimizer disabled for: " + clazz.getName() + " [" + + StringHelper.unqualify(t.getClass().getName()) + ": " + t.getMessage() + " (property " + + setterNames[index] + ")"); + else LOG.debug("Reflection optimizer disabled for: " + clazz.getName() + " [" + + StringHelper.unqualify(t.getClass().getName()) + ": " + t.getMessage()); } } @@ -90,9 +88,7 @@ public class BytecodeProviderImpl implements BytecodeProvider { new AccessOptimizerAdapter( bulkAccessor, clazz ) ); } - else { - return null; - } + return null; } public ClassTransformer getTransformer(ClassFilter classFilter, FieldFilter fieldFilter) { diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/JavassistClassTransformer.java b/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/JavassistClassTransformer.java index d75ec5bbc5..936b114c9f 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/JavassistClassTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/javassist/JavassistClassTransformer.java @@ -32,8 +32,8 @@ import java.io.IOException; import java.security.ProtectionDomain; import javassist.bytecode.ClassFile; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.bytecode.AbstractClassTransformerImpl; -import org.hibernate.bytecode.Logger; import org.hibernate.bytecode.util.ClassFilter; /** @@ -69,7 +69,7 @@ public class JavassistClassTransformer extends AbstractClassTransformerImpl { } FieldTransformer transformer = getFieldTransformer( classfile ); if ( transformer != null ) { - LOG.enhancingClass("Enhancing " + className); + LOG.debug("Enhancing " + className); DataOutputStream out = null; try { transformer.transform( classfile ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java b/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java index 3c7757678f..4163d6b795 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java @@ -28,6 +28,7 @@ import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.jndi.JndiHelper; import org.hibernate.util.StringHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/Logger.java b/hibernate-core/src/main/java/org/hibernate/cache/Logger.java deleted file mode 100644 index 737a77f0b7..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/cache/Logger.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.cache; - -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; -import java.io.Serializable; -import java.util.Set; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Cached: %s" ) - void cached( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Caching: %s" ) - void caching( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Caching after insert: %s" ) - void cachingAfterInsert( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Caching query results in region: %s; timestamp=%s" ) - void cachingQueryResults( String region, - Long ts ); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking cached query results in region: %s" ) - void checkingQueryResults( String region ); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking query spaces are up-to-date: %s" ) - void checkingQuerySpacesUpToDate( Set spaces ); - - @LogMessage( level = DEBUG ) - @Message( value = "Clearing" ) - void clearing(); - - @LogMessage( level = DEBUG ) - @Message( value = "Item already cached: %s" ) - void exists( Object key ); - - @LogMessage( level = WARN ) - @Message( value = "An item was expired by the cache while it was locked (increase your cache timeout): %s" ) - void expired( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Cache hit: %s" ) - void hit( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Inserted: %s" ) - void inserted( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Inserting: %s" ) - void inserting( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Invalidating: %s" ) - void invalidating( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Invalidating space [%s], timestamp: %s" ) - void invalidatingSpace( Serializable space, - Long ts ); - - @LogMessage( level = ERROR ) - @Message( value = "Application attempted to edit read only item: %s" ) - void invalidEditOfReadOnlyItem( Object key ); - - @LogMessage( level = TRACE ) - @Message( value = "key.hashCode=%s" ) - void key( int hashCode ); - - @LogMessage( level = DEBUG ) - @Message( value = "Cached item was locked: %s" ) - void locked( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Cache lookup: %s" ) - void lookup( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Cache miss: %s" ) - void miss( Object key ); - - @LogMessage( level = TRACE ) - @Message( value = " tuple is null; returnTypes is %s" ) - void nullTuple( String returnTypesState ); - - @LogMessage( level = DEBUG ) - @Message( value = "Pre-invalidating space [%s]" ) - void preInvalidatingSpace( Serializable space ); - - @LogMessage( level = DEBUG ) - @Message( value = "Query results were not found in cache" ) - void queryResultsNotFound(); - - @LogMessage( level = DEBUG ) - @Message( value = "Cached query results were not up-to-date" ) - void queryResultsNotUpToDate(); - - @LogMessage( level = TRACE ) - @Message( value = "querySpaces=%s" ) - void querySpaces( Set spaces ); - - @LogMessage( level = DEBUG ) - @Message( value = "Releasing: %s" ) - void releasing( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Removing: %s" ) - void removing( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Returning cached query results" ) - void returningQueryResults(); - - @LogMessage( level = TRACE ) - @Message( value = "unexpected returnTypes is %s! result%s" ) - void returnTypeInfo( String returnTypeInfo ); - - @LogMessage( level = DEBUG ) - @Message( value = "[%s] last update timestamp: %d, result set timestamp: %d" ) - void spaceLastUpdated( Serializable space, - long lastUpdate, - long timestamp ); - - @LogMessage( level = INFO ) - @Message( value = "Starting query cache at region: %s" ) - void startingQueryCache( String region ); - - @LogMessage( level = INFO ) - @Message( value = "Starting update timestamps cache at region: %s" ) - void startingUpdateTimestampsCache( String region ); - - @LogMessage( level = TRACE ) - @Message( value = " tuple is Object[%d]; returnTypes is Type[%d]" ) - void tupleAndReturnTypes( int tupleCount, - int returnTypeCount ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to destroy cache: %s" ) - void unableToDestroyCache( String message ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to destroy query cache: %s: %s" ) - void unableToDestroyQueryCache( String region, - String message ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to destroy update timestamps cache: %s: %s" ) - void unableToDestroyUpdateTimestampsCache( String region, - String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to reassemble cached result set" ) - void unableToReassembleResultSet(); - - @LogMessage( level = INFO ) - @Message( value = "Unable to release initial context: %s" ) - void unableToReleaseContext( String message ); - - @LogMessage( level = INFO ) - @Message( value = "Unable to retreive cache from JNDI [%s]: %s" ) - void unableToRetrieveCache( String namespace, - String message ); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected result tuple! tuple is null; returnTypes is %s" ) - void unexpectedNonNullTupleResult( String returnTypesState ); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected result tuple! tuple is null; should be Object[%d]!" ) - void unexpectedNullTupleResult( int returnTypeCount ); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected returnTypes is %s! result%s" ) - void unexpectedReturnTypes( String returnTypesState, - String resultState ); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected tuple length! transformer= expected=%d got=%d" ) - void unexpectedTupleCount( int returntypesCount, - int tupleCount ); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected tuple value type! transformer= expected=%s got=%s" ) - void unexpectedTupleValueType( String returnTypeClassName, - String tupleClassName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Updated: %s" ) - void updated( Object key ); - - @LogMessage( level = DEBUG ) - @Message( value = "Updating: %s" ) - void updating( Object key ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java b/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java index ea0c72e7c1..850891b444 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java @@ -25,6 +25,7 @@ package org.hibernate.cache; import java.util.Comparator; +import org.hibernate.Logger; import org.hibernate.cache.access.SoftLock; /** @@ -58,15 +59,11 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Get the most recent version, if available. */ public Object get(Object key, long txTimestamp) throws CacheException { - LOG.lookup(key); + LOG.debug("Cache lookup: " + key); Object result = cache.get( key ); - if ( result != null ) { - LOG.hit(key); - } - else { - LOG.miss(key); - } + if (result != null) LOG.debug("Cache hit: " + key); + else LOG.debug("Cache miss: " + key); return result; } @@ -81,10 +78,10 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { Comparator versionComparator, boolean minimalPut) throws CacheException { if ( minimalPut && cache.get( key ) != null ) { - LOG.exists(key); + LOG.debug("Item already cached: " + key); return false; } - LOG.caching(key); + LOG.debug("Caching: " + key); cache.put( key, value ); return true; @@ -101,12 +98,12 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { } public void remove(Object key) throws CacheException { - LOG.removing(key); + LOG.debug("Removing: " + key); cache.remove( key ); } public void clear() throws CacheException { - LOG.clearing(); + LOG.debug("Clearing"); cache.clear(); } @@ -123,7 +120,7 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Invalidate the item */ public void evict(Object key) throws CacheException { - LOG.invalidating(key); + LOG.debug("Invalidating: " + key); cache.remove( key ); } @@ -146,7 +143,7 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Invalidate the item (again, for safety). */ public void release(Object key, SoftLock lock) throws CacheException { - LOG.invalidating(key); + LOG.debug("Invalidating: " + key); cache.remove( key ); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java b/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java index aa38d76727..e105af92be 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java @@ -25,6 +25,7 @@ package org.hibernate.cache; import java.util.Comparator; +import org.hibernate.Logger; import org.hibernate.cache.access.SoftLock; /** @@ -53,7 +54,7 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { public synchronized Object get(Object key, long timestamp) throws CacheException { Object result = cache.get(key); - if (result != null) LOG.hit(key); + if (result != null) LOG.debug("Cache hit: " + key); return result; } @@ -74,10 +75,10 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { boolean minimalPut) throws CacheException { if ( minimalPut && cache.get(key)!=null ) { - LOG.exists(key); + LOG.debug("Item already cached: " + key); return false; } - LOG.caching(key); + LOG.debug("Caching: " + key); cache.put(key, value); return true; } @@ -119,7 +120,7 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { * Do nothing. */ public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - LOG.cachingAfterInsert(key); + LOG.debug("Caching after insert: " + key); cache.update(key, value); return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java b/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java index 6d1ae16149..b7ace26645 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java @@ -26,6 +26,7 @@ package org.hibernate.cache; import java.io.Serializable; import java.util.Comparator; +import org.hibernate.Logger; import org.hibernate.cache.access.SoftLock; /** @@ -92,15 +93,15 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * the data is versioned or timestamped. */ public synchronized Object get(Object key, long txTimestamp) throws CacheException { - LOG.lookup(key); + LOG.debug("Cache lookup: " + key); Lockable lockable = (Lockable)cache.get(key); boolean gettable = lockable != null && lockable.isGettable(txTimestamp); if (gettable) { - LOG.hit(key); + LOG.debug("Cache hit: " + key); return ((Item)lockable).getValue(); } - if (lockable == null) LOG.miss(key); - else LOG.locked(key); + if (lockable == null) LOG.debug("Cache miss: " + key); + else LOG.debug("Cached item was locked: " + key); return null; } @@ -112,7 +113,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * item. */ public synchronized SoftLock lock(Object key, Object version) throws CacheException { - LOG.invalidating(key); + LOG.debug("Invalidating: " + key); try { cache.lock(key); @@ -146,7 +147,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { Comparator versionComparator, boolean minimalPut) throws CacheException { - LOG.caching(key); + LOG.debug("Caching: " + key); try { cache.lock(key); @@ -158,14 +159,12 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { if (puttable) { cache.put( key, new Item( value, version, cache.nextTimestamp() ) ); - LOG.cached(key); + LOG.debug("Cached: " + key); return true; } - else { - if (lockable.isLock()) LOG.locked(key); - else LOG.exists(key); - return false; - } + if (lockable.isLock()) LOG.debug("Cached item was locked: " + key); + else LOG.debug("Item already cached: " + key); + return false; } finally { cache.unlock(key); @@ -187,7 +186,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * simultaneous lock). */ public synchronized void release(Object key, SoftLock clientLock) throws CacheException { - LOG.releasing(key); + LOG.debug("Releasing: " + key); try { cache.lock(key); @@ -238,7 +237,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { public synchronized boolean afterUpdate(Object key, Object value, Object version, SoftLock clientLock) throws CacheException { - LOG.updating(key); + LOG.debug("Updating: " + key); try { cache.lock(key); @@ -252,18 +251,13 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { decrementLock(key, lock); return false; } - else { - //recache the updated state - cache.update( key, new Item( value, version, cache.nextTimestamp() ) ); - LOG.updated(key); - return true; - } + // recache the updated state + cache.update(key, new Item(value, version, cache.nextTimestamp())); + LOG.debug("Updated: " + key); + return true; } - else { - handleLockExpiry(key); - return false; - } - + handleLockExpiry(key); + return false; } finally { cache.unlock(key); @@ -277,19 +271,17 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { public synchronized boolean afterInsert(Object key, Object value, Object version) throws CacheException { - LOG.inserting(key); + LOG.debug("Inserting: " + key); try { cache.lock(key); Lockable lockable = (Lockable) cache.get(key); if (lockable==null) { cache.update( key, new Item( value, version, cache.nextTimestamp() ) ); - LOG.inserted(key); + LOG.debug("Inserted: " + key); return true; } - else { - return false; - } + return false; } finally { cache.unlock(key); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java b/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java index e8ea924b95..a42fcbe5ae 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java @@ -30,6 +30,7 @@ import java.util.Properties; import java.util.Set; import javax.persistence.EntityNotFoundException; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.UnresolvableObjectException; import org.hibernate.cfg.Settings; import org.hibernate.engine.SessionImplementor; @@ -81,32 +82,22 @@ public class StandardQueryCache implements QueryCache { List result, boolean isNaturalKeyLookup, SessionImplementor session) throws HibernateException { - if ( isNaturalKeyLookup && result.size() == 0 ) { - return false; - } - else { - Long ts = new Long( session.getFactory().getSettings().getRegionFactory().nextTimestamp()); + if (isNaturalKeyLookup && result.size() == 0) return false; + Long ts = new Long(session.getFactory().getSettings().getRegionFactory().nextTimestamp()); - LOG.cachingQueryResults(cacheRegion.getName(), ts); + LOG.debug("Caching query results in region: " + cacheRegion.getName() + "; timestamp=" + ts); - List cacheable = new ArrayList( result.size() + 1 ); - logCachedResultDetails(key, null, returnTypes, cacheable); - cacheable.add( ts ); - for ( Object aResult : result ) { - if ( returnTypes.length == 1 ) { - cacheable.add( returnTypes[0].disassemble( aResult, session, null ) ); - } - else { - cacheable.add( - TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ) - ); - } - logCachedResultRowDetails(returnTypes, aResult); - } + List cacheable = new ArrayList(result.size() + 1); + logCachedResultDetails(key, null, returnTypes, cacheable); + cacheable.add(ts); + for (Object aResult : result) { + if (returnTypes.length == 1) cacheable.add(returnTypes[0].disassemble(aResult, session, null)); + else cacheable.add(TypeHelper.disassemble((Object[])aResult, returnTypes, null, session, null)); + logCachedResultRowDetails(returnTypes, aResult); + } - cacheRegion.put( key, cacheable ); - return true; - } + cacheRegion.put(key, cacheable); + return true; } @SuppressWarnings({ "unchecked" }) @@ -116,23 +107,23 @@ public class StandardQueryCache implements QueryCache { boolean isNaturalKeyLookup, Set spaces, SessionImplementor session) throws HibernateException { - LOG.checkingQueryResults(cacheRegion.getName()); + LOG.debug("Checking cached query results in region: " + cacheRegion.getName()); List cacheable = ( List ) cacheRegion.get( key ); logCachedResultDetails(key, spaces, returnTypes, cacheable); if ( cacheable == null ) { - LOG.queryResultsNotFound(); + LOG.debug("Query results were not found in cache"); return null; } Long timestamp = ( Long ) cacheable.get( 0 ); if ( !isNaturalKeyLookup && !isUpToDate( spaces, timestamp ) ) { - LOG.queryResultsNotUpToDate(); + LOG.debug("Cached query results were not up-to-date"); return null; } - LOG.returningQueryResults(); + LOG.debug("Returning cached query results"); for ( int i = 1; i < cacheable.size(); i++ ) { if ( returnTypes.length == 1 ) { returnTypes[0].beforeAssemble( ( Serializable ) cacheable.get( i ), session ); @@ -162,20 +153,18 @@ public class StandardQueryCache implements QueryCache { // the uoe could occur while resolving // associations, leaving the PC in an // inconsistent state - LOG.unableToReassembleResultSet(); + LOG.debug("Unable to reassemble cached result set"); cacheRegion.evict( key ); return null; } - else { - throw ex; - } + throw ex; } } return result; } protected boolean isUpToDate(Set spaces, Long timestamp) { - LOG.checkingQuerySpacesUpToDate(spaces); + LOG.debug("Checking query spaces are up-to-date: " + spaces); return updateTimestampsCache.isUpToDate( spaces, timestamp ); } @@ -199,12 +188,11 @@ public class StandardQueryCache implements QueryCache { private static void logCachedResultDetails(QueryKey key, Set querySpaces, Type[] returnTypes, List result) { if (!LOG.isTraceEnabled()) return; - LOG.key(key.hashCode()); - LOG.querySpaces(querySpaces); - if ( returnTypes == null || returnTypes.length == 0 ) { - LOG.unexpectedReturnTypes(returnTypes == null ? "null" : "empty", - result == null ? " is null" : ".size()=" + result.size()); - } + LOG.trace("key.hashCode=" + key.hashCode()); + LOG.trace("querySpaces=" + querySpaces); + if (returnTypes == null || returnTypes.length == 0) LOG.trace("Unexpected returnTypes is " + + (returnTypes == null ? "null" : "empty") + "! result" + + (result == null ? " is null" : ".size()=" + result.size())); else { StringBuffer returnTypeInfo = new StringBuffer(); for ( int i=0; i 1) LOG.unexpectedNullTupleResult(returnTypes.length); + LOG.trace(" tuple is null; returnTypes is " + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]"); + if (returnTypes != null && returnTypes.length > 1) LOG.trace("Unexpected result tuple! tuple is null; should be Object[" + + returnTypes.length + "]!"); } else { - if (returnTypes == null || returnTypes.length == 0) LOG.unexpectedNonNullTupleResult(returnTypes == null ? "null" : "empty"); - LOG.tupleAndReturnTypes(tuple.length, returnTypes.length); - if (tuple.length != returnTypes.length) LOG.unexpectedTupleCount(returnTypes.length, tuple.length); + if (returnTypes == null || returnTypes.length == 0) LOG.trace("Unexpected result tuple! tuple is null; returnTypes is " + + (returnTypes == null ? "null" : "empty")); + LOG.trace(" tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]"); + if (tuple.length != returnTypes.length) LOG.trace("Unexpected tuple length! transformer= expected=" + + returnTypes.length + " got=" + tuple.length); else for (int j = 0; j < tuple.length; j++) { - if (tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance(tuple[j])) LOG.unexpectedTupleValueType(returnTypes[j].getReturnedClass().getName(), - tuple[j].getClass().getName()); + if (tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance(tuple[j])) LOG.trace("Unexpected tuple value type! transformer= expected=" + + returnTypes[j].getReturnedClass().getName() + + " got=" + + tuple[j].getClass().getName()); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java b/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java index e0b6b01a5e..53f1d605d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java @@ -25,6 +25,7 @@ package org.hibernate.cache; import java.util.Comparator; +import org.hibernate.Logger; import org.hibernate.cache.access.SoftLock; /** @@ -46,10 +47,10 @@ public class TransactionalCache implements CacheConcurrencyStrategy { } public Object get(Object key, long txTimestamp) throws CacheException { - LOG.lookup(key); + LOG.debug("Cache lookup: " + key); Object result = cache.read( key ); - if (result == null) LOG.miss(key); - else LOG.hit(key); + if (result == null) LOG.debug("Cache miss: " + key); + else LOG.debug("Cache hit: " + key); return result; } @@ -61,10 +62,10 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Comparator versionComparator, boolean minimalPut) throws CacheException { if ( minimalPut && cache.read( key ) != null ) { - LOG.exists(key); + LOG.debug("Item already cached: " + key); return false; } - LOG.caching(key); + LOG.debug("Caching: " + key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeLoad( key, value, version ); } @@ -94,7 +95,7 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Object value, Object currentVersion, Object previousVersion) throws CacheException { - LOG.updating(key); + LOG.debug("Updating: " + key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeUpdate( key, value, currentVersion, previousVersion ); } @@ -108,7 +109,7 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Object key, Object value, Object currentVersion) throws CacheException { - LOG.inserting(key); + LOG.debug("Inserting: " + key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeInsert( key, value, currentVersion ); } @@ -123,12 +124,12 @@ public class TransactionalCache implements CacheConcurrencyStrategy { } public void remove(Object key) throws CacheException { - LOG.removing(key); + LOG.debug("Removing: " + key); cache.remove( key ); } public void clear() throws CacheException { - LOG.clearing(); + LOG.debug("Clearing"); cache.clear(); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java b/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java index 34c5790463..94b1786765 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Settings; /** @@ -43,7 +44,8 @@ import org.hibernate.cfg.Settings; */ public class UpdateTimestampsCache { public static final String REGION_NAME = UpdateTimestampsCache.class.getName(); - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + UpdateTimestampsCache.class.getPackage().getName()); private final TimestampsRegion region; @@ -58,7 +60,7 @@ public class UpdateTimestampsCache { //TODO: to handle concurrent writes correctly, this should return a Lock to the client Long ts = new Long( region.nextTimestamp() + region.getTimeout() ); for ( int i=0; i= timestamp.longValue() ) { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/CollectionRegionAdapter.java b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/CollectionRegionAdapter.java index 8ce4ad7e9d..72562b364f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/CollectionRegionAdapter.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/CollectionRegionAdapter.java @@ -24,6 +24,7 @@ */ package org.hibernate.cache.impl.bridge; +import org.hibernate.Logger; import org.hibernate.cache.Cache; import org.hibernate.cache.CacheConcurrencyStrategy; import org.hibernate.cache.CacheDataDescription; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/EntityRegionAdapter.java b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/EntityRegionAdapter.java index 4396f15522..8ef4b6f5eb 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/EntityRegionAdapter.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/EntityRegionAdapter.java @@ -24,6 +24,7 @@ */ package org.hibernate.cache.impl.bridge; +import org.hibernate.Logger; import org.hibernate.cache.Cache; import org.hibernate.cache.CacheConcurrencyStrategy; import org.hibernate.cache.CacheDataDescription; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/Logger.java b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/Logger.java deleted file mode 100644 index ba561f04e8..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/Logger.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.cache.impl.bridge; - -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger { - - @LogMessage( level = INFO ) - @Message( value = "Cache provider: %s" ) - void cacheProvider( String name ); - - @LogMessage( level = WARN ) - @Message( value = "read-only cache configured for mutable collection [%s]" ) - void readOnlyCacheConfiguredForMutableCollection( String name ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/RegionFactoryCacheProviderBridge.java b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/RegionFactoryCacheProviderBridge.java index f0d4b48d51..a930f0b0b3 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/RegionFactoryCacheProviderBridge.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/impl/bridge/RegionFactoryCacheProviderBridge.java @@ -24,6 +24,7 @@ package org.hibernate.cache.impl.bridge; import java.util.Properties; +import org.hibernate.Logger; import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.CacheException; import org.hibernate.cache.CacheProvider; @@ -48,7 +49,8 @@ import org.hibernate.util.ReflectHelper; public class RegionFactoryCacheProviderBridge implements RegionFactory { public static final String DEF_PROVIDER = NoCacheProvider.class.getName(); - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + RegionFactoryCacheProviderBridge.class.getPackage().getName()); private CacheProvider cacheProvider; private Settings settings; diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java index b0459a8eaa..0aea72cdb4 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -23,10 +23,6 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; @@ -87,6 +83,7 @@ import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; import org.hibernate.FetchMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; @@ -173,10 +170,6 @@ import org.hibernate.mapping.UnionSubclass; import org.hibernate.persister.entity.JoinedSubclassEntityPersister; import org.hibernate.persister.entity.SingleTableEntityPersister; import org.hibernate.persister.entity.UnionSubclassEntityPersister; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * JSR 175 annotation binder which reads the annotations from classes, applies the @@ -272,7 +265,7 @@ public final class AnnotationBinder { SequenceGenerator ann = pckg.getAnnotation( SequenceGenerator.class ); IdGenerator idGen = buildIdGenerator( ann, mappings ); mappings.addGenerator( idGen ); - LOG.addSequenceGenerator(idGen.getName()); + LOG.trace("Add sequence generator with name: " + idGen.getName()); } if ( pckg.isAnnotationPresent( TableGenerator.class ) ) { TableGenerator ann = pckg.getAnnotation( TableGenerator.class ); @@ -413,7 +406,7 @@ public final class AnnotationBinder { org.hibernate.id.enhanced.TableGenerator.INITIAL_PARAM, String.valueOf( tabGen.initialValue() + 1 ) ); - if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.tableGenerator(tabGen.name()); + if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.warn(tabGen.name()); } else { idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() ); @@ -441,7 +434,7 @@ public final class AnnotationBinder { } idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) ); } - LOG.addTableGenerator(idGen.getName()); + LOG.trace("Add table generator with name: " + idGen.getName()); } else if ( ann instanceof SequenceGenerator ) { SequenceGenerator seqGen = ( SequenceGenerator ) ann; @@ -471,7 +464,7 @@ public final class AnnotationBinder { // steve : or just use o.h.id.enhanced.SequenceStyleGenerator if (seqGen.initialValue() != 1) LOG.unsupportedInitialValue(Configuration.USE_NEW_ID_GENERATOR_MAPPINGS); idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) ); - LOG.addSequenceGenerator(idGen.getName()); + LOG.trace("Add sequence generator with name: " + idGen.getName()); } } else if ( ann instanceof GenericGenerator ) { @@ -482,7 +475,7 @@ public final class AnnotationBinder { for ( Parameter parameter : params ) { idGen.addParam( parameter.name(), parameter.value() ); } - LOG.addGenericGenerator(idGen.getName()); + LOG.trace("Add generic generator with name: " + idGen.getName()); } else { throw new AssertionFailure( "Unknown Generator annotation: " + ann ); @@ -996,7 +989,7 @@ public final class AnnotationBinder { SharedCacheMode mode; final Object value = mappings.getConfigurationProperties().get( "javax.persistence.sharedCache.mode" ); if ( value == null ) { - LOG.sharedCacheModeNotFound(); + LOG.debug("No value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED"); mode = SharedCacheMode.UNSPECIFIED; } else { @@ -1008,7 +1001,7 @@ public final class AnnotationBinder { mode = SharedCacheMode.valueOf( value.toString() ); } catch ( Exception e ) { - LOG.invalidSharedCacheMode(value, e); + LOG.debug("Unable to resolve given mode name [" + value + "]; using UNSPECIFIED : " + e); mode = SharedCacheMode.UNSPECIFIED; } } @@ -1024,24 +1017,24 @@ public final class AnnotationBinder { static void prepareDefaultCacheConcurrencyStrategy(Properties properties) { if ( DEFAULT_CACHE_CONCURRENCY_STRATEGY != null ) { - LOG.defaultCacheConcurrencyStrategyAlreadyDefined(); + LOG.trace("Default cache concurrency strategy already defined"); return; } if ( !properties.containsKey( Configuration.DEFAULT_CACHE_CONCURRENCY_STRATEGY ) ) { - LOG.defaultCacheConcurrencyStrategyNotFound(); + LOG.trace("Given properties did not contain any default cache concurrency strategy setting"); return; } final String strategyName = properties.getProperty( Configuration.DEFAULT_CACHE_CONCURRENCY_STRATEGY ); - LOG.defaultCacheConcurrencyStrategyDiscovered(strategyName); + LOG.trace("Discovered default cache concurrency strategy via config [" + strategyName + "]"); CacheConcurrencyStrategy strategy = CacheConcurrencyStrategy.parse( strategyName ); if ( strategy == null ) { - LOG.defaultCacheConcurrencyStrategySpecifiedNothing(); + LOG.trace("Discovered default cache concurrency strategy specified nothing"); return; } - LOG.defaultCacheConcurrencyStrategy(strategy.name()); + LOG.debug("Setting default cache concurrency strategy via config [" + strategy.name() + "]"); DEFAULT_CACHE_CONCURRENCY_STRATEGY = strategy; } @@ -1136,7 +1129,7 @@ public final class AnnotationBinder { ( Map ) null, ( PropertyHolder ) null, mappings ); } - LOG.subclassJoinedColumnsCreated(); + LOG.trace("Subclass joined column(s) created"); } else { if (clazzToProcess.isAnnotationPresent(PrimaryKeyJoinColumns.class) @@ -1326,7 +1319,7 @@ public final class AnnotationBinder { discriminatorColumn.linkWithValue( discrim ); discrim.setTypeName( discriminatorColumn.getDiscriminatorTypeName() ); rootClass.setPolymorphic( true ); - LOG.settingDiscriminator(rootClass.getEntityName()); + LOG.trace("Setting discriminator for entity " + rootClass.getEntityName()); } } @@ -1445,7 +1438,7 @@ public final class AnnotationBinder { * ordering does not matter */ - LOG.processingAnnotations(propertyHolder.getEntityName(), inferredData.getPropertyName()); + LOG.trace("Processing annotations of " + propertyHolder.getEntityName() + "." + inferredData.getPropertyName()); final XProperty property = inferredData.getProperty(); if ( property.isAnnotationPresent( Parent.class ) ) { @@ -1509,7 +1502,7 @@ public final class AnnotationBinder { + propertyHolder.getEntityName() ); } - LOG.versionProperty(inferredData.getPropertyName()); + LOG.trace(inferredData.getPropertyName() + " is a version property"); RootClass rootClass = ( RootClass ) propertyHolder.getPersistentClass(); propertyBinder.setColumns( columns ); Property prop = propertyBinder.makePropertyValueAndBind(); @@ -1533,7 +1526,8 @@ public final class AnnotationBinder { SimpleValue simpleValue = ( SimpleValue ) prop.getValue(); simpleValue.setNullValue( "undefined" ); rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION ); - LOG.version(rootClass.getVersion().getName(), ((SimpleValue)rootClass.getVersion().getValue()).getNullValue()); + LOG.trace("Version name: " + rootClass.getVersion().getName() + ", unsavedValue: " + + ((SimpleValue)rootClass.getVersion().getValue()).getNullValue()); } else { final boolean forcePersist = property.isAnnotationPresent( MapsId.class ) @@ -2141,7 +2135,7 @@ public final class AnnotationBinder { } //a component must not have any generator BinderHelper.makeIdGenerator( idValue, generatorType, generatorName, mappings, localGenerators ); - LOG.bindAnnotationToProperty((isComponent ? "@EmbeddedId" : "@Id"), inferredData.getPropertyName()); + LOG.trace("Bind " + (isComponent ? "@EmbeddedId" : "@Id") + " on " + inferredData.getPropertyName()); } //TODO move that to collection binder? @@ -2323,7 +2317,7 @@ public final class AnnotationBinder { */ Component comp = createComponent( propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper, mappings ); String subpath = BinderHelper.getPath( propertyHolder, inferredData ); - LOG.bindingComponent(subpath); + LOG.trace("Binding component with path: " + subpath); PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder( comp, subpath, inferredData, propertyHolder, mappings @@ -2752,7 +2746,7 @@ public final class AnnotationBinder { Mappings mappings) { //column.getTable() => persistentClass.getTable() final String propertyName = inferredData.getPropertyName(); - LOG.fetching(propertyName, fetchMode); + LOG.trace("Fetching " + propertyName + " with " + fetchMode); boolean mapToPK = true; if ( !trueOneToOne ) { //try to find a hidden true one to one (FK == PK columns) @@ -3075,144 +3069,4 @@ public final class AnnotationBinder { } return false; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Add generic generator with name: %s" ) - void addGenericGenerator( String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Add sequence generator with name: %s" ) - void addSequenceGenerator( String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Add table generator with name: %s" ) - void addTableGenerator( String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Bind %s on %s" ) - void bindAnnotationToProperty( String annotation, - String propertyName ); - - @LogMessage( level = TRACE ) - @Message( value = "Binding component with path: %s" ) - void bindingComponent( String subpath ); - - @LogMessage( level = INFO ) - @Message( value = "Binding entity from annotated class: %s" ) - void bindingEntityFromClass( String className ); - - @LogMessage( level = INFO ) - @Message( value = "Binding filter definition: %s" ) - void bindingFilterDefinition( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Binding type definition: %s" ) - void bindingTypeDefinition( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Setting default cache concurrency strategy via config [%s]" ) - void defaultCacheConcurrencyStrategy( String strategy ); - - @LogMessage( level = TRACE ) - @Message( value = "Default cache concurrency strategy already defined" ) - void defaultCacheConcurrencyStrategyAlreadyDefined(); - - @LogMessage( level = TRACE ) - @Message( value = "Discovered default cache concurrency strategy via config [%s]" ) - void defaultCacheConcurrencyStrategyDiscovered( String strategy ); - - @LogMessage( level = TRACE ) - @Message( value = "Given properties did not contain any default cache concurrency strategy setting" ) - void defaultCacheConcurrencyStrategyNotFound(); - - @LogMessage( level = TRACE ) - @Message( value = "Discovered default cache concurrency strategy specified nothing" ) - void defaultCacheConcurrencyStrategySpecifiedNothing(); - - @LogMessage( level = WARN ) - @Message( value = "@ForceDiscriminator is deprecated use @DiscriminatorOptions instead." ) - void deprecatedForceDescriminatorAnnotation(); - - @LogMessage( level = TRACE ) - @Message( value = "Fetching %s with %s" ) - void fetching( String propertyName, - FetchMode fetchMode ); - - @LogMessage( level = WARN ) - @Message( value = "Ignoring unique constraints specified on table generator [%s]" ) - void ignoringTableGeneratorConstraints(String name); - - @LogMessage( level = WARN ) - @Message( value = "Discriminator column has to be defined in the root entity, it will be ignored in subclass: %s" ) - void invalidDescriminatorAnnotation( String className ); - - @LogMessage( level = WARN ) - @Message( value = "Inapropriate use of @OnDelete on entity, annotation ignored: %s" ) - void invalidOnDeleteAnnotation( String entityName ); - - @LogMessage( level = WARN ) - @Message( value = "Root entity should not hold an PrimaryKeyJoinColum(s), will be ignored" ) - void invalidPrimaryKeyJoinColumnAnnotation(); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to resolve given mode name [%s]; using UNSPECIFIED : %s" ) - void invalidSharedCacheMode( Object value, - Exception error ); - - @LogMessage( level = WARN ) - @Message( value = "Mixing inheritance strategy in a entity hierarchy is not allowed, ignoring sub strategy in: %s" ) - void invalidSubStrategy( String className ); - - @LogMessage( level = WARN ) - @Message( value = "Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: %s" ) - void invalidTableAnnotation( String className ); - - @LogMessage( level = WARN ) - @Message( value = "Class annotated @org.hibernate.annotations.Entity but not javax.persistence.Entity (most likely a user error): %s" ) - void missingEntityAnnotation( String className ); - - @LogMessage( level = WARN ) - @Message( value = "Package not found or wo package-info.java: %s" ) - void packageNotFound( String packageName ); - - @LogMessage( level = TRACE ) - @Message( value = "Processing annotations of %s.%s" ) - void processingAnnotations( String entityName, - String propertyName ); - - @LogMessage( level = TRACE ) - @Message( value = "Setting discriminator for entity %s" ) - void settingDiscriminator( String entityName ); - - @LogMessage( level = DEBUG ) - @Message( value = "No value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED" ) - void sharedCacheModeNotFound(); - - @LogMessage( level = TRACE ) - @Message( value = "Subclass joined column(s) created" ) - void subclassJoinedColumnsCreated(); - - @LogMessage( level = WARN ) - @Message( value = "%s" ) - void tableGenerator( String name ); - - @LogMessage( level = WARN ) - @Message( value = "Hibernate does not support SequenceGenerator.initialValue() unless '%s' set" ) - void unsupportedInitialValue( String propertyName ); - - @LogMessage( level = TRACE ) - @Message( value = "Version name: %s, unsavedValue: %s" ) - void version( String name, - String nullValue ); - - @LogMessage( level = TRACE ) - @Message( value = "%s is a version property" ) - void versionProperty( String propertyName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java b/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java index 6f2cd9cc60..800e6579b5 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.INFO; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -36,6 +35,7 @@ import java.util.Set; import java.util.StringTokenizer; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.AnyMetaDef; import org.hibernate.annotations.AnyMetaDefs; @@ -63,10 +63,6 @@ import org.hibernate.mapping.Table; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -691,20 +687,7 @@ public class BinderHelper { } return pd; } - else { - String propertyPath = isId ? "" : propertyName; - return mappings.getPropertyAnnotatedWithMapsId( persistentXClass, propertyPath ); - } + String propertyPath = isId ? "" : propertyName; + return mappings.getPropertyAnnotatedWithMapsId(persistentXClass, propertyPath); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Binding Any Meta definition: %s" ) - void bindingAnyMetaDefinition( String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java index e69472162a..4f9557cb67 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java @@ -23,20 +23,16 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.Collections; import java.util.Iterator; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.mapping.Collection; import org.hibernate.mapping.IndexedCollection; import org.hibernate.mapping.OneToMany; import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Value; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Collection second pass @@ -64,7 +60,7 @@ public abstract class CollectionSecondPass implements SecondPass { public void doSecondPass(java.util.Map persistentClasses) throws MappingException { - LOG.secondPass(collection.getRole()); + LOG.debug("Second pass for collection: " + collection.getRole()); secondPass( persistentClasses, localInheritedMetas ); // using local since the inheritedMetas at this point is not the correct map since it is always the empty map collection.createAllKeys(); @@ -80,7 +76,7 @@ public abstract class CollectionSecondPass implements SecondPass { else { msg += ", element: " + columns( collection.getElement() ); } - LOG.mappedCollection(msg); + LOG.debug(msg); } } @@ -96,19 +92,4 @@ public abstract class CollectionSecondPass implements SecondPass { } return columns.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "%s" ) - void mappedCollection( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Second pass for collection: %s" ) - void secondPass( String role ); - } } 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 72505b8f27..fcc1cb418b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -23,11 +23,6 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -175,10 +170,6 @@ import org.hibernate.util.xml.Origin; import org.hibernate.util.xml.OriginImpl; import org.hibernate.util.xml.XmlDocument; import org.hibernate.util.xml.XmlDocumentImpl; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; @@ -586,7 +577,7 @@ public class Configuration implements Serializable { XmlDocument metadataXml = add( inputSource, "file", name ); try { - LOG.writingCacheFile(xmlFile, cachedFile); + LOG.debug("Writing cache file for: " + xmlFile + " to: " + cachedFile); SerializationHelper.serialize( ( Serializable ) metadataXml.getDocumentTree(), new FileOutputStream( cachedFile ) ); } catch (Exception e) { LOG.unableToWriteCachedFile(cachedFile.getPath(), e.getMessage()); @@ -653,7 +644,7 @@ public class Configuration implements Serializable { * given XML string */ public Configuration addXML(String xml) throws MappingException { - LOG.mappingXml(xml); + LOG.debug("Mapping XML:\n" + xml); final InputSource inputSource = new InputSource( new StringReader( xml ) ); add( inputSource, "string", "XML String" ); return this; @@ -670,7 +661,7 @@ public class Configuration implements Serializable { public Configuration addURL(URL url) throws MappingException { final String urlExternalForm = url.toExternalForm(); - LOG.readingMappingDocument(urlExternalForm); + LOG.debug("Reading mapping document from URL : " + urlExternalForm); try { add( url.openStream(), "URL", urlExternalForm ); @@ -691,7 +682,7 @@ public class Configuration implements Serializable { inputStream.close(); } catch ( IOException ignore ) { - LOG.unableToCloseInputStream(); + LOG.trace("Was unable to close input stream"); } } } @@ -705,7 +696,7 @@ public class Configuration implements Serializable { * the mapping document. */ public Configuration addDocument(org.w3c.dom.Document doc) throws MappingException { - LOG.mappingDocument(doc); + LOG.debug("Mapping Document:\n" + doc); final Document document = xmlHelper.createDOMReader().read( doc ); add( new XmlDocumentImpl( document, "unknown", null ) ); @@ -1345,7 +1336,7 @@ public class Configuration implements Serializable { } protected void secondPassCompile() throws MappingException { - LOG.startingSecondPassCompile(); + LOG.trace("Starting secondPassCompile() processing"); //process default values first { @@ -1432,7 +1423,7 @@ public class Configuration implements Serializable { * an entity having a PK made of a ManyToOne ...). */ private void processFkSecondPassInOrder() { - LOG.processingForeignKeyMappings(); + LOG.debug("Processing fk mappings (*ToOne and JoinedSubclass)"); List fkSecondPasses = getFKSecondPassesOnly(); if ( fkSecondPasses.size() == 0 ) { @@ -1672,10 +1663,10 @@ public class Configuration implements Serializable { } private void originalSecondPassCompile() throws MappingException { - LOG.processingExtendsQueue(); + LOG.debug("Processing extends queue"); processExtendsQueue(); - LOG.processingCollectionMappings(); + LOG.debug("Processing collection mappings"); Iterator itr = secondPasses.iterator(); while ( itr.hasNext() ) { SecondPass sp = (SecondPass) itr.next(); @@ -1685,7 +1676,7 @@ public class Configuration implements Serializable { } } - LOG.processingNativeQuery(); + LOG.debug("Processing native query and ResultSetMapping mappings"); itr = secondPasses.iterator(); while ( itr.hasNext() ) { SecondPass sp = (SecondPass) itr.next(); @@ -1693,7 +1684,7 @@ public class Configuration implements Serializable { itr.remove(); } - LOG.processingAssociationPropertyReferences(); + LOG.debug("Processing association property references"); itr = propertyReferences.iterator(); while ( itr.hasNext() ) { @@ -1715,7 +1706,7 @@ public class Configuration implements Serializable { //TODO: Somehow add the newly created foreign keys to the internal collection - LOG.processingForeignKeyConstraints(); + LOG.debug("Processing foreign key constraints"); itr = getTableMappings(); Set done = new HashSet(); @@ -1726,7 +1717,7 @@ public class Configuration implements Serializable { } private int processExtendsQueue() { - LOG.processingExtendsQueue(); + LOG.debug("Processing extends queue"); int added = 0; ExtendsQueueEntry extendsQueueEntry = findPossibleExtends(); while ( extendsQueueEntry != null ) { @@ -1783,7 +1774,7 @@ public class Configuration implements Serializable { " does not specify the referenced entity" ); } - LOG.resolvingReference(referencedEntityName); + LOG.debug("Resolving reference to class: " + referencedEntityName); PersistentClass referencedClass = classes.get( referencedEntityName ); if ( referencedClass == null ) { throw new MappingException( @@ -1857,7 +1848,7 @@ public class Configuration implements Serializable { } catch ( ClassNotFoundException e ) { //validator is not present - LOG.legacyValidatorNotFound(); + LOG.debug("Legacy Validator not present in classpath, ignoring event listener registration"); } if ( enableValidatorListeners && validateEventListenerClass != null ) { //TODO so much duplication @@ -1940,7 +1931,7 @@ public class Configuration implements Serializable { searchStartupClass = ReflectHelper.classForName( SEARCH_EVENT_LISTENER_REGISTERER_CLASS, getClass() ); } catch ( ClassNotFoundException cnfe ) { - LOG.searchNotFound(); + LOG.debug("Search not present in classpath, ignoring event listener registration."); return; } } @@ -1956,16 +1947,16 @@ public class Configuration implements Serializable { enableSearchMethod.invoke( searchStartupInstance, getEventListeners(), getProperties() ); } catch ( InstantiationException e ) { - LOG.unableToInstantiate(SEARCH_STARTUP_CLASS); + LOG.debug("Unable to instantiate " + SEARCH_STARTUP_CLASS + ", ignoring event listener registration."); } catch ( IllegalAccessException e ) { - LOG.unableToInstantiate(SEARCH_STARTUP_CLASS); + LOG.debug("Unable to instantiate " + SEARCH_STARTUP_CLASS + ", ignoring event listener registration."); } catch ( NoSuchMethodException e ) { - LOG.methodNotFound(SEARCH_STARTUP_METHOD, SEARCH_STARTUP_CLASS); + LOG.debug("Method " + SEARCH_STARTUP_METHOD + "() not found in " + SEARCH_STARTUP_CLASS); } catch ( InvocationTargetException e ) { - LOG.unableToExecute(SEARCH_STARTUP_METHOD); + LOG.debug("Unable to execute " + SEARCH_STARTUP_METHOD + ", ignoring event listener registration."); } } @@ -2079,7 +2070,7 @@ public class Configuration implements Serializable { Element node = (Element) itr.next(); String name = node.attributeValue( "name" ); String value = node.getText().trim(); - LOG.attribute(name, value); + LOG.debug(name + "=" + value); properties.setProperty( name, value ); if ( !name.startsWith( "hibernate" ) ) { properties.setProperty( "hibernate." + name, value ); @@ -2259,7 +2250,7 @@ public class Configuration implements Serializable { } LOG.configuredSessionFactory(name); - LOG.properties(properties); + LOG.debug("Properties: " + properties); return this; } @@ -2304,27 +2295,27 @@ public class Configuration implements Serializable { if ( resourceAttribute != null ) { final String resourceName = resourceAttribute.getValue(); - LOG.sessionFactoryConfigResourceForMapping(name, resourceName); + LOG.debug("Session-factory config [" + name + "] named resource [" + resourceName + "] for mapping"); addResource( resourceName ); } else if ( fileAttribute != null ) { final String fileName = fileAttribute.getValue(); - LOG.sessionFactoryConfigFileForMapping(name, fileName); + LOG.debug("Session-factory config [" + name + "] named file [" + fileName + "] for mapping"); addFile( fileName ); } else if ( jarAttribute != null ) { final String jarFileName = jarAttribute.getValue(); - LOG.sessionFactoryConfigJarForMapping(name, jarFileName); + LOG.debug("Session-factory config [" + name + "] named jar file [" + jarFileName + "] for mapping"); addJar( new File( jarFileName ) ); } else if ( packageAttribute != null ) { final String packageName = packageAttribute.getValue(); - LOG.sessionFactoryConfigPackageForMapping(name, packageName); + LOG.debug("Session-factory config [" + name + "] named package [" + packageName + "] for mapping"); addPackage( packageName ); } else if ( classAttribute != null ) { final String className = classAttribute.getValue(); - LOG.sessionFactoryConfigClassForMapping(name, className); + LOG.debug("Session-factory config [" + name + "] named class [" + className + "] for mapping"); try { addAnnotatedClass( ReflectHelper.classForName( className ) ); @@ -2367,7 +2358,7 @@ public class Configuration implements Serializable { for ( int i = 0; i < listeners.size() ; i++ ) { listenerClasses[i] = ( (Element) listeners.get( i ) ).attributeValue( "class" ); } - LOG.eventListeners(type, StringHelper.toString(listenerClasses)); + LOG.debug("Event listeners: " + type + "=" + StringHelper.toString(listenerClasses)); setListeners( type, listenerClasses ); } @@ -2377,7 +2368,7 @@ public class Configuration implements Serializable { throw new MappingException( "No type specified for listener" ); } String impl = element.attributeValue( "class" ); - LOG.eventListener(type, impl); + LOG.debug("Event listener: " + type + "=" + impl); setListeners( type, new String[]{impl} ); } @@ -3290,7 +3281,7 @@ public class Configuration implements Serializable { public void addTypeDef(String typeName, String typeClass, Properties paramMap) { TypeDef def = new TypeDef( typeClass, paramMap ); typeDefs.put( typeName, def ); - LOG.addedType(typeName, typeClass); + LOG.debug("Added " + typeName + " with class " + typeClass); } public Map getFilterDefinitions() { @@ -3914,7 +3905,7 @@ public class Configuration implements Serializable { } private void processHbmXmlQueue() { - LOG.processingHbmFiles(); + LOG.debug("Processing hbm.xml files"); for ( Map.Entry> entry : hbmMetadataToEntityNamesMap.entrySet() ) { // Unfortunately we have to create a Mappings instance for each iteration here processHbmXml( entry.getKey(), entry.getValue() ); @@ -3944,7 +3935,7 @@ public class Configuration implements Serializable { } private void processAnnotatedClassesQueue() { - LOG.processAnnotatedClasses(); + LOG.debug("Process annotated classes"); //bind classes in the correct order calculating some inheritance state List orderedClasses = orderAndFillHierarchy( annotatedClasses ); Mappings mappings = createMappings(); @@ -4067,256 +4058,4 @@ public class Configuration implements Serializable { public boolean isClass; public boolean cacheLazy; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Added %s with class %s" ) - void addedType( String typeName, - String typeClass ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s=%s" ) - void attribute( String name, - String value ); - - @LogMessage( level = DEBUG ) - @Message( value = "Preparing to build session factory with filters : %s" ) - void buildingSessionFactory( Map filterDefinitions ); - - @LogMessage( level = WARN ) - @Message( value = "I/O reported cached file could not be found : %s : %s" ) - void cachedFileNotFound( String path, - FileNotFoundException error ); - - @LogMessage( level = INFO ) - @Message( value = "Configuration resource: %s" ) - void configurationResource( String resource ); - - @LogMessage( level = INFO ) - @Message( value = "Configured SessionFactory: %s" ) - void configuredSessionFactory( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Configuring from file: %s" ) - void configuringFromFile( String file ); - - @LogMessage( level = INFO ) - @Message( value = "Configuring from resource: %s" ) - void configuringFromResource( String resource ); - - @LogMessage( level = INFO ) - @Message( value = "Configuring from URL: %s" ) - void configuringFromUrl( URL url ); - - @LogMessage( level = INFO ) - @Message( value = "Configuring from XML document" ) - void configuringFromXmlDocument(); - - @LogMessage( level = WARN ) - @Message( value = "Duplicate generator name %s" ) - void duplicateGeneratorName( String name ); - - @LogMessage( level = WARN ) - @Message( value = "Duplicate generator table: %s" ) - void duplicateGeneratorTable( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Duplicate import: %s -> %s" ) - void duplicateImport( String entityName, - String rename ); - - @LogMessage( level = WARN ) - @Message( value = "Duplicate joins for class: %s" ) - void duplicateJoins( String entityName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Event listener: %s=%s" ) - void eventListener( String type, - String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "Event listeners: %s=%s" ) - void eventListeners( String type, - String listenerClasses ); - - @LogMessage( level = INFO ) - @Message( value = "Found mapping document in jar: %s" ) - void foundMappingDocument( String name ); - - @LogMessage( level = WARN ) - @Message( value = "Mapping metadata cache was not completely processed" ) - void incompleteMappingMetadataCacheProcessing(); - - @LogMessage( level = INFO ) - @Message( value = "JACC contextID: %s" ) - void jaccContextId( String contextId ); - - @LogMessage( level = DEBUG ) - @Message( value = "Legacy Validator not present in classpath, ignoring event listener registration" ) - void legacyValidatorNotFound(); - - @LogMessage( level = DEBUG ) - @Message( value = "Mapping Document:\n%s" ) - void mappingDocument( org.w3c.dom.Document document ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping Package %s" ) - void mappingPackage( String packageName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Mapping XML:\n%s" ) - void mappingXml( String xml ); - - @LogMessage( level = DEBUG ) - @Message( value = "Method %s() not found in %s" ) - void methodNotFound( String searchStartupMethod, - String searchStartupClass ); - - @LogMessage( level = DEBUG ) - @Message( value = "Process annotated classes" ) - void processAnnotatedClasses(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing association property references" ) - void processingAssociationPropertyReferences(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing collection mappings" ) - void processingCollectionMappings(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing extends queue" ) - void processingExtendsQueue(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing foreign key constraints" ) - void processingForeignKeyConstraints(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing fk mappings (*ToOne and JoinedSubclass)" ) - void processingForeignKeyMappings(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing hbm.xml files" ) - void processingHbmFiles(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing native query and ResultSetMapping mappings" ) - void processingNativeQuery(); - - @LogMessage( level = DEBUG ) - @Message( value = "Properties: %s" ) - void properties( Properties properties ); - - @LogMessage( level = INFO ) - @Message( value = "Reading mappings from cache file: %s" ) - void readingCachedMappings( File cachedFile ); - - @LogMessage( level = DEBUG ) - @Message( value = "Reading mapping document from URL : %s" ) - void readingMappingDocument( String urlExternalForm ); - - @LogMessage( level = INFO ) - @Message( value = "Reading mappings from file: %s" ) - void readingMappingsFromFile( String path ); - - @LogMessage( level = INFO ) - @Message( value = "Reading mappings from resource: %s" ) - void readingMappingsFromResource( String resourceName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolving reference to class: %s" ) - void resolvingReference( String referencedEntityName ); - - @LogMessage( level = INFO ) - @Message( value = "Searching for mapping documents in jar: %s" ) - void searchingForMappingDocuments( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Search not present in classpath, ignoring event listener registration." ) - void searchNotFound(); - - @LogMessage( level = DEBUG ) - @Message( value = "Session-factory config [%s] named class [%s] for mapping" ) - void sessionFactoryConfigClassForMapping( String configName, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Session-factory config [%s] named file [%s] for mapping" ) - void sessionFactoryConfigFileForMapping( String configName, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Session-factory config [%s] named jar file [%s] for mapping" ) - void sessionFactoryConfigJarForMapping( String configName, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Session-factory config [%s] named package [%s] for mapping" ) - void sessionFactoryConfigPackageForMapping( String configName, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Session-factory config [%s] named resource [%s] for mapping" ) - void sessionFactoryConfigResourceForMapping( String configName, - String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting secondPassCompile() processing" ) - void startingSecondPassCompile(); - - @LogMessage( level = WARN ) - @Message( value = "Unable to apply constraints on DDL for %s : %s" ) - void unableToApplyConstraints( String className, - String message ); - - @LogMessage( level = TRACE ) - @Message( value = "Was unable to close input stream" ) - void unableToCloseInputStream(); - - @LogMessage( level = WARN ) - @Message( value = "Could not close input stream for %s : %s" ) - void unableToCloseInputStream( String resourceName, - String message ); - - @LogMessage( level = ERROR ) - @Message( value = "Could not close jar: %s" ) - void unableToCloseJar( String message ); - - @LogMessage( level = WARN ) - @Message( value = "Could not deserialize cache file: %s : %s" ) - void unableToDeserializeCache( String path, - SerializationException error ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to execute %s, ignoring event listener registration." ) - void unableToExecute( String searchStartupMethod ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to instantiate %s, ignoring event listener registration." ) - void unableToInstantiate( String searchStartupClass ); - - @LogMessage( level = ERROR ) - @Message( value = "Could not parse the package-level metadata [%s]" ) - void unableToParseMetadata( String packageName ); - - @LogMessage( level = WARN ) - @Message( value = "I/O reported error writing cached file : %s: %s" ) - void unableToWriteCachedFile( String path, - String message ); - - @LogMessage( level = INFO ) - @Message( value = "Hibernate Validator not found: ignoring" ) - void validatorNotFound(); - - @LogMessage( level = DEBUG ) - @Message( value = "Writing cache file for: %s to: %s" ) - void writingCacheFile( File xmlFile, - File cachedFile ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java b/hibernate-core/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java index cee5d98352..fabe26723e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java @@ -23,13 +23,9 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.InputStream; +import org.hibernate.Logger; import org.hibernate.util.DTDEntityResolver; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; @@ -56,7 +52,7 @@ public class EJB3DTDEntityResolver extends DTDEntityResolver { @Override public InputSource resolveEntity(String publicId, String systemId) { - LOG.resolvingXmlEntity(publicId, systemId); + LOG.trace("Resolving XML entity " + publicId + " : " + systemId); InputSource is = super.resolveEntity( publicId, systemId ); if ( is == null ) { if ( systemId != null ) { @@ -92,10 +88,10 @@ public class EJB3DTDEntityResolver extends DTDEntityResolver { private InputSource buildInputSource(String publicId, String systemId, InputStream dtdStream, boolean resolved) { if ( dtdStream == null ) { - LOG.unableToLocate(systemId); + LOG.trace("Unable to locate [" + systemId + "] on classpath"); return null; } - LOG.located(systemId); + LOG.trace("Located [" + systemId + "] in classpath"); InputSource source = new InputSource(dtdStream); source.setPublicId(publicId); source.setSystemId(systemId); @@ -104,33 +100,9 @@ public class EJB3DTDEntityResolver extends DTDEntityResolver { } private InputStream getStreamFromClasspath(String fileName) { - LOG.resolvingFileName(); + LOG.trace("Recognized JPA ORM namespace; attempting to resolve on classpath under org/hibernate/ejb"); String path = "org/hibernate/ejb/" + fileName; InputStream dtdStream = resolveInHibernateNamespace( path ); return dtdStream; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Located [%s] in classpath" ) - void located( String systemId ); - - @LogMessage( level = TRACE ) - @Message( value = "Recognized JPA ORM namespace; attempting to resolve on classpath under org/hibernate/ejb" ) - void resolvingFileName(); - - @LogMessage( level = TRACE ) - @Message( value = "Resolving XML entity %s : %s" ) - void resolvingXmlEntity( String publicId, - String systemId ); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to locate [%s] on classpath" ) - void unableToLocate( String systemId ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java index 161666bcc2..9930579e0e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java @@ -23,10 +23,10 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.Map; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; +import org.hibernate.Logger; import org.hibernate.annotations.ColumnTransformer; import org.hibernate.annotations.ColumnTransformers; import org.hibernate.annotations.Index; @@ -38,10 +38,6 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Wrap state of an EJB3 @Column annotation @@ -186,7 +182,7 @@ public class Ejb3Column { public void bind() { if ( StringHelper.isNotEmpty( formulaString ) ) { - LOG.bindingFormula(formulaString); + LOG.debug("Binding formula " + formulaString); formula = new Formula(); formula.setFormula( formulaString ); } @@ -194,7 +190,7 @@ public class Ejb3Column { initMappingColumn( logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true ); - LOG.bindingColumn(toString()); + LOG.debug("Binding column: " + toString()); } } @@ -425,7 +421,7 @@ public class Ejb3Column { throw new AnnotationException( "AttributeOverride.column() should override all columns for now" ); } actualCols = overriddenCols.length == 0 ? null : overriddenCols; - LOG.columnsOverridden(inferredData.getPropertyName()); + LOG.debug("Column(s) overridden for property " + inferredData.getPropertyName()); } if ( actualCols == null ) { columns = buildImplicitColumn( @@ -631,23 +627,4 @@ public class Ejb3Column { sb.append( '}' ); return sb.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Binding column: %s" ) - void bindingColumn( String column ); - - @LogMessage( level = DEBUG ) - @Message( value = "Binding formula %s" ) - void bindingFormula( String formula ); - - @LogMessage( level = DEBUG ) - @Message( value = "Column(s) overridden for property %s" ) - void columnsOverridden( String propertyName ); - } } 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 f6a8bb82fb..929a10f9e8 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -23,9 +23,6 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; @@ -36,14 +33,11 @@ import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.Version; import org.hibernate.bytecode.BytecodeProvider; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.util.ConfigHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -812,81 +806,4 @@ public final class Environment { LOG.unknownBytecodeProvider(providerName); return new org.hibernate.bytecode.javassist.BytecodeProviderImpl(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Bytecode provider name : %s" ) - void bytecodeProvider( String provider ); - - @LogMessage( level = INFO ) - @Message( value = "JVM does not support Statement.getGeneratedKeys()" ) - void generatedKeysNotSupported(); - - @LogMessage( level = INFO ) - @Message( value = "JVM does not support LinkedHashMap, LinkedHashSet - ordered maps and sets disabled" ) - void linkedMapsAndSetsNotSupported(); - - @LogMessage( level = INFO ) - @Message( value = "Loaded properties from resource hibernate.properties: %s" ) - void propertiesLoaded( Properties maskOut ); - - @LogMessage( level = INFO ) - @Message( value = "hibernate.properties not found" ) - void propertiesNotFound(); - - @LogMessage( level = WARN ) - @Message( value = "Property [%s] has been renamed to [%s]; update your properties appropriately" ) - void renamedProperty( Object propertyName, - Object newPropertyName ); - - @LogMessage( level = ERROR ) - @Message( value = "Could not close stream on hibernate.properties: %s" ) - void unableToCloseStream( IOException error ); - - @LogMessage( level = WARN ) - @Message( value = "Could not copy system properties, system properties will be ignored" ) - void unableToCopySystemProperties(); - - @LogMessage( level = ERROR ) - @Message( value = "Problem loading properties from hibernate.properties" ) - void unableToloadProperties(); - - @LogMessage( level = WARN ) - @Message( value = "unrecognized bytecode provider [%s], using javassist by default" ) - void unknownBytecodeProvider( String providerName ); - - @LogMessage( level = WARN ) - @Message( value = "Usage of obsolete property: %s no longer supported, use: %s" ) - void unsupportedProperty( Object propertyName, - Object newPropertyName ); - - @LogMessage( level = INFO ) - @Message( value = "Using JDK 1.4 java.sql.Timestamp handling" ) - void usingJdk14TimestampHandling(); - - @LogMessage( level = INFO ) - @Message( value = "Using pre JDK 1.4 java.sql.Timestamp handling" ) - void usingPreJdk14TimestampHandling(); - - @LogMessage( level = INFO ) - @Message( value = "Using bytecode reflection optimizer" ) - void usingReflectionOptimizer(); - - @LogMessage( level = INFO ) - @Message( value = "Using java.io streams to persist binary types" ) - void usingStreams(); - - @LogMessage( level = INFO ) - @Message( value = "Using workaround for JVM bug in java.sql.Timestamp" ) - void usingTimestampWorkaround(); - - @LogMessage( level = INFO ) - @Message( value = "Hibernate %s" ) - void version( String versionString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java index b644df502d..9a5978aeba 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java @@ -23,9 +23,6 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -39,6 +36,7 @@ import org.hibernate.CacheMode; import org.hibernate.EntityMode; import org.hibernate.FetchMode; import org.hibernate.FlushMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.FilterDefinition; @@ -99,10 +97,6 @@ import org.hibernate.util.JoinedIterator; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; import org.hibernate.util.xml.XmlDocument; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Walks an XML mapping document and produces the Hibernate configuration-time metamodel (the @@ -234,7 +228,7 @@ public final class HbmBinder { String rename = ( renameNode == null ) ? StringHelper.unqualify( className ) : renameNode.getValue(); - LOG.bindImport( rename, className ); + LOG.debug("Import: " + rename + " -> " + className); mappings.addImport( className, rename ); } @@ -1324,7 +1318,7 @@ public final class HbmBinder { if ( columns.length() > 0 ) msg += " -> " + columns; // TODO: this fails if we run with debug on! // if ( model.getType()!=null ) msg += ", type: " + model.getType().getName(); - LOG.mappedProperty(msg); + LOG.debug(msg); } property.setMetaAttributes( getMetas( node, inheritedMetas ) ); @@ -2606,7 +2600,7 @@ public final class HbmBinder { if ( condition==null) { throw new MappingException("no filter condition found for filter: " + name); } - LOG.applyingManyToManyFilter(name, condition, collection.getRole()); + LOG.debug("Applying many-to-many filter [" + name + "] as [" + condition + "] to role [" + collection.getRole() + "]"); collection.addManyToManyFilter( name, condition ); } } @@ -2639,7 +2633,7 @@ public final class HbmBinder { String queryName = queryElem.attributeValue( "name" ); if (path!=null) queryName = path + '.' + queryName; String query = queryElem.getText(); - LOG.namedQuery(queryName, query); + LOG.debug("Named query: " + queryName + " -> " + query); boolean cacheable = "true".equals( queryElem.attributeValue( "cacheable" ) ); String region = queryElem.attributeValue( "cache-region" ); @@ -2972,7 +2966,7 @@ public final class HbmBinder { private static void parseFilterDef(Element element, Mappings mappings) { String name = element.attributeValue( "name" ); - LOG.parsingFilterDefinition(name); + LOG.debug("Parsing filter-def [" + name + "]"); String defaultCondition = element.getTextTrim(); if ( StringHelper.isEmpty( defaultCondition ) ) { defaultCondition = element.attributeValue( "condition" ); @@ -2983,12 +2977,12 @@ public final class HbmBinder { final Element param = (Element) params.next(); final String paramName = param.attributeValue( "name" ); final String paramType = param.attributeValue( "type" ); - LOG.addingFilterParameter(paramName, paramType); + LOG.debug("Adding filter parameter : " + paramName + " -> " + paramType); final Type heuristicType = mappings.getTypeResolver().heuristicType( paramType ); - LOG.parameterHeuristicType(heuristicType); + LOG.debug("Parameter heuristic type : " + heuristicType); paramMappings.put( paramName, heuristicType ); } - LOG.parsedFilterDefinition(name); + LOG.debug("Parsed filter-def [" + name + "]"); FilterDefinition def = new FilterDefinition( name, defaultCondition, paramMappings ); mappings.addFilterDefinition( def ); } @@ -3011,7 +3005,7 @@ public final class HbmBinder { if ( condition==null) { throw new MappingException("no filter condition found for filter: " + name); } - LOG.applyingFilter(name, condition); + LOG.debug("Applying filter [" + name + "] as [" + condition + "]"); filterable.addFilter( name, condition ); } @@ -3147,87 +3141,4 @@ public final class HbmBinder { private static interface EntityElementHandler { public void handleEntity(String entityName, String className, Mappings mappings); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Applying filter [%s] as [%s]" ) - void applyingFilter( String name, - String condition ); - - @LogMessage( level = DEBUG ) - @Message( value = "Adding filter parameter : %s -> %s" ) - void addingFilterParameter( String paramName, - String paramType ); - - @LogMessage( level = DEBUG ) - @Message( value = "Applying many-to-many filter [%s] as [%s] to role [%s]" ) - void applyingManyToManyFilter( String name, - String condition, - String role ); - - @LogMessage( level = WARN ) - @Message( value = "Attribute \"order-by\" ignored in JDK1.3 or less" ) - void attributeIgnored(); - - @LogMessage( level = DEBUG ) - @Message( value = "Import: %s -> %s" ) - void bindImport( String rename, - String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s" ) - void mappedProperty( String message ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping class: %s -> %s" ) - void mappingClass( String entityName, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping class join: %s -> %s" ) - void mappingClassJoin( String entityName, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping collection: %s -> %s" ) - void mappingCollection( String entityName, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping joined-subclass: %s -> %s" ) - void mappingJoinedSubclass( String entityName, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping subclass: %s -> %s" ) - void mappingSubclass( String entityName, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping union-subclass: %s -> %s" ) - void mappingUnionSubclass( String entityName, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Named query: %s -> %s" ) - void namedQuery( String queryName, - String query ); - - @LogMessage( level = DEBUG ) - @Message( value = "Parameter heuristic type : %s" ) - void parameterHeuristicType( Type heuristicType ); - - @LogMessage( level = DEBUG ) - @Message( value = "Parsed filter-def [%s]" ) - void parsedFilterDefinition( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Parsing filter-def [%s]" ) - void parsingFilterDefinition( String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java index 632bda748e..bb3686dcea 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java @@ -23,20 +23,16 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Element; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.NamedSQLQueryDefinition; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -120,19 +116,7 @@ public class NamedSQLQuerySecondPass extends ResultSetMappingBinder implements Q ); } - LOG.namedSqlQuery(queryName, namedQuery.getQueryString()); + LOG.debug("Named SQL query: " + queryName + " -> " + namedQuery.getQueryString()); mappings.addSQLQuery( queryName, namedQuery ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Named SQL query: %s -> %s" ) - void namedSqlQuery( String queryName, - String namedQuery ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java b/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java index 3b9f07763b..550477bc7a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java @@ -26,7 +26,6 @@ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.WARN; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -39,6 +38,7 @@ import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Transient; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.ManyToAny; import org.hibernate.annotations.Target; @@ -46,10 +46,6 @@ import org.hibernate.annotations.Type; import org.hibernate.annotations.common.reflection.XClass; import org.hibernate.annotations.common.reflection.XProperty; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A helper class to keep the {@code XProperty}s of a class ordered by access type. @@ -278,17 +274,6 @@ class PropertyContainer { || "net.sf.cglib.transform.impl.InterceptFieldCallback".equals( property.getType().getName() ) || "org.hibernate.bytecode.javassist.FieldHandler".equals( property.getType().getName() ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Placing @Access(AccessType.%s) on a field does not have any effect." ) - void annotationHasNoEffect( AccessType type ); - } } 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 c8b97dfacc..e27339d47b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java @@ -23,11 +23,7 @@ */ package org.hibernate.cfg; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; -import java.sql.SQLException; import java.util.Map; import java.util.Properties; import org.hibernate.ConnectionReleaseMode; @@ -51,10 +47,6 @@ import org.hibernate.transaction.TransactionManagerLookup; import org.hibernate.transaction.TransactionManagerLookupFactory; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Reads configuration properties and builds a {@link Settings} instance. @@ -285,7 +277,7 @@ public class SettingsFactory implements Serializable { return new org.hibernate.bytecode.cglib.BytecodeProviderImpl(); } else { - LOG.usingJavassist(); + LOG.debug("Using javassist as bytecode provider by default"); return new org.hibernate.bytecode.javassist.BytecodeProviderImpl(); } } @@ -378,193 +370,4 @@ public class SettingsFactory implements Serializable { protected TransactionManagerLookup createTransactionManagerLookup(Properties properties) { return TransactionManagerLookupFactory.getTransactionManagerLookup(properties); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Automatic flush during beforeCompletion(): %s" ) - void autoFlush( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Automatic session close at end of transaction: %s" ) - void autoSessionClose( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Batcher factory: %s" ) - void batcherFactory( String batcherClass ); - - @LogMessage( level = INFO ) - @Message( value = "Cache region factory : %s" ) - void cacheRegionFactory( String regionFactoryClassName ); - - @LogMessage( level = INFO ) - @Message( value = "Cache region prefix: %s" ) - void cacheRegionPrefix( String prefix ); - - @LogMessage( level = INFO ) - @Message( value = "Check Nullability in Core (should be disabled when Bean Validation is on): %s" ) - void checkNullability( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Connection release mode: %s" ) - void connectionReleaseMode( String releaseModeName ); - - @LogMessage( level = INFO ) - @Message( value = "%s did not provide constructor accepting java.util.Properties; attempting no-arg constructor." ) - void constructorWithPropertiesNotFound( String regionFactoryClassName ); - - @LogMessage( level = INFO ) - // @formatter:off - @Message( value = "Database ->\n" + - " name : %s\n" + - " version : %s\n" + - " major : %s\n" + - " minor : %s" ) - // @formatter:on - void database( String databaseProductName, - String databaseProductVersion, - int databaseMajorVersion, - int databaseMinorVersion ); - - @LogMessage( level = INFO ) - @Message( value = "Default batch fetch size: %s" ) - void defaultBatchFetchSize( int batchFetchSize ); - - @LogMessage( level = INFO ) - @Message( value = "Default catalog: %s" ) - void defaultCatalog( String defaultCatalog ); - - @LogMessage( level = INFO ) - @Message( value = "Default entity-mode: %s" ) - void defaultEntityMode( EntityMode defaultEntityMode ); - - @LogMessage( level = INFO ) - @Message( value = "Default schema: %s" ) - void defaultSchema( String defaultSchema ); - - @LogMessage( level = INFO ) - @Message( value = "Deleted entity synthetic identifier rollback: %s" ) - void deletedEntitySyntheticIdentifierRollback( String enabledDisabled ); - - @LogMessage( level = INFO ) - // @formatter:off - @Message( value = "Driver ->\n" + - " name : %s\n" + - " version : %s\n" + - " major : %s\n" + - " minor : %s" ) - // @formatter:on - void driver( String driverProductName, - String driverProductVersion, - int driverMajorVersion, - int driverMinorVersion ); - - @LogMessage( level = INFO ) - @Message( value = "Echoing all SQL to stdout" ) - void echoingSql(); - - @LogMessage( level = INFO ) - @Message( value = "Generate SQL with comments: %s" ) - void generateSqlWithComments( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "JDBC3 getGeneratedKeys(): %s" ) - void jdbc3GeneratedKeys( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "JDBC batch size: %s" ) - void jdbcBatchSize( int batchSize ); - - @LogMessage( level = INFO ) - @Message( value = "JDBC batch updates for versioned data: %s" ) - void jdbcBatchUpdates( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "JDBC result set fetch size: %s" ) - void jdbcResultSetFetchSize( Integer statementFetchSize ); - - @LogMessage( level = INFO ) - @Message( value = "JPA-QL strict compliance: %s" ) - void jpaQlStrictCompliance( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Maximum outer join fetch depth: %s" ) - void maxOuterJoinFetchDepth( Integer maxFetchDepth ); - - @LogMessage( level = INFO ) - @Message( value = "Named query checking : %s" ) - void namedQueryChecking( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Optimize cache for minimal puts: %s" ) - void optimizeCacheForMinimalInputs( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Order SQL inserts for batching: %s" ) - void orderSqlInsertsForBatching( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Order SQL updates by primary key: %s" ) - void orderSqlUpdatesByPrimaryKey( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache: %s" ) - void queryCache( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache factory: %s" ) - void queryCacheFactory( String queryCacheFactoryClassName ); - - @LogMessage( level = INFO ) - @Message( value = "Query language substitutions: %s" ) - void queryLanguageSubstitutions( Map querySubstitutions ); - - @LogMessage( level = INFO ) - @Message( value = "Query translator: %s" ) - void queryTranslator( String className ); - - @LogMessage( level = INFO ) - @Message( value = "Scrollable result sets: %s" ) - void scrollabelResultSets( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Second-level cache: %s" ) - void secondLevelCache( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Statistics: %s" ) - void statistics( String enabledDisabled ); - - @LogMessage( level = INFO ) - @Message( value = "Structured second-level cache entries: %s" ) - void structuredSecondLevelCacheEntries( String enabledDisabled ); - - @LogMessage( level = WARN ) - @Message( value = "Could not obtain connection metadata: %s" ) - void unableToObjectConnectionMetadata( SQLException error ); - - @LogMessage( level = WARN ) - @Message( value = "Could not obtain connection to query metadata: %s" ) - void unableToObjectConnectionToQueryMetadata( SQLException error ); - - @LogMessage( level = WARN ) - @Message( value = "Overriding release mode as connection provider does not support 'after_statement'" ) - void unsupportedAfterStatement(); - - @LogMessage( level = DEBUG ) - @Message( value = "Using javassist as bytecode provider by default" ) - void usingJavassist(); - - @LogMessage( level = WARN ) - @Message( value = "Error building SQLExceptionConverter; using minimal converter" ) - void usingMinimalConverter(); - - @LogMessage( level = INFO ) - @Message( value = "Wrap result sets: %s" ) - void wrapResultSets( String enabledDisabled ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java index 87f627425d..320949470d 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java @@ -23,8 +23,6 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -46,6 +44,7 @@ import javax.persistence.MapKeyColumn; import javax.persistence.OneToMany; import org.hibernate.AnnotationException; import org.hibernate.FetchMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; @@ -110,10 +109,6 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.Table; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Base class for binding different types of collections to Hibernate configuration objects. @@ -376,7 +371,7 @@ public abstract class CollectionBinder { public void bind() { this.collection = createCollection( propertyHolder.getPersistentClass() ); String role = StringHelper.qualify(propertyHolder.getPath(), propertyName); - LOG.collectionRole(role); + LOG.debug("Collection role: " + role); collection.setRole(role); collection.setNodeName( propertyName ); @@ -720,7 +715,7 @@ public abstract class CollectionBinder { String hqlOrderBy, Mappings mappings, Map inheritanceStatePerClass) { - LOG.bindingOneToMany(propertyHolder.getEntityName(), propertyName); + LOG.debug("Binding a OneToMany: " + propertyHolder.getEntityName() + "." + propertyName + " through a foreign key"); org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany( mappings, collection.getOwner() ); collection.setElement( oneToMany ); oneToMany.setReferencedEntityName( collectionType.getName() ); @@ -1151,10 +1146,10 @@ public abstract class CollectionBinder { ManyToAny anyAnn = property.getAnnotation( ManyToAny.class ); if (LOG.isDebugEnabled()) { String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName(); - if (isCollectionOfEntities && unique) LOG.bindingOneToMany(path); - else if (isCollectionOfEntities) LOG.bindingManyToMany(path); - else if (anyAnn != null) LOG.bindingManyToAny(path); - else LOG.bindingCollection(path); + if (isCollectionOfEntities && unique) LOG.debug("Binding a OneToMany: " + path + " through an association table"); + else if (isCollectionOfEntities) LOG.debug("Binding as ManyToMany: " + path); + else if (anyAnn != null) LOG.debug("Binding a ManyToAny: " + path); + else LOG.debug("Binding a collection of element: " + path); } //check for user error if ( !isCollectionOfEntities ) { @@ -1541,41 +1536,4 @@ public abstract class CollectionBinder { public void setLocalGenerators(HashMap localGenerators) { this.localGenerators = localGenerators; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Binding a collection of element: %s" ) - void bindingCollection( String property ); - - @LogMessage( level = DEBUG ) - @Message( value = "Binding a ManyToAny: %s" ) - void bindingManyToAny( String property ); - - @LogMessage( level = DEBUG ) - @Message( value = "Binding as ManyToMany: %s" ) - void bindingManyToMany( String property ); - - @LogMessage( level = DEBUG ) - @Message( value = "Binding a OneToMany: %s through an association table" ) - void bindingOneToMany( String property ); - - @LogMessage( level = DEBUG ) - @Message( value = "Binding a OneToMany: %s.%s through a foreign key" ) - void bindingOneToMany( String entity, - String property ); - - @LogMessage( level = DEBUG ) - @Message( value = "Collection role: %s" ) - void collectionRole( String role ); - - @LogMessage( level = INFO ) - @Message( value = "Mapping collection: %s -> %s" ) - void mappingCollection( String role, - String collectionTable ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java index 568d4acdee..a2e37d79f0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java @@ -23,9 +23,6 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -40,6 +37,7 @@ import javax.persistence.SecondaryTables; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; @@ -87,10 +85,6 @@ import org.hibernate.mapping.TableOwner; import org.hibernate.mapping.Value; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Stateful holder and processor for binding Entity information @@ -345,7 +339,7 @@ public class EntityBinder { persistentClass.addFilter( filterName, cond ); } } else if (filters.size() > 0) LOG.filterAnnotationOnSubclass(persistentClass.getEntityName()); - LOG.importWithEntityName(name); + LOG.debug("Import with entity name " + name); try { mappings.addImport( persistentClass.getEntityName(), name ); String entityName = persistentClass.getEntityName(); @@ -922,37 +916,4 @@ public class EntityBinder { return accessType; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Adding secondary table to entity %s -> %s" ) - void addingSecondaryTableToEntity( String entity, - String table ); - - @LogMessage( level = INFO ) - @Message( value = "Bind entity %s on table %s" ) - void bindEntityOnTable( String entity, - String table ); - - @LogMessage( level = WARN ) - @Message( value = "@org.hibernate.annotations.Entity used on a non root entity: ignored for %s" ) - void entityAnnotationOnNonRoot( String className ); - - @LogMessage( level = WARN ) - @Message( value = "@Filter not allowed on subclasses (ignored): %s" ) - void filterAnnotationOnSubclass( String className ); - - @LogMessage( level = WARN ) - @Message( value = "@Immutable used on a non root entity: ignored for %s" ) - void immutableAnnotationOnNonRoot( String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "Import with entity name %s" ) - void importWithEntityName( String entity ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ListBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ListBinder.java index 3a87e544cf..e5d3d1b121 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ListBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ListBinder.java @@ -23,9 +23,9 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.WARN; import java.util.Map; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.annotations.OrderBy; import org.hibernate.annotations.Sort; @@ -45,10 +45,6 @@ import org.hibernate.mapping.OneToMany; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Bind a list to the underlying Hibernate configuration @@ -147,19 +143,4 @@ public class ListBinder extends CollectionBinder { ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "@OrderBy not allowed for an indexed collection, annotation ignored." ) - void orderByAnnotationIndexedCollection(); - - @LogMessage( level = WARN ) - @Message( value = "@Sort not allowed for an indexed collection, annotation ignored." ) - void sortAnnotationIndexedCollection(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java index c46975f806..8a89b8f412 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java @@ -23,12 +23,11 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.Map; import javax.persistence.EmbeddedId; import javax.persistence.Id; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; import org.hibernate.annotations.Immutable; @@ -53,10 +52,6 @@ import org.hibernate.mapping.RootClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Value; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -176,7 +171,7 @@ public class PropertyBinder { private Property makePropertyAndValue() { validateBind(); - LOG.bindingPropertyWithLazy(name, lazy); + LOG.debug("Binder property " + name + " with lazy=" + lazy); String containerClassName = holder == null ? null : holder.getClassName(); @@ -256,7 +251,7 @@ public class PropertyBinder { //used when the value is provided and the binding is done elsewhere public Property makeProperty() { validateMake(); - LOG.buildingProperty(name); + LOG.debug("Building property " + name); Property prop = new Property(); prop.setName( name ); prop.setNodeName( name ); @@ -313,7 +308,7 @@ public class PropertyBinder { ); } } - LOG.cascadingProperty(name, cascade); + LOG.trace("Cascading " + name + " with " + cascade); this.mappingProperty = prop; return prop; } @@ -341,25 +336,4 @@ public class PropertyBinder { public void setInheritanceStatePerClass(Map inheritanceStatePerClass) { this.inheritanceStatePerClass = inheritanceStatePerClass; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Binder property %s with lazy=%s" ) - void bindingPropertyWithLazy( String property, - boolean lazy ); - - @LogMessage( level = DEBUG ) - @Message( value = "Building property %s" ) - void buildingProperty( String property ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading %s with %s" ) - void cascadingProperty( String property, - String cascade ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java index f11e74a6e0..b490b1308b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.INFO; import java.util.HashMap; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; @@ -37,6 +36,7 @@ import org.hibernate.AssertionFailure; import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.annotations.CacheModeType; import org.hibernate.annotations.FlushModeType; import org.hibernate.cfg.BinderHelper; @@ -46,10 +46,6 @@ import org.hibernate.engine.NamedQueryDefinition; import org.hibernate.engine.NamedSQLQueryDefinition; import org.hibernate.engine.query.sql.NativeSQLQueryReturn; import org.hibernate.engine.query.sql.NativeSQLQueryRootReturn; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Query binder @@ -424,21 +420,4 @@ public abstract class QueryBinder { } return timeout; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Binding named native query: %s => %s" ) - void bindingNamedNativeQuery( String name, - String query ); - - @LogMessage( level = INFO ) - @Message( value = "Binding named query: %s => %s" ) - void bindingNamedQuery( String name, - String query ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java index 49c0656371..5187b1f3b0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.INFO; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -36,6 +35,7 @@ import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.SqlResultSetMapping; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.BinderHelper; import org.hibernate.cfg.Mappings; @@ -49,10 +49,6 @@ import org.hibernate.mapping.Property; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -269,15 +265,4 @@ public class ResultsetMappingSecondPass implements QuerySecondPass { } return -1; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Binding result set mapping: %s" ) - void bindingResultSetMapping( String mapping ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SetBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SetBinder.java index 13e97b1419..2bfbf2b445 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SetBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SetBinder.java @@ -23,15 +23,11 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.WARN; +import org.hibernate.Logger; import org.hibernate.annotations.OrderBy; import org.hibernate.cfg.Environment; import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Bind a set. @@ -62,15 +58,4 @@ public class SetBinder extends CollectionBinder { else LOG.orderByAttributeIgnored(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Attribute \"order-by\" ignored in JDK1.3 or less" ) - void orderByAttributeIgnored(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java index 96d426ce36..8cb3294cff 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.sql.Types; import java.util.Calendar; @@ -38,6 +37,7 @@ import javax.persistence.TemporalType; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.Hibernate; +import org.hibernate.Logger; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.hibernate.annotations.common.reflection.XClass; @@ -57,10 +57,6 @@ import org.hibernate.type.PrimitiveCharacterArrayClobType; import org.hibernate.type.SerializableToBlobType; import org.hibernate.type.WrappedMaterializedBlobType; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -303,7 +299,7 @@ public class SimpleValueBinder { public SimpleValue make() { validate(); - LOG.buildingSimpleValue(propertyName); + LOG.debug("building SimpleValue for " + propertyName); if ( table == null ) { table = columns[0].getTable(); } @@ -341,7 +337,7 @@ public class SimpleValueBinder { public void fillSimpleValue() { - LOG.settingSimpleValueTypeName(propertyName); + LOG.debug("Setting SimpleValue typeName for " + propertyName); String type = BinderHelper.isEmptyAnnotationValue( explicitType ) ? returnedClassName : explicitType; org.hibernate.mapping.TypeDef typeDef = mappings.getTypeDef( type ); @@ -371,19 +367,4 @@ public class SimpleValueBinder { public void setKey(boolean key) { this.key = key; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "building SimpleValue for %s" ) - void buildingSimpleValue( String propertyName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Setting SimpleValue typeName for %s" ) - void settingSimpleValueTypeName( String propertyName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java index 5e4ab1c7a4..8066d7020a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java @@ -23,13 +23,13 @@ */ package org.hibernate.cfg.annotations; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.UniqueConstraint; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; +import org.hibernate.Logger; import org.hibernate.annotations.Index; import org.hibernate.cfg.BinderHelper; import org.hibernate.cfg.Ejb3JoinColumn; @@ -51,10 +51,6 @@ import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.util.CollectionHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Table related operations @@ -343,7 +339,7 @@ public class TableBinder { * Get the columns of the mapped-by property * copy them and link the copy to the actual value */ - LOG.retreivingProperty(associatedClass.getEntityName(), mappedByProperty); + LOG.debug("Retrieving property " + associatedClass.getEntityName() + "." + mappedByProperty); final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() ); Iterator mappedByColumns; @@ -450,7 +446,7 @@ public class TableBinder { Iterator idColItr = referencedEntity.getKey().getColumnIterator(); org.hibernate.mapping.Column col; Table table = referencedEntity.getTable(); //works cause the pk has to be on the primary table - if (!idColItr.hasNext()) LOG.noColumnInIdentifier(); + if (!idColItr.hasNext()) LOG.debug("No column in the identifier!"); while ( idColItr.hasNext() ) { boolean match = false; //for each PK column, find the associated FK column. @@ -578,20 +574,4 @@ public class TableBinder { this.propertyName = propertyName; this.name = null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Retrieving property %s.%s" ) - void retreivingProperty( String entityName, - String propertyName ); - - @LogMessage( level = DEBUG ) - @Message( value = "No column in the identifier!" ) - void noColumnInIdentifier(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverridenAnnotationReader.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverridenAnnotationReader.java index 99a4c2d919..96cb6acf28 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverridenAnnotationReader.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverridenAnnotationReader.java @@ -24,7 +24,6 @@ package org.hibernate.cfg.annotations.reflection; -import static org.jboss.logging.Logger.Level.WARN; import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; @@ -119,6 +118,7 @@ import javax.persistence.Version; import org.dom4j.Attribute; import org.dom4j.Element; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CollectionOfElements; import org.hibernate.annotations.Columns; @@ -129,10 +129,6 @@ import org.hibernate.annotations.common.reflection.Filter; import org.hibernate.annotations.common.reflection.ReflectionUtil; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Encapsulates the overriding of Java annotations from an EJB 3.0 descriptor. @@ -2504,15 +2500,4 @@ public class JPAOverridenAnnotationReader implements AnnotationReader { private Annotation[] getJavaAnnotations() { return element.getAnnotations(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Property %s not found in class but described in (possible typo error)" ) - void propertyNotFound( String property ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java index 3bc571d7e4..ff897de9cf 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java @@ -26,9 +26,6 @@ package org.hibernate.cfg.annotations.reflection; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; @@ -38,11 +35,8 @@ import javax.persistence.AccessType; import org.dom4j.Document; import org.dom4j.Element; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -159,7 +153,7 @@ public class XMLContext implements Serializable { setAccess( access, localDefault ); defaultsOverriding.put( className, localDefault ); - LOG.addingOverridingInformation(className); + LOG.debug("Adding XML overriding information for " + className); addEntityListenerClasses( element, packageName, addedClasses ); } } @@ -186,7 +180,7 @@ public class XMLContext implements Serializable { classOverriding.put( listenerClassName, listener ); } } - LOG.addingListenerOverridingInformation(localAddedClasses); + LOG.debug("Adding XML overriding information for listeners: " + localAddedClasses); addedClasses.addAll( localAddedClasses ); return localAddedClasses; } @@ -312,27 +306,4 @@ public class XMLContext implements Serializable { public List getDefaultEntityListeners() { return defaultEntityListeners; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Adding XML overriding information for %s" ) - void addingOverridingInformation( String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "Adding XML overriding information for listeners: %s" ) - void addingListenerOverridingInformation( List classNames ); - - @LogMessage( level = INFO ) - @Message( value = "entity-listener duplication, first event definition will be used: %s" ) - void duplicateListener( String className ); - - @LogMessage( level = WARN ) - @Message( value = "Found more than one , subsequent ignored" ) - void duplicateMetadata(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java index 0e1ec5459d..ca462f57ff 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg.beanvalidation; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.HashSet; import java.util.Properties; import java.util.Set; @@ -35,6 +34,7 @@ import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.hibernate.EntityMode; +import org.hibernate.Logger; import org.hibernate.cfg.Configuration; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.event.Initializable; @@ -45,10 +45,6 @@ import org.hibernate.event.PreInsertEventListener; import org.hibernate.event.PreUpdateEvent; import org.hibernate.event.PreUpdateEventListener; import org.hibernate.persister.entity.EntityPersister; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Event listener used to enable Bean Validation for insert/update/delete events. @@ -142,7 +138,7 @@ public class BeanValidationEventListener implements new HashSet>( constraintViolations.size() ); Set classNames = new HashSet(); for ( ConstraintViolation violation : constraintViolations ) { - LOG.violation(violation); + LOG.trace(violation); propagatedViolations.add( violation ); classNames.add( violation.getLeafBean().getClass().getName() ); } @@ -174,15 +170,4 @@ public class BeanValidationEventListener implements toString.append( "]" ); return toString.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "%s" ) - void violation( ConstraintViolation violation ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java index e487330c9c..7ec2e81187 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java @@ -23,7 +23,6 @@ */ package org.hibernate.cfg.beanvalidation; -import static org.jboss.logging.Logger.Level.WARN; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -57,10 +56,6 @@ import org.hibernate.mapping.Property; import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -387,16 +382,4 @@ class TypeSafeActivator { } return factory; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Unable to apply constraints on DDL for %s\n%s" ) - void unableToApplyConstraints( String className, - String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java b/hibernate-core/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java index 077a8e74b8..5ff0ee89d1 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java @@ -23,10 +23,9 @@ */ package org.hibernate.cfg.search; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; import java.util.Properties; import org.hibernate.AnnotationException; +import org.hibernate.Logger; import org.hibernate.event.EventListeners; import org.hibernate.event.PostCollectionRecreateEventListener; import org.hibernate.event.PostCollectionRemoveEventListener; @@ -35,10 +34,6 @@ import org.hibernate.event.PostDeleteEventListener; import org.hibernate.event.PostInsertEventListener; import org.hibernate.event.PostUpdateEventListener; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Helper methods initializing Hibernate Search event listeners. @@ -231,7 +226,7 @@ public class HibernateSearchEventListenerRegister { FULL_TEXT_INDEX_EVENT_LISTENER_CLASS, HibernateSearchEventListenerRegister.class); } catch (ClassNotFoundException e) { - LOG.unableToFindListenerClass(); + LOG.debug("Search not present in classpath, ignoring event listener registration."); } return searchEventListenerClass; } @@ -246,23 +241,4 @@ public class HibernateSearchEventListenerRegister { } return searchEventListener; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Property hibernate.search.autoregister_listeners is set to false. No attempt will be made to register Hibernate Search event listeners." ) - void willNotRegisterListeners(); - - @LogMessage( level = INFO ) - @Message( value = "Unable to find %s on the classpath. Hibernate Search is not enabled." ) - void unableToFindListenerClass( String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "Search not present in classpath, ignoring event listener registration." ) - void unableToFindListenerClass(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java index e4e4c95cf1..dda1ceec8b 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java @@ -24,7 +24,6 @@ */ package org.hibernate.collection; -import static org.jboss.logging.Logger.Level.ERROR; import java.io.Serializable; import java.lang.reflect.Array; import java.sql.ResultSet; @@ -34,14 +33,11 @@ import java.util.Collection; import java.util.Iterator; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionImplementor; import org.hibernate.loader.CollectionAliases; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A persistent wrapper for an array. Lazy initialization @@ -257,15 +253,4 @@ public class PersistentArrayHolder extends AbstractPersistentCollection { public boolean entryExists(Object entry, int i) { return entry!=null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = ERROR ) - @Message( value = "Array element type error\n%s" ) - void invalidArrayElementType( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java index effe462cf4..6bf65c6f88 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java @@ -24,7 +24,6 @@ */ package org.hibernate.context; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.Hashtable; import java.util.Map; import javax.transaction.Synchronization; @@ -32,13 +31,10 @@ import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.classic.Session; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.JTAHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An implementation of {@link CurrentSessionContext} which scopes the notion @@ -121,7 +117,7 @@ public class JTASessionContext implements CurrentSessionContext { currentSession.close(); } catch ( Throwable ignore ) { - LOG.unableToReleaseSession(ignore.getMessage()); + LOG.debug("Unable to release generated current-session on failed synch registration", ignore); } throw new HibernateException( "Unable to register cleanup Synchronization with TransactionManager" ); } @@ -212,15 +208,4 @@ public class JTASessionContext implements CurrentSessionContext { context.currentSessionMap.remove( transactionIdentifier ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to release generated current-session on failed synch registration\n%s" ) - void unableToReleaseSession( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java index f5d707627f..bc9d8f7883 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java @@ -24,9 +24,6 @@ */ package org.hibernate.context; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -40,13 +37,10 @@ import java.util.Map; import javax.transaction.Synchronization; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.hibernate.engine.SessionFactoryImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A {@link CurrentSessionContext} impl which scopes the notion of current @@ -216,13 +210,13 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { orphan.getTransaction().rollback(); } catch( Throwable t ) { - LOG.unableToRollbackTransaction(t.getMessage()); + LOG.debug("Unable to rollback transaction for orphaned session", t); } } orphan.close(); } catch( Throwable t ) { - LOG.unableToCloseOrphanedSession(t.getMessage()); + LOG.debug("Unable to close orphaned session", t); } } } @@ -238,12 +232,8 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { private static Session existingSession(SessionFactory factory) { Map sessionMap = sessionMap(); - if ( sessionMap == null ) { - return null; - } - else { - return ( Session ) sessionMap.get( factory ); - } + if (sessionMap == null) return null; + return (Session)sessionMap.get(factory); } protected static Map sessionMap() { @@ -335,7 +325,7 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { || "isTransactionInProgress".equals( method.getName() ) || "setFlushMode".equals( method.getName() ) || "getSessionFactory".equals( method.getName() ) ) { - LOG.allowingMethodInNonTransactedContext(method.getName()); + LOG.trace("Allowing method [" + method.getName() + "] in non-transacted context"); } else if ( "reconnect".equals( method.getName() ) || "disconnect".equals( method.getName() ) ) { @@ -345,16 +335,12 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { throw new HibernateException( method.getName() + " is not valid without active transaction" ); } } - LOG.allowingProxiedMethodInSession(method.getName()); + LOG.trace("Allowing proxied method [" + method.getName() + "] to proceed to real session"); return method.invoke( realSession, args ); } catch ( InvocationTargetException e ) { - if ( e.getTargetException() instanceof RuntimeException ) { - throw ( RuntimeException ) e.getTargetException(); - } - else { - throw e; - } + if (e.getTargetException() instanceof RuntimeException) throw (RuntimeException)e.getTargetException(); + throw e; } } @@ -389,31 +375,4 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { doBind( wrappedSession, factory ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Allowing method [%s] in non-transacted context" ) - void allowingMethodInNonTransactedContext( String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Allowing proxied method [%s] to proceed to real session" ) - void allowingProxiedMethodInSession( String name ); - - @LogMessage( level = WARN ) - @Message( value = "Already session bound on call to bind(); make sure you clean up your sessions!" ) - void alreadySessionBound(); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to close orphaned session\n%s" ) - void unableToCloseOrphanedSession( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to rollback transaction for orphaned session\n%s" ) - void unableToRollbackTransaction( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java index 0f46568096..5876ef5635 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java @@ -23,18 +23,14 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.Method; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.dialect.function.AnsiTrimFunction; import org.hibernate.dialect.function.DerbyConcatFunction; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DerbyCaseFragment; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Hibernate Dialect for Cloudscape 10 - aka Derby. This implements both an @@ -238,15 +234,4 @@ public String getForUpdateString() { public boolean supportsLobValueChangePropogation() { return false; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Unable to load/access derby driver class sysinfo to check versions : %s" ) - void unableToLoadDerbyDriver( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java index 627defd6ce..8255b14900 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -23,7 +23,6 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.INFO; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -36,6 +35,7 @@ import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.CastFunction; @@ -66,10 +66,6 @@ import org.hibernate.sql.JoinFragment; import org.hibernate.type.StandardBasicTypes; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Represents a dialect of SQL implemented by a particular RDBMS. @@ -1930,22 +1926,11 @@ public abstract class Dialect { /** * Does this dialect support `count(distinct a,b)`? - * + * * @return True if the database supports counting distinct tuples; false otherwise. */ public boolean supportsTupleDistinctCounts() { // oddly most database in fact seem to, so true is the default. return true; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Using dialect: %s" ) - void usingDialect( Dialect dialect ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java index af21029165..f10df9885e 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java @@ -23,9 +23,9 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.SQLException; import java.sql.Types; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.AvgWithArgumentCastFunction; import org.hibernate.dialect.function.NoArgSQLFunction; @@ -35,10 +35,6 @@ import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.ViolatedConstraintNameExtracter; import org.hibernate.type.StandardBasicTypes; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A dialect compatible with the H2 database. @@ -345,17 +341,4 @@ public class H2Dialect extends Dialect { // see http://groups.google.com/group/h2-database/browse_thread/thread/562d8a49e2dabe99?hl=en return true; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "The %d.%d.%d version of H2 implements temporary table creation such that it commits current transaction; multi-table, bulk hql/jpaql will not work properly" ) - void unsupportedMultiTableBulkHqlJpaql( int majorVersion, - int minorVersion, - int buildId ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java index d57e9a53a6..258735e543 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java @@ -23,12 +23,12 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.sql.SQLException; import java.sql.Types; import org.hibernate.JDBCException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.StaleObjectStateException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.AvgWithArgumentCastFunction; @@ -50,10 +50,6 @@ import org.hibernate.exception.ViolatedConstraintNameExtracter; import org.hibernate.persister.entity.Lockable; import org.hibernate.type.StandardBasicTypes; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An SQL dialect compatible with HSQLDB (HyperSQL). @@ -666,15 +662,4 @@ public class HSQLDialect extends Dialect { public boolean supportsTupleDistinctCounts() { return false; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "HSQLDB supports only READ_UNCOMMITTED isolation" ) - void hsqldbSupportsOnlyReadCommittedIsolation(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java index cde2ec3459..c809e5f726 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java @@ -23,12 +23,12 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.NvlFunction; @@ -40,10 +40,6 @@ import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.ViolatedConstraintNameExtracter; import org.hibernate.type.StandardBasicTypes; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An SQL dialect for Oracle 9 (uses ANSI-style syntax where possible). @@ -372,15 +368,4 @@ public class Oracle9Dialect extends Dialect { public boolean supportsExistsInSelect() { return false; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead" ) - void deprecatedOracle9Dialect(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java index 830c7e1ff3..36f07bed1c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java @@ -23,16 +23,12 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.Types; +import org.hibernate.Logger; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.sql.JoinFragment; import org.hibernate.sql.OracleJoinFragment; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An SQL dialect for Oracle, compatible with Oracle 8. @@ -121,15 +117,4 @@ public class OracleDialect extends Oracle9Dialect { public String getCurrentTimestampSQLFunctionName() { return "sysdate"; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "The OracleDialect dialect has been deprecated; use Oracle8iDialect instead" ) - void deprecatedOracleDialect(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java index 17af1c83e2..9948938573 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java @@ -23,9 +23,9 @@ */ package org.hibernate.dialect; -import static org.jboss.logging.Logger.Level.INFO; import java.sql.Types; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; @@ -41,10 +41,6 @@ import org.hibernate.persister.entity.Lockable; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.type.StandardBasicTypes; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * This is the Hibernate dialect for the Unisys 2200 Relational Database (RDMS). @@ -365,15 +361,4 @@ public class RDMSOS2200Dialect extends Dialect { return new SelectLockingStrategy( lockable, lockMode ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "RDMSOS2200Dialect version: 1.0" ) - void rdmsOs2200Dialect(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java index 74b8ab74cf..7859daf5e2 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java @@ -23,14 +23,10 @@ */ package org.hibernate.dialect.function; -import static org.jboss.logging.Logger.Level.WARN; import java.util.ArrayList; import java.util.List; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Delegate for handling function "templates". @@ -119,16 +115,4 @@ public class TemplateRenderer { } return buf.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Function template anticipated %d arguments, but %d arguments encountered" ) - void missingArguments( int anticipatedNumberOfArguments, - int numberOfArguments ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/Logger.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/Logger.java deleted file mode 100644 index 8763f1b2e4..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/Logger.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.dialect.lock; - -import static org.jboss.logging.Logger.Level.WARN; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Write locks via update not supported for non-versioned entities [%s]" ) - void writeLocksNotSupported( String entityName ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java index e561813cfa..478cca5f60 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java @@ -29,6 +29,7 @@ import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.PessimisticLockException; import org.hibernate.StaleObjectStateException; import org.hibernate.engine.SessionFactoryImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java index 21643b5981..66de468dc9 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java @@ -29,6 +29,7 @@ import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.PessimisticLockException; import org.hibernate.StaleObjectStateException; import org.hibernate.engine.SessionFactoryImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java index edb891751b..33ca712fc8 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java @@ -29,6 +29,7 @@ import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.StaleObjectStateException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/AbstractDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/AbstractDialectResolver.java index 63a0256742..126be42612 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/AbstractDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/AbstractDialectResolver.java @@ -23,17 +23,13 @@ */ package org.hibernate.dialect.resolver; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.hibernate.JDBCException; import org.hibernate.cfg.CollectionSecondPass; import org.hibernate.dialect.Dialect; import org.hibernate.exception.JDBCConnectionException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.service.jdbc.dialect.spi.DialectResolver; /** * A templated resolver impl which delegates to the {@link #resolveDialectInternal} method @@ -76,21 +72,4 @@ public abstract class AbstractDialectResolver implements DialectResolver { * @throws SQLException Indicates problems accessing the metadata. */ protected abstract Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException; - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Error executing resolver [%s] : %s" ) - void unableToExecuteResolver( AbstractDialectResolver abstractDialectResolver, - String message ); - - @LogMessage( level = WARN ) - @Message( value = "%s : %s" ) - void unableToQueryDatabaseMetadata( String message, - String errorMessage ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java index fda82438dc..e46a864d5a 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java @@ -25,11 +25,9 @@ package org.hibernate.dialect.resolver; import java.sql.SQLException; import org.hibernate.JDBCException; +import org.hibernate.Logger; import org.hibernate.exception.SQLStateConverter; import org.hibernate.exception.ViolatedConstraintNameExtracter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A helper to centralize conversion of {@link java.sql.SQLException}s to {@link org.hibernate.JDBCException}s. @@ -63,14 +61,4 @@ public class BasicSQLExceptionConverter { return "???"; } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Unable to query java.sql.DatabaseMetaData" ) - String unableToQueryDatabaseMetadata(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectFactory.java b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectFactory.java index 7facff6dd3..d0be9c4b16 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectFactory.java @@ -23,19 +23,15 @@ */ package org.hibernate.dialect.resolver; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A factory for generating Dialect instances. @@ -163,19 +159,4 @@ public class DialectFactory { throw new HibernateException( "Could not instantiate dialect class", e ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Dialect resolver class not found: %s" ) - void dialectResolverNotFound( String resolverName ); - - @LogMessage( level = WARN ) - @Message( value = "Could not instantiate dialect resolver class : %s" ) - void unableToInstantiateDialectResolver( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectResolverSet.java index 2e872f9363..24b9a96e0b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectResolverSet.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectResolverSet.java @@ -23,7 +23,6 @@ */ package org.hibernate.dialect.resolver; -import static org.jboss.logging.Logger.Level.INFO; import java.sql.DatabaseMetaData; import java.util.ArrayList; import java.util.Iterator; @@ -31,10 +30,7 @@ import java.util.List; import org.hibernate.cfg.CollectionSecondPass; import org.hibernate.dialect.Dialect; import org.hibernate.exception.JDBCConnectionException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.service.jdbc.dialect.spi.DialectResolver; /** * A {@link DialectResolver} implementation which coordinates resolution by delegating to its @@ -92,15 +88,4 @@ public class DialectResolverSet implements DialectResolver { public void addResolverAtFirst(DialectResolver resolver) { resolvers.add( 0, resolver ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "sub-resolver threw unexpected exception, continuing to next : %s" ) - void subResolverException( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/StandardDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/StandardDialectResolver.java index b7fd38d74d..a90a4c8c71 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/StandardDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/StandardDialectResolver.java @@ -23,9 +23,9 @@ */ package org.hibernate.dialect.resolver; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.DatabaseMetaData; import java.sql.SQLException; +import org.hibernate.Logger; import org.hibernate.dialect.DB2Dialect; import org.hibernate.dialect.DerbyDialect; import org.hibernate.dialect.Dialect; @@ -43,10 +43,6 @@ import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseAnywhereDialect; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * The standard Hibernate resolver. @@ -138,27 +134,4 @@ public class StandardDialectResolver extends AbstractDialectResolver{ return null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Unknown Ingres major version [%s]; using Ingres 9.2 dialect" ) - void unknownIngresVersion( int databaseMajorVersion ); - - @LogMessage( level = WARN ) - @Message( value = "Unknown Oracle major version [%s]" ) - void unknownOracleVersion( int databaseMajorVersion ); - - @LogMessage( level = WARN ) - @Message( value = "Ingres 10 is not yet fully supported; using Ingres 9.3 dialect" ) - void unsupportedIngresVersion(); - - @LogMessage( level = WARN ) - @Message( value = "Oracle 11g is not yet fully supported; using Oracle 10g dialect" ) - void unsupportedOracleVersion(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java b/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java index 44c82b7168..be9e9ba7da 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java @@ -23,9 +23,6 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -38,6 +35,7 @@ import java.util.List; import java.util.Set; import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.action.AfterTransactionCompletionProcess; import org.hibernate.action.BeforeTransactionCompletionProcess; import org.hibernate.action.BulkOperationCleanupAction; @@ -51,10 +49,6 @@ import org.hibernate.action.EntityUpdateAction; import org.hibernate.action.Executable; import org.hibernate.cache.CacheException; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Responsible for maintaining the queue of actions related to events. @@ -253,7 +247,7 @@ public class ActionQueue { final Serializable[] spaces = action.getPropertySpaces(); for ( Serializable space : spaces ) { if ( tableSpaces.contains( space ) ) { - LOG.changesMustBeFlushed(space); + LOG.debug("Changes must be flushed to space: " + space); return true; } } @@ -415,45 +409,45 @@ public class ActionQueue { * @throws IOException Indicates an error writing to the stream */ public void serialize(ObjectOutputStream oos) throws IOException { - LOG.serializingActionQueue(); + LOG.trace("Serializing action-queue"); int queueSize = insertions.size(); - LOG.serializingInsertions(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] insertions entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( insertions.get( i ) ); } queueSize = deletions.size(); - LOG.serializingDeletions(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] deletions entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( deletions.get( i ) ); } queueSize = updates.size(); - LOG.serializingUpdates(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] updates entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( updates.get( i ) ); } queueSize = collectionUpdates.size(); - LOG.serializingCollectionUpdates(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] collectionUpdates entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionUpdates.get( i ) ); } queueSize = collectionRemovals.size(); - LOG.serializingCollectionRemovals(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] collectionRemovals entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionRemovals.get( i ) ); } queueSize = collectionCreations.size(); - LOG.serializingCollectionCreations(queueSize); + LOG.trace("Starting serialization of [" + queueSize + "] collectionCreations entries"); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionCreations.get( i ) ); @@ -476,46 +470,46 @@ public class ActionQueue { public static ActionQueue deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { - LOG.deserializingActionQueue(); + LOG.trace("Dedeserializing action-queue"); ActionQueue rtn = new ActionQueue( session ); int queueSize = ois.readInt(); - LOG.deserializingInsertions(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] insertions entries"); rtn.insertions = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.insertions.add( ois.readObject() ); } queueSize = ois.readInt(); - LOG.deserializingDeletions(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] deletions entries"); rtn.deletions = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.deletions.add( ois.readObject() ); } queueSize = ois.readInt(); - LOG.deserializingUpdates(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] updates entries"); rtn.updates = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.updates.add( ois.readObject() ); } queueSize = ois.readInt(); - LOG.deserializingCollectionUpdates(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] collectionUpdates entries"); rtn.collectionUpdates = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionUpdates.add( ois.readObject() ); } queueSize = ois.readInt(); - LOG.deserializingCollectionRemovals(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] collectionRemovals entries"); rtn.collectionRemovals = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionRemovals.add( ois.readObject() ); } queueSize = ois.readInt(); - LOG.deserializingCollectionCreations(queueSize); + LOG.trace("Starting deserialization of [" + queueSize + "] collectionCreations entries"); rtn.collectionCreations = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionCreations.add( ois.readObject() ); @@ -732,75 +726,4 @@ public class ActionQueue { } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Changes must be flushed to space: %s" ) - void changesMustBeFlushed( Serializable space ); - - @LogMessage( level = ERROR ) - @Message( value = "Could not release a cache lock : %s" ) - void unableToReleaseCacheLock( CacheException ce ); - - @LogMessage( level = TRACE ) - @Message( value = "Dedeserializing action-queue" ) - void deserializingActionQueue(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] collectionCreations entries" ) - void deserializingCollectionCreations( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] collectionRemovals entries" ) - void deserializingCollectionRemovals( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] collectionUpdates entries" ) - void deserializingCollectionUpdates( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] deletions entries" ) - void deserializingDeletions( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] insertions entries" ) - void deserializingInsertions( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] updates entries" ) - void deserializingUpdates( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Serializing action-queue" ) - void serializingActionQueue(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] collectionCreations entries" ) - void serializingCollectionCreations( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] collectionRemovals entries" ) - void serializingCollectionRemovals( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] collectionUpdates entries" ) - void serializingCollectionUpdates( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] deletions entries" ) - void serializingDeletions( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] insertions entries" ) - void serializingInsertions( int queueSize ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] updates entries" ) - void serializingUpdates( int queueSize ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java b/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java index 51015a316d..c210cae66b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java @@ -23,7 +23,6 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; @@ -31,6 +30,7 @@ import java.util.Iterator; import java.util.Stack; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.collection.PersistentCollection; import org.hibernate.event.EventSource; import org.hibernate.persister.collection.CollectionPersister; @@ -42,10 +42,6 @@ import org.hibernate.type.CompositeType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.util.CollectionHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Delegate responsible for, in conjunction with the various @@ -142,7 +138,7 @@ public final class Cascade { throws HibernateException { if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { // performance opt - LOG.processingCascade(action, persister.getEntityName()); + LOG.trace("Processing cascade " + action + " for: " + persister.getEntityName()); Type[] types = persister.getPropertyTypes(); CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles(); @@ -178,7 +174,7 @@ public final class Cascade { } } - LOG.processingCascadeEnded(action, persister.getEntityName()); + LOG.trace("Done processing cascade " + action + " for: " + persister.getEntityName()); } } @@ -250,7 +246,7 @@ public final class Cascade { if (LOG.isTraceEnabled()) { final Serializable id = entry.getPersister().getIdentifier( loadedValue, eventSource ); final String description = MessageHelper.infoString( entityName, id ); - LOG.deletingOrphanedEntity(description); + LOG.trace("Deleting orphaned entity instance: " + description); } eventSource.delete( entityName, loadedValue, false, new HashSet() ); } @@ -413,7 +409,7 @@ public final class Cascade { embeddedElements && child!=CollectionType.UNFETCHED_COLLECTION; if ( reallyDoCascade ) { - LOG.cascadeActionForCollection(action, collectionType.getRole()); + LOG.trace("Cascade " + action + " for collection: " + collectionType.getRole()); Iterator iter = action.getCascadableChildrenIterator(eventSource, collectionType, child); while ( iter.hasNext() ) { @@ -428,7 +424,7 @@ public final class Cascade { ); } - LOG.cascadeActionForColectionEnded(action, collectionType.getRole()); + LOG.trace("Done cascade " + action + " for collection: " + collectionType.getRole()); } final boolean deleteOrphans = style.hasOrphanDelete() && @@ -437,7 +433,7 @@ public final class Cascade { child instanceof PersistentCollection; //a newly instantiated collection can't have orphans if ( deleteOrphans ) { // handle orphaned entities!! - LOG.deletingOrphansForCollection(collectionType.getRole()); + LOG.trace("Deleting orphans for collection: " + collectionType.getRole()); // we can do the cast since orphan-delete does not apply to: // 1. newly instantiated collections @@ -445,7 +441,7 @@ public final class Cascade { final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() ); deleteOrphans( entityName, (PersistentCollection) child ); - LOG.deletingOrphansForCollectionEnded(collectionType.getRole()); + LOG.trace("Done deleting orphans for collection: " + collectionType.getRole()); } } @@ -469,48 +465,9 @@ public final class Cascade { while ( orphanIter.hasNext() ) { Object orphan = orphanIter.next(); if (orphan!=null) { - LOG.deletingOrphanedEntity(entityName); + LOG.trace("Deleting orphaned entity instance: " + entityName); eventSource.delete( entityName, orphan, false, new HashSet() ); } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Cascade %s for collection: %s" ) - void cascadeActionForCollection( CascadingAction action, - String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Done cascade %s for collection: %s" ) - void cascadeActionForColectionEnded( CascadingAction action, - String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Deleting orphaned entity instance: %s" ) - void deletingOrphanedEntity( String description ); - - @LogMessage( level = TRACE ) - @Message( value = "Deleting orphans for collection: %s" ) - void deletingOrphansForCollection( String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Done deleting orphans for collection: %s" ) - void deletingOrphansForCollectionEnded( String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Processing cascade %s for: %s" ) - void processingCascade( CascadingAction action, - String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Done processing cascade %s for: %s" ) - void processingCascadeEnded( CascadingAction action, - String entityName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java b/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java index 4989b8b3c9..c71ed3ef84 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java @@ -24,13 +24,13 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.ReplicationMode; import org.hibernate.TransientObjectException; import org.hibernate.collection.PersistentCollection; @@ -40,10 +40,6 @@ import org.hibernate.proxy.HibernateProxy; import org.hibernate.type.CollectionType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A session action that may be cascaded from parent entity to its children @@ -143,7 +139,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToDelete(entityName); + LOG.trace("Cascading to delete: " + entityName); session.delete( entityName, child, isCascadeDeleteEnabled, ( Set ) anything ); } @Override @@ -169,7 +165,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToLock(entityName); + LOG.trace("Cascading to lock: " + entityName); LockMode lockMode = LockMode.NONE; LockOptions lr = new LockOptions(); if ( anything instanceof LockOptions) { @@ -205,7 +201,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToRefresh(entityName); + LOG.trace("Cascading to refresh: " + entityName); session.refresh( child, (Map) anything ); } @Override @@ -230,7 +226,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToEvict(entityName); + LOG.trace("Cascading to evict: " + entityName); session.evict(child); } @Override @@ -259,7 +255,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToSaveOrUpdate(entityName); + LOG.trace("Cascading to save or update: " + entityName); session.saveOrUpdate(entityName, child); } @Override @@ -289,7 +285,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToMerge(entityName); + LOG.trace("Cascading to merge: " + entityName); session.merge( entityName, child, (Map) anything ); } @Override @@ -317,7 +313,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToSaveOrUpdateCopy(entityName); + LOG.trace("Cascading to save or update copy: " + entityName); session.saveOrUpdateCopy( entityName, child, (Map) anything ); } @Override @@ -343,7 +339,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToPersist(entityName); + LOG.trace("Cascading to persist: " + entityName); session.persist( entityName, child, (Map) anything ); } @Override @@ -374,7 +370,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToPersistOnFlush(entityName); + LOG.trace("Cascading to persist on flush: " + entityName); session.persistOnFlush( entityName, child, (Map) anything ); } @Override @@ -441,7 +437,7 @@ public abstract class CascadingAction { @Override public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - LOG.cascadingToReplicate(entityName); + LOG.trace("Cascading to replicate: " + entityName); session.replicate( entityName, child, (ReplicationMode) anything ); } @Override @@ -497,51 +493,4 @@ public abstract class CascadingAction { private static boolean collectionIsInitialized(Object collection) { return !(collection instanceof PersistentCollection) || ( (PersistentCollection) collection ).wasInitialized(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to delete: %s" ) - void cascadingToDelete( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to evict: %s" ) - void cascadingToEvict( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to lock: %s" ) - void cascadingToLock( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to merge: %s" ) - void cascadingToMerge( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to persist: %s" ) - void cascadingToPersist( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to persist on flush: %s" ) - void cascadingToPersistOnFlush( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to refresh: %s" ) - void cascadingToRefresh( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to replicate: %s" ) - void cascadingToReplicate( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to save or update: %s" ) - void cascadingToSaveOrUpdate( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Cascading to save or update copy: %s" ) - void cascadingToSaveOrUpdateCopy( String entityName ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java b/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java index 251fca577b..bdf9f43001 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java @@ -24,7 +24,6 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -32,14 +31,11 @@ import java.io.Serializable; import java.util.Collection; import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.collection.PersistentCollection; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * We need an entry to tell us all about the current state @@ -199,8 +195,9 @@ public final class CollectionEntry implements Serializable { dirty(collection); - if (LOG.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null) LOG.collectionDirty(MessageHelper.collectionInfoString(getLoadedPersister().getRole(), - getLoadedKey())); + if (LOG.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null) LOG.debug("Collection dirty: " + + MessageHelper.collectionInfoString(getLoadedPersister().getRole(), + getLoadedKey())); setDoupdate(false); setDoremove(false); @@ -417,15 +414,4 @@ public final class CollectionEntry implements Serializable { ( session == null ? null : session.getFactory() ) ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Collection dirty: %s" ) - void collectionDirty( String collectionInfoString ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/Collections.java b/hibernate-core/src/main/java/org/hibernate/engine/Collections.java index 1442b07f25..41b8741e8e 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/Collections.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Collections.java @@ -24,20 +24,15 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.collection.PersistentCollection; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.CollectionType; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Implements book-keeping for the collection persistence by reachability algorithm @@ -75,9 +70,10 @@ public final class Collections { CollectionEntry entry = persistenceContext.getCollectionEntry(coll); final CollectionPersister loadedPersister = entry.getLoadedPersister(); - if (LOG.isDebugEnabled() && loadedPersister != null) LOG.collectionDereferenced(MessageHelper.collectionInfoString(loadedPersister, - entry.getLoadedKey(), - session.getFactory())); + if (LOG.isDebugEnabled() && loadedPersister != null) LOG.debug("Collection dereferenced: " + + MessageHelper.collectionInfoString(loadedPersister, + entry.getLoadedKey(), + session.getFactory())); // do a check boolean hasOrphanDelete = loadedPersister != null && @@ -133,9 +129,8 @@ public final class Collections { final PersistenceContext persistenceContext = session.getPersistenceContext(); CollectionEntry entry = persistenceContext.getCollectionEntry(coll); - LOG.foundCollectionWithUnloadedOwner(MessageHelper.collectionInfoString(entry.getLoadedPersister(), - entry.getLoadedKey(), - session.getFactory())); + LOG.debug("Found collection with unloaded owner: " + + MessageHelper.collectionInfoString(entry.getLoadedPersister(), entry.getLoadedKey(), session.getFactory())); entry.setCurrentPersister( entry.getLoadedPersister() ); entry.setCurrentKey( entry.getLoadedKey() ); @@ -146,7 +141,7 @@ public final class Collections { /** * Initialize the role of the collection. - * + * * @param collection The collection to be updated by reachability. * @param type The type of the collection. * @param entity The owner of the collection. @@ -188,16 +183,15 @@ public final class Collections { ce.setCurrentKey( type.getKeyOfOwner(entity, session) ); //TODO: better to pass the id in as an argument? if (LOG.isDebugEnabled()) { - if (collection.wasInitialized()) LOG.collectionFound(MessageHelper.collectionInfoString(persister, - ce.getCurrentKey(), - factory), - MessageHelper.collectionInfoString(ce.getLoadedPersister(), - ce.getLoadedKey(), - factory), - LOG.initialized()); - else LOG.collectionFound(MessageHelper.collectionInfoString(persister, ce.getCurrentKey(), factory), - MessageHelper.collectionInfoString(ce.getLoadedPersister(), ce.getLoadedKey(), factory), - LOG.uninitialized()); + if (collection.wasInitialized()) LOG.debug("Collection found: " + + MessageHelper.collectionInfoString(persister, ce.getCurrentKey(), factory) + + ", was: " + + MessageHelper.collectionInfoString(ce.getLoadedPersister(), + ce.getLoadedKey(), + factory) + " (initialized)"); + else LOG.debug("Collection found: " + MessageHelper.collectionInfoString(persister, ce.getCurrentKey(), factory) + + ", was: " + MessageHelper.collectionInfoString(ce.getLoadedPersister(), ce.getLoadedKey(), factory) + + " (uninitialized)"); } prepareCollectionForUpdate( collection, ce, session.getEntityMode(), factory ); @@ -255,7 +249,7 @@ public final class Collections { if ( loadedPersister != null ) { entry.setDoremove(true); // we will need to remove ye olde entries if ( entry.isDorecreate() ) { - LOG.forcingCollectionInitialization(); + LOG.trace("Forcing collection initialization"); collection.forceInitialization(); // force initialize! } } @@ -268,35 +262,4 @@ public final class Collections { } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Collection dereferenced: %s" ) - void collectionDereferenced( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Collection found: %s, was: %s (%s)" ) - void collectionFound( String collectionInfoString, - String collectionInfoString2, - String initialized ); - - @LogMessage( level = TRACE ) - @Message( value = "Forcing collection initialization" ) - void forcingCollectionInitialization(); - - @LogMessage( level = DEBUG ) - @Message( value = "Found collection with unloaded owner: %s" ) - void foundCollectionWithUnloadedOwner( String collectionInfoString ); - - @Message( value = "initialized" ) - String initialized(); - - @Message( value = "uninitialized" ) - String uninitialized(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java b/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java index d006b6c3e8..c35ebf3dcd 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java @@ -24,12 +24,8 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * A strategy for determining if an identifier value is an identifier of @@ -52,7 +48,7 @@ public class IdentifierValue { public static final IdentifierValue ANY = new IdentifierValue() { @Override public final Boolean isUnsaved(Serializable id) { - LOG.idUnsavedValueStrategy("ANY"); + LOG.trace("ID unsaved-value strategy ANY"); return Boolean.TRUE; } @Override @@ -71,7 +67,7 @@ public class IdentifierValue { public static final IdentifierValue NONE = new IdentifierValue() { @Override public final Boolean isUnsaved(Serializable id) { - LOG.idUnsavedValueStrategy("NONE"); + LOG.trace("ID unsaved-value strategy NONE"); return Boolean.FALSE; } @Override @@ -91,7 +87,7 @@ public class IdentifierValue { public static final IdentifierValue NULL = new IdentifierValue() { @Override public final Boolean isUnsaved(Serializable id) { - LOG.idUnsavedValueStrategy("NULL"); + LOG.trace("ID unsaved-value strategy NULL"); return id==null ? Boolean.TRUE : Boolean.FALSE; } @Override @@ -110,7 +106,7 @@ public class IdentifierValue { public static final IdentifierValue UNDEFINED = new IdentifierValue() { @Override public final Boolean isUnsaved(Serializable id) { - LOG.idUnsavedValueStrategy("UNDEFINED"); + LOG.trace("ID unsaved-value strategy UNDEFINED"); return null; } @Override @@ -139,7 +135,7 @@ public class IdentifierValue { * Does the given identifier belong to a new instance? */ public Boolean isUnsaved(Serializable id) { - LOG.idUnsavedValue(value); + LOG.trace("ID unsaved-value: " + value); return id==null || id.equals(value) ? Boolean.TRUE : Boolean.FALSE; } @@ -151,19 +147,4 @@ public class IdentifierValue { public String toString() { return "identifier unsaved-value: " + value; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "ID unsaved-value: %s" ) - void idUnsavedValue( Serializable value ); - - @LogMessage( level = TRACE ) - @Message( value = "ID unsaved-value strategy %s" ) - void idUnsavedValueStrategy( String name ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java b/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java index 5970c748f1..9dc232b836 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java @@ -24,17 +24,13 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Centralizes the commonality regarding binding of parameter values into @@ -122,7 +118,7 @@ public class ParameterBinder { TypedValue typedval = ( TypedValue ) e.getValue(); int[] locations = source.getNamedParameterLocations( name ); for ( int i = 0; i < locations.length; i++ ) { - LOG.bindNamedParameters(typedval.getValue(), name, locations[i] + start); + LOG.debug("bindNamedParameters() " + typedval.getValue() + " -> " + name + " [" + (locations[i] + start) + "]"); typedval.getType().nullSafeSet( ps, typedval.getValue(), locations[i] + start, session ); } result += locations.length; @@ -131,17 +127,4 @@ public class ParameterBinder { } return 0; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "bindNamedParameters() %s -> %s [%d]" ) - void bindNamedParameters( Object value, - String name, - int i ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java b/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java index 624a795306..1f71f31043 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java @@ -24,7 +24,6 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -34,6 +33,7 @@ import java.util.Map; import java.util.StringTokenizer; import org.hibernate.HibernateException; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.ScrollMode; import org.hibernate.dialect.Dialect; @@ -43,10 +43,6 @@ import org.hibernate.pretty.Printer; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Gavin King @@ -281,9 +277,9 @@ public final class QueryParameters { public void traceParameters(SessionFactoryImplementor factory) throws HibernateException { Printer print = new Printer( factory ); - if (positionalParameterValues.length != 0) LOG.parameters(print.toString(positionalParameterTypes, - positionalParameterValues)); - if (namedParameters != null) LOG.namedParameters(print.toString(namedParameters)); + if (positionalParameterValues.length != 0) LOG.trace("Parameters: " + + print.toString(positionalParameterTypes, positionalParameterValues)); + if (namedParameters != null) LOG.trace("Named parameters: " + print.toString(namedParameters)); } public boolean isCacheable() { @@ -563,19 +559,4 @@ public final class QueryParameters { copy.processedPositionalParameterValues = this.processedPositionalParameterValues; return copy; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Named parameters: %s" ) - void namedParameters( String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Parameters: %s" ) - void parameters( String string ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java index cbdb08e3e9..6c51fd87dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java @@ -24,8 +24,6 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.io.InvalidObjectException; @@ -44,6 +42,7 @@ import org.hibernate.AssertionFailure; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.NonUniqueObjectException; import org.hibernate.PersistentObjectException; @@ -58,10 +57,6 @@ import org.hibernate.proxy.LazyInitializer; import org.hibernate.tuple.ElementWrapper; import org.hibernate.util.IdentityMap; import org.hibernate.util.MarkerObject; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A PersistenceContext represents the state of persistent "stuff" which @@ -553,7 +548,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } if ( value instanceof HibernateProxy ) { - LOG.settingProxyIdentifier(id); + LOG.debug("setting proxy identifier: " + id); HibernateProxy proxy = (HibernateProxy) value; LazyInitializer li = proxy.getHibernateLazyInitializer(); li.setIdentifier(id); @@ -889,7 +884,7 @@ public class StatefulPersistenceContext implements PersistenceContext { */ public void initializeNonLazyCollections() throws HibernateException { if ( loadCounter == 0 ) { - LOG.initializingNonLazyCollections(); + LOG.debug("Initializing non-lazy collections"); //do this work only at the very highest level of the load loadCounter++; //don't let this method be called recursively try { @@ -1435,13 +1430,13 @@ public class StatefulPersistenceContext implements PersistenceContext { * @throws IOException serialization errors. */ public void serialize(ObjectOutputStream oos) throws IOException { - LOG.serializingPersistentContext(); + LOG.trace("Serializing persistent-context"); oos.writeBoolean( defaultReadOnly ); oos.writeBoolean( hasNonReadOnlyEntities ); oos.writeInt( entitiesByKey.size() ); - LOG.serializingEntitiesByKey(entitiesByKey.size()); + LOG.trace("Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries"); Iterator itr = entitiesByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1450,7 +1445,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entitiesByUniqueKey.size() ); - LOG.serializingEntitiesByUniqueKey(entitiesByUniqueKey.size()); + LOG.trace("Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries"); itr = entitiesByUniqueKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1459,7 +1454,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( proxiesByKey.size() ); - LOG.serializingProxiesByKey(proxiesByKey.size()); + LOG.trace("Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries"); itr = proxiesByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1468,7 +1463,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entitySnapshotsByKey.size() ); - LOG.serializingEntitySnapshotsByKey(entitySnapshotsByKey.size()); + LOG.trace("Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries"); itr = entitySnapshotsByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1477,7 +1472,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entityEntries.size() ); - LOG.serializingEntityEntries(entityEntries.size()); + LOG.trace("Starting serialization of [" + entityEntries.size() + "] entityEntries entries"); itr = entityEntries.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1486,7 +1481,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( collectionsByKey.size() ); - LOG.serializingCollectionsByKey(collectionsByKey.size()); + LOG.trace("Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries"); itr = collectionsByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1495,7 +1490,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( collectionEntries.size() ); - LOG.serializingCollectionEntries(collectionEntries.size()); + LOG.trace("Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries"); itr = collectionEntries.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1504,7 +1499,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( arrayHolders.size() ); - LOG.serializingArrayHolders(arrayHolders.size()); + LOG.trace("Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries"); itr = arrayHolders.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1513,7 +1508,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( nullifiableEntityKeys.size() ); - LOG.serializingNullifiableEntityKeys(nullifiableEntityKeys.size()); + LOG.trace("Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries"); itr = nullifiableEntityKeys.iterator(); while ( itr.hasNext() ) { EntityKey entry = ( EntityKey ) itr.next(); @@ -1524,7 +1519,7 @@ public class StatefulPersistenceContext implements PersistenceContext { public static StatefulPersistenceContext deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { - LOG.deserializingPersistentContext(); + LOG.trace("Serializing persistent-context"); StatefulPersistenceContext rtn = new StatefulPersistenceContext( session ); // during deserialization, we need to reconnect all proxies and @@ -1538,21 +1533,21 @@ public class StatefulPersistenceContext implements PersistenceContext { rtn.hasNonReadOnlyEntities = ois.readBoolean(); int count = ois.readInt(); - LOG.deserializingEntitiesByKey(count); + LOG.trace("Starting deserialization of [" + count + "] entitiesByKey entries"); rtn.entitiesByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitiesByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - LOG.deserializingEntitiesByUniqueKey(count); + LOG.trace("Starting deserialization of [" + count + "] entitiesByUniqueKey entries"); rtn.entitiesByUniqueKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitiesByUniqueKey.put( EntityUniqueKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - LOG.deserializingProxiesByKey(count); + LOG.trace("Starting deserialization of [" + count + "] proxiesByKey entries"); rtn.proxiesByKey = new ReferenceMap( AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK, count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count, .75f ); for ( int i = 0; i < count; i++ ) { EntityKey ek = EntityKey.deserialize( ois, session ); @@ -1560,19 +1555,19 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( proxy instanceof HibernateProxy ) { ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setSession( session ); rtn.proxiesByKey.put( ek, proxy ); - } else LOG.encounteredPrunedProxy(); + } else LOG.trace("Encountered prunded proxy"); // otherwise, the proxy was pruned during the serialization process } count = ois.readInt(); - LOG.deserializingEntitySnapshotsByKey(count); + LOG.trace("Starting deserialization of [" + count + "] entitySnapshotsByKey entries"); rtn.entitySnapshotsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitySnapshotsByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - LOG.deserializingEntityEntries(count); + LOG.trace("Starting deserialization of [" + count + "] entityEntries entries"); rtn.entityEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { Object entity = ois.readObject(); @@ -1581,14 +1576,14 @@ public class StatefulPersistenceContext implements PersistenceContext { } count = ois.readInt(); - LOG.deserializingCollectionsByKey(count); + LOG.trace("Starting deserialization of [" + count + "] collectionsByKey entries"); rtn.collectionsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.collectionsByKey.put( CollectionKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - LOG.deserializingCollectionEntries(count); + LOG.trace("Starting deserialization of [" + count + "] collectionEntries entries"); rtn.collectionEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { final PersistentCollection pc = ( PersistentCollection ) ois.readObject(); @@ -1598,14 +1593,14 @@ public class StatefulPersistenceContext implements PersistenceContext { } count = ois.readInt(); - LOG.deserializingArrayHolders(count); + LOG.trace("Starting deserialization of [" + count + "] arrayHolders entries"); rtn.arrayHolders = IdentityMap.instantiate( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.arrayHolders.put( ois.readObject(), ois.readObject() ); } count = ois.readInt(); - LOG.deserializingNullifiableEntityKeys(count); + LOG.trace("Starting deserialization of [" + count + "] nullifiableEntityKey entries"); rtn.nullifiableEntityKeys = new HashSet(); for ( int i = 0; i < count; i++ ) { rtn.nullifiableEntityKeys.add( EntityKey.deserialize( ois, session ) ); @@ -1676,107 +1671,4 @@ public class StatefulPersistenceContext implements PersistenceContext { insertedKeysMap.clear(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] arrayHolders entries" ) - void deserializingArrayHolders( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] collectionEntries entries" ) - void deserializingCollectionEntries( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] collectionsByKey entries" ) - void deserializingCollectionsByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] entitiesByKey entries" ) - void deserializingEntitiesByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] entitiesByUniqueKey entries" ) - void deserializingEntitiesByUniqueKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] entityEntries entries" ) - void deserializingEntityEntries( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] entitySnapshotsByKey entries" ) - void deserializingEntitySnapshotsByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] nullifiableEntityKey entries" ) - void deserializingNullifiableEntityKeys( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Serializing persistent-context" ) - void deserializingPersistentContext(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of [%d] proxiesByKey entries" ) - void deserializingProxiesByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Encountered prunded proxy" ) - void encounteredPrunedProxy(); - - @LogMessage( level = DEBUG ) - @Message( value = "Initializing non-lazy collections" ) - void initializingNonLazyCollections(); - - @LogMessage( level = WARN ) - @Message( value = "Narrowing proxy to %s - this operation breaks ==" ) - void narrowingProxy( Class concreteProxyClass ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] arrayHolders entries" ) - void serializingArrayHolders( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] collectionEntries entries" ) - void serializingCollectionEntries( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] collectionsByKey entries" ) - void serializingCollectionsByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] entitiesByKey entries" ) - void serializingEntitiesByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] entitiesByUniqueKey entries" ) - void serializingEntitiesByUniqueKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] entityEntries entries" ) - void serializingEntityEntries( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] entitySnapshotsByKey entries" ) - void serializingEntitySnapshotsByKey( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] nullifiableEntityKey entries" ) - void serializingNullifiableEntityKeys( int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Serializing persistent-context" ) - void serializingPersistentContext(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [%d] proxiesByKey entries" ) - void serializingProxiesByKey( int size ); - - @LogMessage( level = DEBUG ) - @Message( value = "setting proxy identifier: %s" ) - void settingProxyIdentifier( Serializable id ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java b/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java index 9f4a9b33fd..17e9c6ebea 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java @@ -23,13 +23,12 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.AssertionFailure; import org.hibernate.CacheMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.cache.CacheKey; import org.hibernate.cache.entry.CacheEntry; import org.hibernate.event.PostLoadEvent; @@ -43,10 +42,6 @@ import org.hibernate.property.BackrefPropertyAccessor; import org.hibernate.proxy.HibernateProxy; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Functionality relating to Hibernate's two-phase loading process, @@ -99,7 +94,7 @@ public final class TwoPhaseLoad { String versionStr = persister.isVersioned() ? persister.getVersionType().toLoggableString( version, session.getFactory() ) : "null"; - LOG.version(versionStr); + LOG.trace("Version: " + versionStr); } } @@ -130,7 +125,8 @@ public final class TwoPhaseLoad { Serializable id = entityEntry.getId(); Object[] hydratedState = entityEntry.getLoadedState(); - if (LOG.isDebugEnabled()) LOG.resolvingAssociations(MessageHelper.infoString(persister, id, session.getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Resolving associations for " + + MessageHelper.infoString(persister, id, session.getFactory())); Type[] types = persister.getPropertyTypes(); for ( int i = 0; i < hydratedState.length; i++ ) { @@ -154,9 +150,8 @@ public final class TwoPhaseLoad { final SessionFactoryImplementor factory = session.getFactory(); if ( persister.hasCache() && session.getCacheMode().isPutEnabled() ) { - if (LOG.isDebugEnabled()) LOG.addingEntityToSecondLevelCache(MessageHelper.infoString(persister, - id, - session.getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Adding entity to second-level cache: " + + MessageHelper.infoString(persister, id, session.getFactory())); Object version = Versioning.getVersion(hydratedState, persister); CacheEntry entry = new CacheEntry( @@ -249,7 +244,8 @@ public final class TwoPhaseLoad { } } - if (LOG.isDebugEnabled()) LOG.doneMaterializingEntity(MessageHelper.infoString(persister, id, session.getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Done materializing entity " + + MessageHelper.infoString(persister, id, session.getFactory())); if ( factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor().loadEntity( persister.getEntityName() ); @@ -316,27 +312,4 @@ public final class TwoPhaseLoad { lazyPropertiesAreUnfetched ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Adding entity to second-level cache: %s" ) - void addingEntityToSecondLevelCache( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done materializing entity %s" ) - void doneMaterializingEntity( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolving associations for %s" ) - void resolvingAssociations( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Version: %s" ) - void version( String versionStr ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java b/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java index 1d8efc0505..ea69ef2d33 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java @@ -24,13 +24,9 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.id.IdentifierGeneratorHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A strategy for determining if a version value is an version of @@ -53,7 +49,7 @@ public class VersionValue { public static final VersionValue NULL = new VersionValue() { @Override public final Boolean isUnsaved(Object version) { - LOG.versionUnsavedValueStrategy("NULL"); + LOG.trace("Version unsaved-value strategy NULL"); return version==null ? Boolean.TRUE : Boolean.FALSE; } @Override @@ -72,7 +68,7 @@ public class VersionValue { public static final VersionValue UNDEFINED = new VersionValue() { @Override public final Boolean isUnsaved(Object version) { - LOG.versionUnsavedValueStrategy("UNDEFINED"); + LOG.trace("Version unsaved-value strategy UNDEFINED"); return version==null ? Boolean.TRUE : null; } @Override @@ -92,7 +88,7 @@ public class VersionValue { @Override public final Boolean isUnsaved(Object version) throws MappingException { - LOG.versionUnsavedValueStrategy("NEGATIVE"); + LOG.trace("Version unsaved-value strategy NEGATIVE"); if (version==null) return Boolean.TRUE; if (version instanceof Number) return ((Number)version).longValue() < 0l ? Boolean.TRUE : Boolean.FALSE; throw new MappingException("unsaved-value NEGATIVE may only be used with short, int and long types"); @@ -129,7 +125,7 @@ public class VersionValue { * @return true is unsaved, false is saved, null is undefined */ public Boolean isUnsaved(Object version) throws MappingException { - LOG.versionUnsavedValue(value); + LOG.trace("Version unsaved-value: " + value); return version==null || version.equals(value) ? Boolean.TRUE : Boolean.FALSE; } @@ -141,19 +137,4 @@ public class VersionValue { public String toString() { return "version unsaved-value: " + value; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Version unsaved-value: %s" ) - void versionUnsavedValue( Object value ); - - @LogMessage( level = TRACE ) - @Message( value = "Version unsaved-value strategy %s" ) - void versionUnsavedValueStrategy( String string ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java b/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java index b6f28432f2..d56c672f11 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java @@ -24,13 +24,9 @@ */ package org.hibernate.engine; -import static org.jboss.logging.Logger.Level.TRACE; +import org.hibernate.Logger; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.VersionType; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Utilities for dealing with optimisitic locking values. @@ -79,7 +75,7 @@ public final class Versioning { */ private static Object seed(VersionType versionType, SessionImplementor session) { Object seed = versionType.seed( session ); - LOG.seeding(seed); + LOG.trace("Seeding: " + seed); return seed; } @@ -112,10 +108,8 @@ public final class Versioning { fields[versionProperty] = seed( versionType, session ); return true; } - else { - LOG.usingInitialVersion(initialVersion); - return false; - } + LOG.trace("Using initial version: " + initialVersion); + return false; } @@ -130,8 +124,8 @@ public final class Versioning { */ public static Object increment(Object version, VersionType versionType, SessionImplementor session) { Object next = versionType.next( version, session ); - if (LOG.isTraceEnabled()) LOG.incrementing(versionType.toLoggableString(version, session.getFactory()), - versionType.toLoggableString(next, session.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Incrementing: " + versionType.toLoggableString(version, session.getFactory()) + " to " + + versionType.toLoggableString(next, session.getFactory())); return next; } @@ -185,24 +179,4 @@ public final class Versioning { } return false; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Incrementing: %s to %s" ) - void incrementing( String loggableString, - String loggableString2 ); - - @LogMessage( level = TRACE ) - @Message( value = "Seeding: %s" ) - void seeding( Object seed ); - - @LogMessage( level = TRACE ) - @Message( value = "Using initial version: %s" ) - void usingInitialVersion( Object initialVersion ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java index b42b34fc90..77b80f8bbc 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java @@ -30,11 +30,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.ResultSet; import java.sql.SQLException; +import org.hibernate.Logger; import org.hibernate.util.JDBCExceptionReporter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A proxy for a ResultSet delegate, responsible for locally caching the columnName-to-columnIndex resolution that @@ -115,7 +112,7 @@ public class ResultSetWrapperProxy implements InvocationHandler { catch ( NoSuchMethodException ex ) { if (LOG.isEnabled(WARN)) { StringBuffer buf = new StringBuffer().append("Exception switching from method: [").append(method).append("] to a method using the column index. Reverting to using: [").append(method).append("]"); - LOG.missingMethod(buf.toString()); + LOG.warn(buf.toString()); } } } @@ -189,15 +186,4 @@ public class ResultSetWrapperProxy implements InvocationHandler { throw e.getTargetException(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "%s" ) - void missingMethod( String string ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java index 52b2ae78bf..03eae474f5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java @@ -118,7 +118,7 @@ public abstract class AbstractBatchImpl implements Batch { } PreparedStatement statement = statements.get( sql ); if ( statement != null ) { - log.debug( "reusing prepared statement" ); + LOG.debug("Reusing prepared statement"); statementLogger.logStatement( sql ); } return statement; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilder.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilder.java index 9d45f380be..70d63205f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilder.java @@ -53,7 +53,7 @@ public class BatchBuilder { public Batch buildBatch(Object key, SQLStatementLogger statementLogger, SQLExceptionHelper exceptionHelper) { - log.trace( "building batch [size={}]", size ); + LOG.trace("Building batch [size=" + size + "]"); return size > 1 ? new BatchingBatch( key, statementLogger, exceptionHelper, size ) : new NonBatchingBatch( key, statementLogger, exceptionHelper ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java index 758295dc0e..8464160c33 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java @@ -106,15 +106,10 @@ public class BatchingBatch extends AbstractBatchImpl { */ @Override protected void doExecuteBatch() { - if ( maxBatchPosition == 0 ) { - log.debug( "no batched statements to execute" ); - } + if (maxBatchPosition == 0) LOG.debug("No batched statements to execute"); else { - if ( log.isDebugEnabled() ) { - log.debug( "Executing {} statements with maximum batch size {} ", - getStatements().size(), maxBatchPosition - ); - } + LOG.debug("Executing " + getStatements().size() + " statements with maximum batch size " + maxBatchPosition); + try { executeStatements(); } @@ -145,17 +140,10 @@ public class BatchingBatch extends AbstractBatchImpl { ); } if ( expectations.size() > 0 ) { - if ( log.isDebugEnabled() ) { - log.debug( "Executing with batch of size {}: {}", expectations.size(), sql ); - } + LOG.debug("Executing with batch of size " + expectations.size() + ": " + sql); executeStatement( sql, statement, expectations ); expectations.clear(); - } - else { - if ( log.isDebugEnabled() ) { - log.debug( "Skipped executing because batch size is 0: ", sql ); - } - } + } else LOG.debug("Skipped executing because batch size is 0: " + sql); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java index d4100ca497..b5aef5d319 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java @@ -25,6 +25,7 @@ package org.hibernate.engine.jdbc.batch.internal; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.Logger; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.jdbc.Expectation; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ConnectionManagerImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ConnectionManagerImpl.java index dddaa20eca..5912f085fe 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ConnectionManagerImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ConnectionManagerImpl.java @@ -31,14 +31,11 @@ import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; +import org.hibernate.Logger; import org.hibernate.ScrollMode; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.jdbc.batch.internal.BatchBuilder; @@ -57,7 +54,7 @@ import org.hibernate.jdbc.Expectation; */ public class ConnectionManagerImpl implements ConnectionManager { - private static final Logger log = LoggerFactory.getLogger( ConnectionManagerImpl.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public static interface Callback extends ConnectionObserver { public boolean isTransactionInProgress(); @@ -77,11 +74,11 @@ public class ConnectionManagerImpl implements ConnectionManager { * Constructs a ConnectionManager. *

* This is the form used internally. - * + * * @param callback An observer for internal state change. * @param releaseMode The mode by which to release JDBC connections. * @param suppliedConnection An externally supplied connection. - */ + */ public ConnectionManagerImpl( SessionFactoryImplementor factory, Callback callback, @@ -254,17 +251,11 @@ public class ConnectionManagerImpl implements ConnectionManager { */ public void afterTransaction() { if ( logicalConnection != null ) { - if ( isAfterTransactionRelease() || isAggressiveReleaseNoTransactionCheck() ) { - logicalConnection.afterTransaction(); - } - else if ( isOnCloseRelease() ) { - // log a message about potential connection leaks - log.debug( "transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!" ); - } - } - if ( statementPreparer != null ) { - statementPreparer.unsetTransactionTimeout(); + if (isAfterTransactionRelease() || isAggressiveReleaseNoTransactionCheck()) logicalConnection.afterTransaction(); + // log a message about potential connection leaks + else if (isOnCloseRelease()) LOG.debug("Transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!"); } + if (statementPreparer != null) statementPreparer.unsetTransactionTimeout(); } private boolean isAfterTransactionRelease() { @@ -349,11 +340,11 @@ public class ConnectionManagerImpl implements ConnectionManager { */ private Connection cleanup() throws HibernateException { if ( logicalConnection == null ) { - log.trace( "connection already null in cleanup : no action"); + LOG.trace("Connection already null in cleanup : no action"); return null; } try { - log.trace( "performing cleanup" ); + LOG.trace("Performing cleanup"); releaseBatch(); statementPreparer.close(); Connection c = logicalConnection.close(); @@ -373,7 +364,7 @@ public class ConnectionManagerImpl implements ConnectionManager { */ @Override public void flushBeginning() { - log.trace( "registering flush begin" ); + LOG.trace("Registering flush begin"); logicalConnection.disableReleases(); } @@ -383,7 +374,7 @@ public class ConnectionManagerImpl implements ConnectionManager { */ @Override public void flushEnding() { - log.trace( "registering flush end" ); + LOG.trace("Registering flush end"); logicalConnection.enableReleases(); afterStatement(); } @@ -448,7 +439,7 @@ public class ConnectionManagerImpl implements ConnectionManager { @Override public CallableStatement prepareCallableStatement(String sql) { executeBatch(); - log.trace("preparing callable statement"); + LOG.trace("Preparing callable statement"); return CallableStatement.class.cast( statementPreparer.prepareStatement( getSQL( sql ), true ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JDBCContextImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JDBCContextImpl.java index c2cb5fd12a..6584bb7c5a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JDBCContextImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JDBCContextImpl.java @@ -24,9 +24,6 @@ */ package org.hibernate.engine.jdbc.internal; -import java.io.ObjectOutputStream; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -37,6 +34,7 @@ import javax.transaction.TransactionManager; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; +import org.hibernate.Logger; import org.hibernate.SessionException; import org.hibernate.Transaction; import org.hibernate.TransactionException; @@ -45,17 +43,6 @@ import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.transaction.synchronization.CallbackCoordinator; import org.hibernate.transaction.synchronization.HibernateSynchronizationImpl; import org.hibernate.util.JTAHelper; -import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.exception.JDBCExceptionHelper; -import org.hibernate.transaction.TransactionFactory; -import org.hibernate.transaction.synchronization.CallbackCoordinator; -import org.hibernate.transaction.synchronization.HibernateSynchronizationImpl; -import org.hibernate.util.JTAHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Acts as the intermediary between "entity-mode related" sessions in terms of their interaction with the JDBC data store. @@ -199,13 +186,13 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont if (tm == null) return false; try { if (!isTransactionInProgress()) { - LOG.noActiveTransaction(); + LOG.trace("TransactionFactory reported no active transaction; Synchronization not registered"); return false; } javax.transaction.Transaction tx = tm.getTransaction(); if (JTAHelper.isMarkedForRollback(tx)) { // transactions marked for rollback-only cause some TM impls to throw exceptions - LOG.transactionMarkedForRollback(); + LOG.debug("Transaction is marked for rollback; skipping Synchronization registration"); return false; } if (hibernateTransaction == null) hibernateTransaction = owner.getFactory().getSettings().getTransactionFactory().createTransaction(this, @@ -213,7 +200,7 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont tx.registerSynchronization(new HibernateSynchronizationImpl(getJtaSynchronizationCallbackCoordinator(tx))); // tx.registerSynchronization( new CacheSynchronization(owner, this, tx, hibernateTransaction) ); isTransactionCallbackRegistered = true; - LOG.successfullyRegisteredSynchronization(); + LOG.debug("Successfully registered Synchronization"); return true; } catch (HibernateException e) { throw e; @@ -221,7 +208,7 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont throw new TransactionException("could not register synchronization with JTA TransactionManager", e); } } - + @Override public boolean isTransactionInProgress() { return owner.getFactory().getSettings().getTransactionFactory() @@ -237,10 +224,10 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont } return hibernateTransaction; } - + @Override public void beforeTransactionCompletion(Transaction tx) { - LOG.beforeTransactionCompletion(); + LOG.trace("Before transaction completion"); owner.beforeTransactionCompletion(tx); } @@ -250,13 +237,13 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont */ @Override public void afterTransactionBegin(Transaction tx) { - LOG.afterTransactionBegin(); + LOG.trace("After transaction begin"); owner.afterTransactionBegin(tx); } @Override public void afterTransactionCompletion(boolean success, Transaction tx) { - LOG.afterTransactionCompletion(); + LOG.trace("After transaction completion"); if ( getFactory().getStatistics().isStatisticsEnabled() ) { getFactory().getStatisticsImplementor().endTransaction(success); @@ -275,7 +262,7 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont */ @Override public void afterNontransactionalQuery(boolean success) { - LOG.afterAutoCommit(); + LOG.trace("After autocommit"); try { // check to see if the connection is in auto-commit // mode (no connection means aggressive connection @@ -358,39 +345,4 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont ); return jdbcContext; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "After autocommit" ) - void afterAutoCommit(); - - @LogMessage( level = TRACE ) - @Message( value = "After transaction begin" ) - void afterTransactionBegin(); - - @LogMessage( level = TRACE ) - @Message( value = "After transaction completion" ) - void afterTransactionCompletion(); - - @LogMessage( level = TRACE ) - @Message( value = "Before transaction completion" ) - void beforeTransactionCompletion(); - - @LogMessage( level = TRACE ) - @Message( value = "TransactionFactory reported no active transaction; Synchronization not registered" ) - void noActiveTransaction(); - - @LogMessage( level = DEBUG ) - @Message( value = "Successfully registered Synchronization" ) - void successfullyRegisteredSynchronization(); - - @LogMessage( level = DEBUG ) - @Message( value = "Transaction is marked for rollback; skipping Synchronization registration" ) - void transactionMarkedForRollback(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcResourceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcResourceRegistryImpl.java index ca18987f1c..2705202ee2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcResourceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcResourceRegistryImpl.java @@ -23,9 +23,6 @@ */ package org.hibernate.engine.jdbc.internal; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -38,11 +35,7 @@ import org.hibernate.engine.jdbc.spi.InvalidatableWrapper; import org.hibernate.engine.jdbc.spi.JdbcResourceRegistry; import org.hibernate.engine.jdbc.spi.JdbcWrapper; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; import org.jboss.logging.Logger.Level; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Standard implementation of the {@link org.hibernate.engine.jdbc.spi.JdbcResourceRegistry} contract @@ -65,7 +58,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void register(Statement statement) { - LOG.registeringStatement(statement); + LOG.trace("Registering statement [" + statement + "]"); if ( xref.containsKey( statement ) ) { throw new HibernateException( "statement already registered with JDBCContainer" ); } @@ -74,7 +67,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { @SuppressWarnings({ "unchecked" }) public void registerLastQuery(Statement statement) { - log.trace( "registering last query statement [{}]", statement ); + LOG.trace("Registering last query statement [" + statement + "]"); if ( statement instanceof JdbcWrapper ) { JdbcWrapper wrapper = ( JdbcWrapper ) statement; registerLastQuery( wrapper.getWrappedObject() ); @@ -101,7 +94,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void release(Statement statement) { - LOG.releasingStatement(statement); + LOG.trace("Releasing statement [" + statement + "]"); Set resultSets = xref.get( statement ); if ( resultSets != null ) { for ( ResultSet resultSet : resultSets ) { @@ -114,7 +107,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void register(ResultSet resultSet) { - LOG.registeringResultSet(resultSet); + LOG.trace("Registering result set [" + resultSet + "]"); Statement statement; try { statement = resultSet.getStatement(); @@ -137,7 +130,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void release(ResultSet resultSet) { - LOG.releasingResultSet(resultSet); + LOG.trace("Releasing result set [" + resultSet + "]"); Statement statement; try { statement = resultSet.getStatement(); @@ -167,7 +160,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void releaseResources() { - LOG.releasingJdbcContainerResources(this); + LOG.trace("Releasing JDBC container resources [" + this + "]"); cleanup(); } @@ -243,13 +236,13 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void close() { - LOG.closingJdbcContainer(this); + LOG.trace("Closing JDBC container [" + this + "]"); cleanup(); } @SuppressWarnings({ "unchecked" }) protected void close(Statement statement) { - LOG.closingPreparedStatement(statement); + LOG.trace("Closing prepared statement [" + statement + "]"); if ( statement instanceof InvalidatableWrapper ) { InvalidatableWrapper wrapper = ( InvalidatableWrapper ) statement; @@ -271,7 +264,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } catch( SQLException sqle ) { // there was a problem "cleaning" the prepared statement - LOG.unableToClearMaxRowsQueryTimeout(sqle.getMessage()); + LOG.debug("Exception clearing maxRows/queryTimeout [" + sqle.getMessage() + "]"); return; // EARLY EXIT!!! } statement.close(); @@ -280,13 +273,13 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } } catch( SQLException sqle ) { - LOG.unableToReleaseStatement(sqle.getMessage()); + LOG.debug("Unable to release statement [" + sqle.getMessage() + "]"); } } @SuppressWarnings({ "unchecked" }) protected void close(ResultSet resultSet) { - LOG.closingResultSet(resultSet); + LOG.trace("Closing result set [" + resultSet + "]"); if ( resultSet instanceof InvalidatableWrapper ) { InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet; @@ -298,66 +291,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { resultSet.close(); } catch( SQLException e ) { - LOG.unableToReleaseResultSet(e.getMessage()); + LOG.debug("Unable to release result set [" + e.getMessage() + "]"); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Closing JDBC container [%s]" ) - void closingJdbcContainer( JdbcResourceRegistryImpl jdbcResourceRegistryImpl ); - - @LogMessage( level = TRACE ) - @Message( value = "Closing prepared statement [%s]" ) - void closingPreparedStatement( Statement statement ); - - @LogMessage( level = TRACE ) - @Message( value = "Closing result set [%s]" ) - void closingResultSet( ResultSet resultSet ); - - @LogMessage( level = TRACE ) - @Message( value = "Registering result set [%s]" ) - void registeringResultSet( ResultSet resultSet ); - - @LogMessage( level = TRACE ) - @Message( value = "Registering statement [%s]" ) - void registeringStatement( Statement statement ); - - @LogMessage( level = TRACE ) - @Message( value = "Releasing JDBC container resources [%s]" ) - void releasingJdbcContainerResources( JdbcResourceRegistryImpl jdbcResourceRegistryImpl ); - - @LogMessage( level = TRACE ) - @Message( value = "Releasing result set [%s]" ) - void releasingResultSet( ResultSet resultSet ); - - @LogMessage( level = TRACE ) - @Message( value = "Releasing statement [%s]" ) - void releasingStatement( Statement statement ); - - @LogMessage( level = DEBUG ) - @Message( value = "Exception clearing maxRows/queryTimeout [%s]" ) - void unableToClearMaxRowsQueryTimeout( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to release result set [%s]" ) - void unableToReleaseResultSet( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to release statement [%s]" ) - void unableToReleaseStatement( String message ); - - @LogMessage( level = WARN ) - @Message( value = "ResultSet's statement was not registered" ) - void unregisteredStatement(); - - @LogMessage( level = WARN ) - @Message( value = "ResultSet had no statement associated with it, but was not yet registered" ) - void unregisteredResultSetWithoutStatement(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java index dfd0e31151..e2187e68af 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java @@ -23,8 +23,6 @@ */ package org.hibernate.engine.jdbc.internal; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -34,6 +32,7 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.spi.ExtractedDatabaseMetaData; @@ -49,10 +48,6 @@ import org.hibernate.service.jdbc.dialect.spi.DialectFactory; import org.hibernate.service.spi.Configurable; import org.hibernate.service.spi.InjectService; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Standard implementation of the {@link JdbcServices} contract @@ -336,60 +331,4 @@ public class JdbcServicesImpl implements JdbcServices, Configurable { public ExtractedDatabaseMetaData getExtractedMetaDataSupport() { return extractedMetaDataSupport; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - // @formatter:off - @Message( value = "Database ->\n" + - " name : %s\n" + - " version : %s\n" + - " major : %s\n" + - " minor : %s" ) - // @formatter:on - void database( String databaseProductName, - String databaseProductVersion, - int databaseMajorVersion, - int databaseMinorVersion ); - - @LogMessage( level = INFO ) - // @formatter:off - @Message( value = "Driver ->\n" + - " name : %s\n" + - " version : %s\n" + - " major : %s\n" + - " minor : %s" ) - // @formatter:on - void driver( String driverProductName, - String driverProductVersion, - int driverMajorVersion, - int driverMinorVersion ); - - @LogMessage( level = INFO ) - @Message( value = "JDBC version : %d.%d" ) - void jdbcVersion( int jdbcMajorVersion, - int jdbcMinorVersion ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to instantiate configured schema name resolver [%s] %s" ) - void unableToInstantiateConfiguredSchemaNameResolver( String resolverClassName, - String message ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to locate configured schema name resolver class [%s] %s" ) - void unableToLocateConfiguredSchemaNameResolver( String resolverClassName, - String message ); - - @LogMessage( level = WARN ) - @Message( value = "Could not obtain connection metadata : %s" ) - void unableToObtainConnectionMetadata( String message ); - - @LogMessage( level = WARN ) - @Message( value = "Could not obtain connection to query metadata : %s" ) - void unableToObtainConnectionToQueryMetadata( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java index c99ca886f8..0882c58869 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java @@ -104,7 +104,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } else if ( connectionReleaseMode == ConnectionReleaseMode.AFTER_STATEMENT && ! jdbcServices.getConnectionProvider().supportsAggressiveRelease() ) { - log.debug( "connection provider reports to not support aggressive release; overriding" ); + LOG.debug("Connection provider reports to not support aggressive release; overriding"); return ConnectionReleaseMode.AFTER_TRANSACTION; } else { @@ -187,7 +187,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { Connection c = physicalConnection; try { releaseBorrowedConnection(); - log.trace( "closing logical connection" ); + LOG.trace("Closing logical connection"); if ( !isUserSuppliedConnection && physicalConnection != null ) { jdbcResourceRegistry.close(); releaseConnection(); @@ -198,7 +198,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { // no matter what physicalConnection = null; isClosed = true; - LOG.closedLogicalConnection(); + LOG.trace("Logical connection closed"); for ( ConnectionObserver observer : observers ) { observer.logicalConnectionClosed(); } @@ -243,19 +243,16 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } public void afterStatementExecution() { - LOG.startingAfterStatementExecution(connectionReleaseMode); + LOG.trace("Starting after statement execution processing [" + connectionReleaseMode + "]"); if ( connectionReleaseMode == ConnectionReleaseMode.AFTER_STATEMENT ) { if ( ! releasesEnabled ) { - LOG.skippingAggressiveReleaseDueToManualDisabling(); + LOG.debug("Skipping aggressive release due to manual disabling"); return; } if ( jdbcResourceRegistry.hasRegisteredResources() ) { - LOG.skippingAggressiveReleaseDueToRegisteredResources(); + LOG.debug("Skipping aggressive release due to registered resources"); return; - } - else if ( borrowedConnection != null ) { - log.debug( "skipping aggresive-release due to borrowed connection" ); - } + } else if (borrowedConnection != null) LOG.debug("Skipping aggressive release due to borrowed connection"); releaseConnection(); } } @@ -272,12 +269,12 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } public void disableReleases() { - LOG.disablingReleases(); + LOG.trace("Disabling releases"); releasesEnabled = false; } public void enableReleases() { - LOG.enablingReleases(); + LOG.trace("(Re)enabling releases"); releasesEnabled = true; //FIXME: uncomment after new batch stuff is integrated!!! //afterStatementExecution(); @@ -287,11 +284,9 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { * Force aggresive release of the underlying connection. */ public void aggressiveRelease() { - if ( isUserSuppliedConnection ) { - LOG.unableToAggressivelyReleaseUserSuppliedConnection(); - } + if (isUserSuppliedConnection) LOG.debug("Cannot aggressively release user-supplied connection; skipping"); else { - LOG.aggressivelyReleasingJdbcConnection( ); + LOG.debug("Aggressively releasing JDBC connection"); if ( physicalConnection != null ) { releaseConnection(); } @@ -305,13 +300,13 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { * @throws org.hibernate.JDBCException Indicates problem opening a connection */ private void obtainConnection() throws JDBCException { - LOG.obtainingJdbcConnection(); + LOG.debug("Obtaining JDBC connection"); try { physicalConnection = getJdbcServices().getConnectionProvider().getConnection(); for ( ConnectionObserver observer : observers ) { observer.physicalConnectionObtained( physicalConnection ); } - LOG.obtainedJdbcConnection(); + LOG.debug("Obtained JDBC connection"); } catch ( SQLException sqle) { throw getJdbcServices().getSqlExceptionHelper().convert( sqle, "Could not open connection" ); @@ -324,18 +319,11 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { * @throws JDBCException Indicates problem closing a connection */ private void releaseConnection() throws JDBCException { - LOG.releasingJdbcConnection(); - if ( physicalConnection == null ) { - return; - } + LOG.debug("Releasing JDBC connection"); + if ( physicalConnection == null ) return; try { - if ( ! physicalConnection.isClosed() ) { - getJdbcServices().getSqlExceptionHelper().logAndClearWarnings( physicalConnection ); - } - if ( !isUserSuppliedConnection ) { - getJdbcServices().getConnectionProvider().closeConnection( physicalConnection ); - } - LOG.releasedJdbcConnection(); + if (!physicalConnection.isClosed()) getJdbcServices().getSqlExceptionHelper().logAndClearWarnings(physicalConnection); + if (!isUserSuppliedConnection) getJdbcServices().getConnectionProvider().closeConnection(physicalConnection); } catch (SQLException sqle) { throw getJdbcServices().getSqlExceptionHelper().convert( sqle, "Could not close connection" ); @@ -343,7 +331,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { finally { physicalConnection = null; } - log.debug( "released JDBC connection" ); + LOG.debug("Released JDBC connection"); for ( ConnectionObserver observer : observers ) { observer.physicalConnectionReleased(); } @@ -389,13 +377,11 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { ); } physicalConnection = suppliedConnection; - log.debug( "reconnected JDBC connection" ); + LOG.debug("Reconnected JDBC connection"); } else { - if ( suppliedConnection != null ) { - throw new IllegalStateException( "unexpected user-supplied connection" ); - } - log.debug( "called reconnect() with null connection (not user-supplied)" ); + if (suppliedConnection != null) throw new IllegalStateException("unexpected user-supplied connection"); + LOG.debug("Called reconnect() with null connection (not user-supplied)"); } } @@ -424,73 +410,4 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { ois.readBoolean() ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - /* - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Aggressively releasing JDBC connection" ) - void aggressivelyReleasingJdbcConnection(); - - @LogMessage( level = TRACE ) - @Message( value = "Logical connection closed" ) - void closedLogicalConnection(); - - @LogMessage( level = TRACE ) - @Message( value = "Closing logical connection" ) - void closingLogicalConnection(); - - @LogMessage( level = TRACE ) - @Message( value = "Disabling releases" ) - void disablingReleases(); - - @LogMessage( level = TRACE ) - @Message( value = "(Re)enabling releases" ) - void enablingReleases(); - - @LogMessage( level = INFO ) - @Message( value = "Forcing container resource cleanup on transaction completion" ) - void forcingContainerResourceCleanup(); - - @LogMessage( level = DEBUG ) - @Message( value = "Obtained JDBC connection" ) - void obtainedJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Obtaining JDBC connection" ) - void obtainingJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Released JDBC connection" ) - void releasedJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Releasing JDBC connection" ) - void releasingJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Skipping aggressive release due to manual disabling" ) - void skippingAggressiveReleaseDueToManualDisabling(); - - @LogMessage( level = DEBUG ) - @Message( value = "Skipping aggressive release due to registered resources" ) - void skippingAggressiveReleaseDueToRegisteredResources(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting after statement execution processing [%s]" ) - void startingAfterStatementExecution( ConnectionReleaseMode connectionReleaseMode ); - - @LogMessage( level = DEBUG ) - @Message( value = "Cannot aggressively release user-supplied connection; skipping" ) - void unableToAggressivelyReleaseUserSuppliedConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Connection provider reports to not support aggressive release; overriding" ) - void unsupportedAggressiveRelease(); - } - */ } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparer.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparer.java index 2500f328f9..f5a08c22ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparer.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparer.java @@ -28,12 +28,9 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.ScrollMode; import org.hibernate.TransactionException; import org.hibernate.cfg.Settings; @@ -48,7 +45,7 @@ import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; */ public class StatementPreparer { - private static final Logger log = LoggerFactory.getLogger( StatementPreparer.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); // TODO: Move JDBC settings into a different object... private final Settings settings; @@ -88,7 +85,7 @@ public class StatementPreparer { return ps; } catch ( SQLException sqle ) { - log.error( "sqlexception escaped proxy", sqle ); + LOG.error(LOG.sqlExceptionEscapedProxy(), sqle); throw sqlExceptionHelper.convert( sqle, "could not prepare statement", sql ); @@ -100,7 +97,8 @@ public class StatementPreparer { QueryStatementPreparation(String sql) { super( sql ); } - public void postProcess(PreparedStatement preparedStatement) throws SQLException { + @Override + public void postProcess(PreparedStatement preparedStatement) throws SQLException { super.postProcess( preparedStatement ); setStatementFetchSize( preparedStatement ); } @@ -111,7 +109,7 @@ public class StatementPreparer { proxiedConnection.close(); } catch (SQLException sqle) { - log.error( "sqlexception escaped proxy", sqle ); + LOG.error(LOG.sqlExceptionEscapedProxy(), sqle); throw sqlExceptionHelper.convert( sqle, "could not close connection proxy" ); } } @@ -128,7 +126,8 @@ public class StatementPreparer { */ public PreparedStatement prepareStatement(String sql, final boolean isCallable) { StatementPreparation statementPreparation = new StatementPreparation( sql ) { - public PreparedStatement doPrepare() throws SQLException { + @Override + public PreparedStatement doPrepare() throws SQLException { return isCallable ? proxiedConnection.prepareCall( getSql() ) : proxiedConnection.prepareStatement( getSql() ); @@ -154,11 +153,12 @@ public class StatementPreparer { */ public PreparedStatement prepareStatement(String sql, final int autoGeneratedKeys) throws HibernateException { - if ( autoGeneratedKeys == PreparedStatement.RETURN_GENERATED_KEYS ) { + if ( autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS ) { checkAutoGeneratedKeysSupportEnabled(); } StatementPreparation statementPreparation = new StatementPreparation( sql ) { - public PreparedStatement doPrepare() throws SQLException { + @Override + public PreparedStatement doPrepare() throws SQLException { return proxiedConnection.prepareStatement( getSql(), autoGeneratedKeys ); } }; @@ -176,7 +176,8 @@ public class StatementPreparer { public PreparedStatement prepareStatement(String sql, final String[] columnNames) { checkAutoGeneratedKeysSupportEnabled(); StatementPreparation preparation = new StatementPreparation( sql ) { - public PreparedStatement doPrepare() throws SQLException { + @Override + public PreparedStatement doPrepare() throws SQLException { return proxiedConnection.prepareStatement( getSql(), columnNames ); } }; @@ -201,7 +202,8 @@ public class StatementPreparer { final boolean isCallable ) { StatementPreparation prep = new QueryStatementPreparation( sql ) { - public PreparedStatement doPrepare() throws SQLException { + @Override + public PreparedStatement doPrepare() throws SQLException { return isCallable ? proxiedConnection.prepareCall( getSql() ) : proxiedConnection.prepareStatement( getSql() ); @@ -226,7 +228,8 @@ public class StatementPreparer { throw new AssertionFailure("scrollable result sets are not enabled"); } StatementPreparation prep = new QueryStatementPreparation( sql ) { - public PreparedStatement doPrepare() throws SQLException { + @Override + public PreparedStatement doPrepare() throws SQLException { return isCallable ? proxiedConnection.prepareCall( getSql(), scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractResultSetProxyHandler.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractResultSetProxyHandler.java index b10beef378..c46acb67f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractResultSetProxyHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractResultSetProxyHandler.java @@ -23,18 +23,14 @@ */ package org.hibernate.engine.jdbc.internal.proxy; -import static org.jboss.logging.Logger.Level.TRACE; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.hibernate.Logger; import org.hibernate.engine.jdbc.spi.JdbcResourceRegistry; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic support for building {@link ResultSet}-based proxy handlers @@ -71,7 +67,7 @@ public abstract class AbstractResultSetProxyHandler extends AbstractProxyHandler @Override protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - LOG.handlingInvocationOfResultSetMethod(methodName); + LOG.trace("Handling invocation of ResultSet method [" + methodName + "]"); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -107,13 +103,9 @@ public abstract class AbstractResultSetProxyHandler extends AbstractProxyHandler } catch ( InvocationTargetException e ) { Throwable realException = e.getTargetException(); - if ( SQLException.class.isInstance( realException ) ) { - throw getJdbcServices().getSqlExceptionHelper() - .convert( ( SQLException ) realException, realException.getMessage() ); - } - else { - throw realException; - } + if (SQLException.class.isInstance(realException)) throw getJdbcServices().getSqlExceptionHelper().convert((SQLException)realException, + realException.getMessage()); + throw realException; } } @@ -127,15 +119,4 @@ public abstract class AbstractResultSetProxyHandler extends AbstractProxyHandler resultSet = null; invalidate(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Handling invocation of ResultSet method [%s]" ) - void handlingInvocationOfResultSetMethod( String methodName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractStatementProxyHandler.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractStatementProxyHandler.java index 8437113b7e..b9f4b50426 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractStatementProxyHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractStatementProxyHandler.java @@ -23,20 +23,16 @@ */ package org.hibernate.engine.jdbc.internal.proxy; -import static org.jboss.logging.Logger.Level.TRACE; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.hibernate.Logger; import org.hibernate.engine.jdbc.spi.JdbcResourceRegistry; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.LogicalConnectionImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic support for building {@link Statement}-based proxy handlers @@ -87,7 +83,7 @@ public abstract class AbstractStatementProxyHandler extends AbstractProxyHandler @Override protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - LOG.handlingInvocationOfStatementMethod(methodName); + LOG.trace("Handling invocation of statement method [" + methodName + "]"); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -169,15 +165,4 @@ public abstract class AbstractStatementProxyHandler extends AbstractProxyHandler statement = null; invalidate(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Handling invocation of statement method [%s]" ) - void handlingInvocationOfStatementMethod( String methodName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/ConnectionProxyHandler.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/ConnectionProxyHandler.java index 6abc433c6f..2b1a4b449b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/ConnectionProxyHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/ConnectionProxyHandler.java @@ -102,7 +102,7 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo @Override protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - LOG.handlingInvocationOfConnectionMethod(methodName); + LOG.trace("Handling invocation of connection method [" + methodName + "]"); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -196,7 +196,7 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo } private void invalidateHandle() { - LOG.invalidatingConnectionHandle(); + LOG.trace("Invalidating connection handle"); logicalConnection = null; invalidate(); } @@ -222,33 +222,7 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo invalidateHandle(); } - /* package-protected */ - StatisticsImplementor getStatisticsImplementorOrNull() { - return getLogicalConnection().getStatisticsImplementor(); - } - - /** - * Interface defining messages that may be logged by the outer class - */ - /* - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Handling invocation of connection method [%s]" ) - void handlingInvocationOfConnectionMethod( String methodName ); - - @LogMessage( level = TRACE ) - @Message( value = "Invalidating connection handle" ) - void invalidatingConnectionHandle(); - - @LogMessage( level = INFO ) - @Message( value = "*** Logical connection closed ***" ) - void logicalConnectionClosed(); - - @LogMessage( level = INFO ) - @Message( value = "Logical connection releasing its physical connection" ) - void logicalConnectionReleasingPhysicalConnection(); + StatisticsImplementor getStatisticsImplementorOrNull() { + return getLogicalConnection().getStatisticsImplementor(); } - */ } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/PreparedStatementProxyHandler.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/PreparedStatementProxyHandler.java index e78e3e32bf..3b60f80cc4 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/PreparedStatementProxyHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/PreparedStatementProxyHandler.java @@ -23,14 +23,12 @@ */ package org.hibernate.engine.jdbc.internal.proxy; +import static org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.LOG; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.Statement; import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Invocation handler for {@link java.sql.PreparedStatement} proxies * @@ -51,7 +49,8 @@ public class PreparedStatementProxyHandler extends AbstractStatementProxyHandler this.sql = sql; } - protected void beginningInvocationHandling(Method method, Object[] args) { + @Override + protected void beginningInvocationHandling(Method method, Object[] args) { if ( isExecution( method ) ) { logExecution(); } @@ -69,13 +68,13 @@ public class PreparedStatementProxyHandler extends AbstractStatementProxyHandler } private void journalParameterBind(Method method, Object[] args) { - log.trace( "binding via {}: []", method.getName(), Arrays.asList( args ) ); + LOG.trace("Binding via " + method.getName() + ": " + Arrays.asList(args)); } private boolean isExecution(Method method) { return false; } - private void logExecution() { - } + private void logExecution() { + } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLExceptionHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLExceptionHelper.java index 4b71c0d585..b28c46f1e8 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLExceptionHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLExceptionHelper.java @@ -23,22 +23,17 @@ */ package org.hibernate.engine.jdbc.spi; -import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLWarning; import org.hibernate.JDBCException; +import org.hibernate.Logger; import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.exception.SQLStateConverter; import org.hibernate.exception.ViolatedConstraintNameExtracter; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Helper for handling SQLExceptions in various manners. @@ -143,7 +138,7 @@ public class SQLExceptionHelper { connection.clearWarnings(); } catch ( SQLException sqle ) { - LOG.unableToClearWarnings(sqle); + LOG.debug("Could not clear warnings : " + sqle); } } @@ -165,15 +160,15 @@ public class SQLExceptionHelper { */ public void logWarnings(SQLWarning warning, String message) { if (LOG.isEnabled(WARN)) { - if (warning != null) LOG.warningPreamble(StringHelper.isNotEmpty(message) ? message : DEFAULT_WARNING_MSG, warning); + if (warning != null) LOG.debug((StringHelper.isNotEmpty(message) ? message : DEFAULT_WARNING_MSG) + " : " + warning); while ( warning != null ) { StringBuffer buf = new StringBuffer( 30 ) .append( "SQL Warning: " ) .append( warning.getErrorCode() ) .append( ", SQLState: " ) .append( warning.getSQLState() ); - LOG.warningProperties(buf.toString()); - LOG.warningMessage(warning.getMessage()); + LOG.warn(buf.toString()); + LOG.warn(warning.getMessage()); warning = warning.getNextWarning(); } } @@ -196,62 +191,17 @@ public class SQLExceptionHelper { */ public void logExceptions(SQLException sqlException, String message) { if (LOG.isEnabled(ERROR)) { - LOG.errorPreamble(StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG, sqlException); + LOG.debug((StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG) + " : " + sqlException); while ( sqlException != null ) { StringBuffer buf = new StringBuffer( 30 ) .append( "SQL Error: " ) .append( sqlException.getErrorCode() ) .append( ", SQLState: " ) .append( sqlException.getSQLState() ); - LOG.errorProperties(buf.toString()); - LOG.errorMessage(sqlException.getMessage()); + LOG.warn(buf.toString()); + LOG.error(sqlException.getMessage()); sqlException = sqlException.getNextException(); } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "On release of batch it still contained JDBC statements" ) - void batchContainedStatementsOnRelease(); - - @LogMessage( level = ERROR ) - @Message( value = "%s" ) - void errorMessage( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s : %s" ) - void errorPreamble( String string, - SQLException sqlException ); - - @LogMessage( level = WARN ) - @Message( value = "%s" ) - void errorProperties( String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Could not clear warnings : %s" ) - void unableToClearWarnings( SQLException sqle ); - - @LogMessage( level = WARN ) - @Message( value = "Could not log warnings : %s" ) - void unableToLogWarnings( SQLException sqle ); - - @LogMessage( level = WARN ) - @Message( value = "%s" ) - void warningMessage( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s : %s" ) - void warningPreamble( String message, - SQLWarning warning ); - - @LogMessage( level = WARN ) - @Message( value = "%s" ) - void warningProperties( String string ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLStatementLogger.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLStatementLogger.java index c306918a19..e7a87cea7a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLStatementLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SQLStatementLogger.java @@ -23,12 +23,8 @@ */ package org.hibernate.engine.jdbc.spi; -import static org.jboss.logging.Logger.Level.DEBUG; +import org.hibernate.Logger; import org.hibernate.jdbc.util.FormatStyle; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Centralize logging for SQL statements. @@ -95,19 +91,8 @@ public class SQLStatementLogger { public void logStatement(String statement) { // for now just assume a DML log for formatting if (format && (logToStdout || LOG.isDebugEnabled())) statement = FormatStyle.BASIC.getFormatter().format(statement); - LOG.statement(statement); + LOG.debug(statement); if (logToStdout) System.out.println("Hibernate: " + statement); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "%s" ) - void statement( String statement ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/CollectionLoadContext.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/CollectionLoadContext.java index b1349e3a40..fea4c534f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/CollectionLoadContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/loading/CollectionLoadContext.java @@ -24,9 +24,6 @@ */ package org.hibernate.engine.loading; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.sql.ResultSet; import java.util.ArrayList; @@ -36,6 +33,7 @@ import java.util.List; import java.util.Set; import org.hibernate.CacheMode; import org.hibernate.EntityMode; +import org.hibernate.Logger; import org.hibernate.cache.CacheKey; import org.hibernate.cache.entry.CollectionCacheEntry; import org.hibernate.collection.PersistentCollection; @@ -46,10 +44,6 @@ import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.Status; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Represents state associated with the processing of a given {@link ResultSet} @@ -114,16 +108,18 @@ public class CollectionLoadContext { public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) { final EntityMode em = loadContexts.getPersistenceContext().getSession().getEntityMode(); final CollectionKey collectionKey = new CollectionKey( persister, key, em ); - if (LOG.isTraceEnabled()) LOG.findingLoadingCollection(MessageHelper.collectionInfoString(persister.getRole(), key)); + if (LOG.isTraceEnabled()) LOG.trace("Starting attempt to find loading collection [" + + MessageHelper.collectionInfoString(persister.getRole(), key) + "]"); final LoadingCollectionEntry loadingCollectionEntry = loadContexts.locateLoadingCollectionEntry( collectionKey ); if ( loadingCollectionEntry == null ) { // look for existing collection as part of the persistence context PersistentCollection collection = loadContexts.getPersistenceContext().getCollection( collectionKey ); if ( collection != null ) { if ( collection.wasInitialized() ) { - LOG.collectionAlreadyInitialized(); + LOG.trace("Collection already initialized; ignoring"); return null; // ignore this row of results! Note the early exit - } else LOG.collectionNotYetInitialized(); + } + LOG.trace("Collection not yet initialized; initializing"); } else { Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister ); @@ -133,15 +129,14 @@ public class CollectionLoadContext { if ( newlySavedEntity ) { // important, to account for newly saved entities in query // todo : some kind of check for new status... - LOG.owningEntityAlreadyLoaded(); + LOG.trace("Owning entity already loaded; ignoring"); return null; } - else { - // create one - LOG.instantiatingNewCollection(key, resultSet); - collection = persister.getCollectionType() - .instantiate( loadContexts.getPersistenceContext().getSession(), persister, key ); - } + // create one + LOG.trace("Instantiating new collection [key=" + key + ", rs=" + resultSet + "]"); + collection = persister.getCollectionType().instantiate(loadContexts.getPersistenceContext().getSession(), + persister, + key); } collection.beforeInitialize( persister, -1 ); collection.beginRead(); @@ -149,18 +144,14 @@ public class CollectionLoadContext { loadContexts.registerLoadingCollectionXRef( collectionKey, new LoadingCollectionEntry( resultSet, persister, key, collection ) ); return collection; } - else { - if ( loadingCollectionEntry.getResultSet() == resultSet ) { - LOG.foundLoadingCollection(); - return loadingCollectionEntry.getCollection(); - } - else { - // ignore this row, the collection is in process of - // being loaded somewhere further "up" the stack - LOG.collectionAlreadyInitializing(); - return null; - } + if (loadingCollectionEntry.getResultSet() == resultSet) { + LOG.trace("Found loading collection bound to current result set processing; reading row"); + return loadingCollectionEntry.getCollection(); } + // ignore this row, the collection is in process of + // being loaded somewhere further "up" the stack + LOG.trace("Collection is already being initialized; ignoring row"); + return null; } /** @@ -200,7 +191,7 @@ public class CollectionLoadContext { lce.getCollection() ); } - LOG.removingCollectionLoadEntry(lce); + LOG.trace("Removing collection load entry [" + lce + "]"); // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)... loadContexts.unregisterLoadingCollectionXRef( collectionKey ); @@ -222,23 +213,23 @@ public class CollectionLoadContext { private void endLoadingCollections(CollectionPersister persister, List matchedCollectionEntries) { if ( matchedCollectionEntries == null ) { - LOG.noCollectionFoundInResultSet(persister.getRole()); + LOG.debug("No collections were found in result set for role: " + persister.getRole()); return; } final int count = matchedCollectionEntries.size(); - LOG.collectionsFound(count, persister.getRole()); + LOG.debug(count + " collections were found in result set for role: " + persister.getRole()); for ( int i = 0; i < count; i++ ) { LoadingCollectionEntry lce = ( LoadingCollectionEntry ) matchedCollectionEntries.get( i ); endLoadingCollection( lce, persister ); } - LOG.collectionsInitialized(count, persister.getRole()); + LOG.debug(count + " collections initialized for role: " + persister.getRole()); } private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) { - LOG.endingLoadingCollection(lce); + LOG.trace("Ending loading collection [" + lce + "]"); final SessionImplementor session = getLoadContext().getPersistenceContext().getSession(); final EntityMode em = session.getEntityMode(); @@ -260,16 +251,11 @@ public class CollectionLoadContext { persister.hasCache() && // and the role has a cache session.getCacheMode().isPutEnabled() && !ce.isDoremove(); // and this is not a forced initialization during flush - if ( addToCache ) { - addCollectionToCache( lce, persister ); - } + if (addToCache) addCollectionToCache(lce, persister); - if (LOG.isDebugEnabled()) LOG.collectionInitialized(MessageHelper.collectionInfoString(persister, - lce.getKey(), - session.getFactory())); - if ( session.getFactory().getStatistics().isStatisticsEnabled() ) { - session.getFactory().getStatisticsImplementor().loadCollection( persister.getRole() ); - } + if (LOG.isDebugEnabled()) LOG.debug("Collection fully initialized: " + + MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory())); + if (session.getFactory().getStatistics().isStatisticsEnabled()) session.getFactory().getStatisticsImplementor().loadCollection(persister.getRole()); } /** @@ -282,11 +268,12 @@ public class CollectionLoadContext { final SessionImplementor session = getLoadContext().getPersistenceContext().getSession(); final SessionFactoryImplementor factory = session.getFactory(); - if (LOG.isDebugEnabled()) LOG.cachingCollection(MessageHelper.collectionInfoString(persister, lce.getKey(), factory)); + if (LOG.isDebugEnabled()) LOG.debug("Caching collection: " + + MessageHelper.collectionInfoString(persister, lce.getKey(), factory)); if ( !session.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( session ) ) { // some filters affecting the collection are enabled on the session, so do not do the put into the cache. - LOG.notAddingToCache(); + LOG.debug("Refusing to add to cache due to enabled filters"); // todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered; // but CacheKey is currently used for both collections and entities; would ideally need to define two seperate ones; // currently this works in conjuction with the check on @@ -336,82 +323,4 @@ public class CollectionLoadContext { public String toString() { return super.toString() + ""; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Caching collection: %s" ) - void cachingCollection( String collectionInfoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Collection already initialized; ignoring" ) - void collectionAlreadyInitialized(); - - @LogMessage( level = TRACE ) - @Message( value = "Collection is already being initialized; ignoring row" ) - void collectionAlreadyInitializing(); - - @LogMessage( level = DEBUG ) - @Message( value = "Collection fully initialized: %s" ) - void collectionInitialized( String collectionInfoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Collection not yet initialized; initializing" ) - void collectionNotYetInitialized(); - - @LogMessage( level = DEBUG ) - @Message( value = "%d collections were found in result set for role: %s" ) - void collectionsFound( int count, - String role ); - - @LogMessage( level = DEBUG ) - @Message( value = "%d collections initialized for role: %s" ) - void collectionsInitialized( int count, - String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Ending loading collection [%s]" ) - void endingLoadingCollection( LoadingCollectionEntry lce ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting attempt to find loading collection [%s]" ) - void findingLoadingCollection( String collectionInfoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Found loading collection bound to current result set processing; reading row" ) - void foundLoadingCollection(); - - @LogMessage( level = TRACE ) - @Message( value = "Instantiating new collection [key=%s, rs=%s]" ) - void instantiatingNewCollection( Serializable key, - ResultSet resultSet ); - - @LogMessage( level = WARN ) - @Message( value = "In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [%s], but no LoadingCollectionEntry was found in loadContexts" ) - void loadingCollectionKeyNotFound( CollectionKey collectionKey ); - - @LogMessage( level = WARN ) - @Message( value = "On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [%d] entries" ) - void localLoadingCollectionKeysCount( int size ); - - @LogMessage( level = DEBUG ) - @Message( value = "No collections were found in result set for role: %s" ) - void noCollectionFoundInResultSet( String role ); - - @LogMessage( level = DEBUG ) - @Message( value = "Refusing to add to cache due to enabled filters" ) - void notAddingToCache(); - - @LogMessage( level = TRACE ) - @Message( value = "Owning entity already loaded; ignoring" ) - void owningEntityAlreadyLoaded(); - - @LogMessage( level = TRACE ) - @Message( value = "Removing collection load entry [%s]" ) - void removingCollectionLoadEntry( LoadingCollectionEntry lce ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/EntityLoadContext.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/EntityLoadContext.java index 86c327f17a..c11dcdee8c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/EntityLoadContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/loading/EntityLoadContext.java @@ -24,14 +24,10 @@ */ package org.hibernate.engine.loading; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * {@inheritDoc} @@ -62,15 +58,4 @@ public class EntityLoadContext { public String toString() { return super.toString() + ""; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "On EntityLoadContext#clear, hydratingEntities contained [%d] entries" ) - void hydratingEntitiesCount( int size ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/loading/LoadContexts.java b/hibernate-core/src/main/java/org/hibernate/engine/loading/LoadContexts.java index f48d67be63..79a33fafd0 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/loading/LoadContexts.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/loading/LoadContexts.java @@ -24,8 +24,6 @@ */ package org.hibernate.engine.loading; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.sql.ResultSet; import java.util.HashMap; @@ -33,6 +31,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; import org.hibernate.EntityMode; +import org.hibernate.Logger; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.CollectionKey; import org.hibernate.engine.PersistenceContext; @@ -40,10 +39,6 @@ import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.util.IdentityMap; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Maps {@link ResultSet result-sets} to specific contextual data @@ -184,14 +179,10 @@ public class LoadContexts { */ public CollectionLoadContext getCollectionLoadContext(ResultSet resultSet) { CollectionLoadContext context = null; - if ( collectionLoadContexts == null ) { - collectionLoadContexts = IdentityMap.instantiate( 8 ); - } - else { - context = ( CollectionLoadContext ) collectionLoadContexts.get( resultSet ); - } + if (collectionLoadContexts == null) collectionLoadContexts = IdentityMap.instantiate(8); + else context = (CollectionLoadContext)collectionLoadContexts.get(resultSet); if ( context == null ) { - LOG.constructingCollectionLoadContext(resultSet); + LOG.trace("Constructing collection load context for result set [" + resultSet + "]"); context = new CollectionLoadContext( this, resultSet ); collectionLoadContexts.put( resultSet, context ); } @@ -209,15 +200,13 @@ public class LoadContexts { public PersistentCollection locateLoadingCollection(CollectionPersister persister, Serializable ownerKey) { LoadingCollectionEntry lce = locateLoadingCollectionEntry( new CollectionKey( persister, ownerKey, getEntityMode() ) ); if ( lce != null ) { - if (LOG.isTraceEnabled()) LOG.returningLoadingCollection(MessageHelper.collectionInfoString(persister, - ownerKey, - getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Returning loading collection: " + + MessageHelper.collectionInfoString(persister, ownerKey, getSession().getFactory())); return lce.getCollection(); } // TODO : should really move this log statement to CollectionType, where this is used from... - if (LOG.isTraceEnabled()) LOG.creatingCollectionWrapper(MessageHelper.collectionInfoString(persister, - ownerKey, - getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Creating collection wrapper: " + + MessageHelper.collectionInfoString(persister, ownerKey, getSession().getFactory())); return null; } @@ -283,13 +272,11 @@ public class LoadContexts { * @return The located entry; or null. */ LoadingCollectionEntry locateLoadingCollectionEntry(CollectionKey key) { - if ( xrefLoadingCollectionEntries == null ) { - return null; - } - LOG.locatingLoadingCollectionEntry(key); + if (xrefLoadingCollectionEntries == null) return null; + LOG.trace("Attempting to locate loading collection entry [" + key + "] in any result-set context"); LoadingCollectionEntry rtn = ( LoadingCollectionEntry ) xrefLoadingCollectionEntries.get( key ); - if (rtn == null) LOG.collectionNotLocated(key); - else LOG.collectionLocated(key); + if (rtn == null) LOG.trace("Collection [" + key + "] not located in load context"); + else LOG.trace("Collection [" + key + "] located in load context"); return rtn; } @@ -319,43 +306,4 @@ public class LoadContexts { } return context; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Collection [%s] located in load context" ) - void collectionLocated( CollectionKey key ); - - @LogMessage( level = TRACE ) - @Message( value = "Collection [%s] not located in load context" ) - void collectionNotLocated( CollectionKey key ); - - @LogMessage( level = TRACE ) - @Message( value = "Constructing collection load context for result set [%s]" ) - void constructingCollectionLoadContext( ResultSet resultSet ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating collection wrapper: %s" ) - void creatingCollectionWrapper( String collectionInfoString ); - - @LogMessage( level = WARN ) - @Message( value = "Fail-safe cleanup (collections) : %s" ) - void failSafeCleanup( CollectionLoadContext collectionLoadContext ); - - @LogMessage( level = WARN ) - @Message( value = "Fail-safe cleanup (entities) : %s" ) - void failSafeCleanup( EntityLoadContext entityLoadContext ); - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to locate loading collection entry [%s] in any result-set context" ) - void locatingLoadingCollectionEntry( CollectionKey key ); - - @LogMessage( level = TRACE ) - @Message( value = "Returning loading collection: %s" ) - void returningLoadingCollection( String collectionInfoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/profile/FetchProfile.java b/hibernate-core/src/main/java/org/hibernate/engine/profile/FetchProfile.java index 88e4dd5c78..e69afddea6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/profile/FetchProfile.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/profile/FetchProfile.java @@ -23,17 +23,12 @@ */ package org.hibernate.engine.profile; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.util.HashMap; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.type.BagType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A 'fetch profile' allows a user to dynamically modify the fetching strategy used for particular associations at @@ -96,7 +91,7 @@ public class FetchProfile { public void addFetch(Fetch fetch) { Type associationType = fetch.getAssociation().getOwner().getPropertyType( fetch.getAssociation().getAssociationPath() ); if ( associationType.isCollectionType() ) { - LOG.addingFetch(fetch.getAssociation().getRole()); + LOG.trace("Handling request to add collection fetch [" + fetch.getAssociation().getRole() + "]"); // couple of things for which to account in the case of collection // join fetches @@ -170,23 +165,4 @@ public class FetchProfile { public boolean isContainsJoinFetchedBag() { return containsJoinFetchedBag; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Handling request to add collection fetch [%s]" ) - void addingFetch( String role ); - - @LogMessage( level = WARN ) - @Message( value = "Ignoring bag join fetch [%s] due to prior collection join fetch" ) - void containsJoinFetchedCollection( String role ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to erase previously added bag join fetch" ) - void unableToRemoveBagJoinFetch(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/HQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/HQLQueryPlan.java index e946987356..c152d7fbfa 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/HQLQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/query/HQLQueryPlan.java @@ -24,8 +24,6 @@ */ package org.hibernate.engine.query; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; @@ -35,6 +33,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.ScrollableResults; import org.hibernate.engine.QueryParameters; @@ -51,10 +50,6 @@ import org.hibernate.util.ArrayHelper; import org.hibernate.util.EmptyIterator; import org.hibernate.util.IdentitySet; import org.hibernate.util.JoinedIterator; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines a query execution plan for an HQL query (or filter). @@ -175,7 +170,7 @@ public class HQLQueryPlan implements Serializable { QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if (LOG.isTraceEnabled()) { - LOG.find(getSourceQuery()); + LOG.trace("Find: " + getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } boolean hasLimit = queryParameters.getRowSelection() != null && @@ -234,7 +229,7 @@ public class HQLQueryPlan implements Serializable { QueryParameters queryParameters, EventSource session) throws HibernateException { if (LOG.isTraceEnabled()) { - LOG.iterate(getSourceQuery()); + LOG.trace("Iterate: " + getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length == 0 ) { @@ -260,7 +255,7 @@ public class HQLQueryPlan implements Serializable { QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if (LOG.isTraceEnabled()) { - LOG.iterate(getSourceQuery()); + LOG.trace("Iterate: " + getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length != 1 ) { @@ -276,7 +271,7 @@ public class HQLQueryPlan implements Serializable { public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if (LOG.isTraceEnabled()) { - LOG.executeUpdate(getSourceQuery()); + LOG.trace("Execute update: " + getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } if (translators.length != 1) LOG.splitQueries(getSourceQuery(), translators.length); @@ -291,7 +286,7 @@ public class HQLQueryPlan implements Serializable { long start = System.currentTimeMillis(); ParamLocationRecognizer recognizer = ParamLocationRecognizer.parseLocations( hql ); long end = System.currentTimeMillis(); - LOG.hqlParamLocationRecognition(end - start, hql); + LOG.trace("HQL param location recognition took " + (end - start) + " mills (" + hql + ")"); int ordinalParamCount = parameterTranslations.getOrdinalParameterCount(); int[] locations = ArrayHelper.toIntArray( recognizer.getOrdinalParameterLocationList() ); @@ -336,37 +331,4 @@ public class HQLQueryPlan implements Serializable { System.arraycopy(translators, 0, copy, 0, copy.length); return copy; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Execute update: %s" ) - void executeUpdate( String sourceQuery ); - - @LogMessage( level = TRACE ) - @Message( value = "Find: %s" ) - void find( String sourceQuery ); - - @LogMessage( level = TRACE ) - @Message( value = "HQL param location recognition took %d mills (%s)" ) - void hqlParamLocationRecognition( long l, - String hql ); - - @LogMessage( level = TRACE ) - @Message( value = "Iterate: %s" ) - void iterate( String sourceQuery ); - - @LogMessage( level = WARN ) - @Message( value = "FirstResult/maxResults specified on polymorphic query; applying in memory!" ) - void needsLimit(); - - @LogMessage( level = WARN ) - @Message( value = "Manipulation query [%s] resulted in [%d] split queries" ) - void splitQueries( String sourceQuery, - int length ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/NativeSQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/NativeSQLQueryPlan.java index 876997dffd..d74d74b3d5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/NativeSQLQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/query/NativeSQLQueryPlan.java @@ -24,7 +24,6 @@ */ package org.hibernate.engine.query; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.SQLException; @@ -32,6 +31,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.action.BulkOperationCleanupAction; import org.hibernate.engine.QueryParameters; @@ -43,10 +43,6 @@ import org.hibernate.event.EventSource; import org.hibernate.loader.custom.sql.SQLCustomQuery; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines a query execution plan for a native-SQL query. @@ -157,7 +153,7 @@ public class NativeSQLQueryPlan implements Serializable { TypedValue typedval = (TypedValue) e.getValue(); int[] locs = getNamedParameterLocs( name ); for (int i = 0; i < locs.length; i++) { - LOG.bindNamedParameters(typedval.getValue(), name, locs[i] + start); + LOG.debug("bindNamedParameters() " + typedval.getValue() + " -> " + name + " [" + (locs[i] + start) + "]"); typedval.getType().nullSafeSet( ps, typedval.getValue(), locs[i] + start, session ); } @@ -220,17 +216,4 @@ public class NativeSQLQueryPlan implements Serializable { return result; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "bindNamedParameters() %s -> %s [%d]" ) - void bindNamedParameters( Object value, - String name, - int i ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java b/hibernate-core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java index 8a3363cb5b..29677dbd25 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java @@ -23,7 +23,6 @@ */ package org.hibernate.engine.query; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Collection; import java.util.Collections; @@ -32,6 +31,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.cfg.Environment; @@ -42,10 +42,6 @@ import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.util.CollectionHelper; import org.hibernate.util.SimpleMRUCache; import org.hibernate.util.SoftLimitMRUCache; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Acts as a cache for compiled query plans, as well as query-parameter metadata. @@ -120,9 +116,9 @@ public class QueryPlanCache implements Serializable { HQLQueryPlan plan = ( HQLQueryPlan ) planCache.get ( key ); if ( plan == null ) { - LOG.unableToLocateHqlQuery(queryString); + LOG.trace("Unable to locate HQL query plan in cache; generating (" + queryString + ")"); plan = new HQLQueryPlan(queryString, shallow, enabledFilters, factory ); - } else LOG.locatedHqlQuery(queryString); + } else LOG.trace("Located HQL query plan in cache (" + queryString + ")"); planCache.put( key, plan ); @@ -135,9 +131,10 @@ public class QueryPlanCache implements Serializable { FilterQueryPlan plan = ( FilterQueryPlan ) planCache.get ( key ); if ( plan == null ) { - LOG.unableToLocateCollectionFilter(collectionRole, filterString); + LOG.trace("Unable to locate collection-filter query plan in cache; generating (" + collectionRole + " : " + + filterString + ")"); plan = new FilterQueryPlan( filterString, collectionRole, shallow, enabledFilters, factory ); - } else LOG.locatedCollectionFilter(collectionRole, filterString); + } else LOG.trace("Located collection-filter query plan in cache (" + collectionRole + " : " + filterString + ")"); planCache.put( key, plan ); @@ -148,9 +145,9 @@ public class QueryPlanCache implements Serializable { NativeSQLQueryPlan plan = ( NativeSQLQueryPlan ) planCache.get( spec ); if ( plan == null ) { - LOG.unableToLocationNativeSqlQueryPlan(spec.getQueryString()); + LOG.trace("Unable to locate native-sql query plan in cache; generating (" + spec.getQueryString() + ")"); plan = new NativeSQLQueryPlan( spec, factory ); - } else LOG.locatedNativeSqlQueryPlan(spec.getQueryString()); + } else LOG.trace("Located native-sql query plan in cache (" + spec.getQueryString() + ")"); planCache.put( spec, plan ); return plan; @@ -345,37 +342,4 @@ public class QueryPlanCache implements Serializable { return hashCode; } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Located collection-filter query plan in cache (%s : %s)" ) - void locatedCollectionFilter( String collectionRole, - String filterString ); - - @LogMessage( level = TRACE ) - @Message( value = "Located HQL query plan in cache (%s)" ) - void locatedHqlQuery( String queryString ); - - @LogMessage( level = TRACE ) - @Message( value = "Located native-sql query plan in cache (%s)" ) - void locatedNativeSqlQueryPlan( String queryString ); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to locate collection-filter query plan in cache; generating (%s : %s)" ) - void unableToLocateCollectionFilter( String collectionRole, - String filterString ); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to locate HQL query plan in cache; generating (%s)" ) - void unableToLocateHqlQuery( String queryString ); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to locate native-sql query plan in cache; generating (%s)" ) - void unableToLocationNativeSqlQueryPlan( String queryString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/Isolater.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/Isolater.java index 822ea4a5fd..7002e0e8b1 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/Isolater.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/Isolater.java @@ -24,9 +24,6 @@ */ package org.hibernate.engine.transaction; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; import java.sql.Connection; import java.sql.SQLException; import javax.transaction.NotSupportedException; @@ -34,14 +31,9 @@ import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; -import org.hibernate.exception.JDBCExceptionHelper; -import org.hibernate.exception.SQLExceptionConverter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Class which provides the isolation semantics required by @@ -120,7 +112,7 @@ public class Isolater { try { // First we suspend any current JTA transaction Transaction surroundingTransaction = transactionManager.suspend(); - LOG.jtaTransactionSuspended(surroundingTransaction); + LOG.debug("Surrounding JTA transaction suspended [" + surroundingTransaction + "]"); boolean hadProblems = false; try { @@ -139,7 +131,7 @@ public class Isolater { finally { try { transactionManager.resume( surroundingTransaction ); - LOG.jtaTransactionResumed(surroundingTransaction); + LOG.debug("Surrounding JTA transaction resumed [" + surroundingTransaction + "]"); } catch( Throwable t ) { // if the actually work had an error use that, otherwise error based on t @@ -304,40 +296,4 @@ public class Isolater { return session.getFactory().getSQLExceptionHelper(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "On release of batch it still contained JDBC statements" ) - void batchContainedStatementsOnRelease(); - - @LogMessage( level = DEBUG ) - @Message( value = "Surrounding JTA transaction resumed [%s]" ) - void jtaTransactionResumed( Transaction surroundingTransaction ); - - @LogMessage( level = DEBUG ) - @Message( value = "Surrounding JTA transaction suspended [%s]" ) - void jtaTransactionSuspended( Transaction surroundingTransaction ); - - @LogMessage( level = INFO ) - @Message( value = "Unable to release isolated connection [%s]" ) - void unableToReleaseIsolatedConnection( Throwable ignore ); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to reset connection back to auto-commit" ) - void unableToResetConnectionToAutoCommit(); - - @LogMessage( level = INFO ) - @Message( value = "Unable to rollback connection on exception [%s]" ) - void unableToRollbackConnection( Exception ignore ); - - @LogMessage( level = INFO ) - @Message( value = "Unable to rollback isolated transaction on error [%s] : [%s]" ) - void unableToRollbackIsolatedTransaction( Exception e, - Exception ignore ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/SynchronizationRegistry.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/SynchronizationRegistry.java index f337cddf69..496ede391a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/SynchronizationRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/SynchronizationRegistry.java @@ -23,15 +23,10 @@ */ package org.hibernate.engine.transaction; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; import java.util.LinkedHashSet; import javax.transaction.Synchronization; import org.hibernate.HibernateException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * Manages a registry of {@link Synchronization Synchronizations}. @@ -100,20 +95,4 @@ public class SynchronizationRegistry { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Synchronization [%s] was already registered" ) - void synchronizationAlreadyRegistered( Synchronization synchronization ); - - @LogMessage( level = ERROR ) - @Message( value = "Exception calling user Synchronization [%s] : %s" ) - void synchronizationFailed( Synchronization synchronization, - Throwable t ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractFlushingEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractFlushingEventListener.java index 88b834148c..5b7fc7da9c 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractFlushingEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractFlushingEventListener.java @@ -24,14 +24,12 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.action.CollectionRecreateAction; import org.hibernate.action.CollectionRemoveAction; import org.hibernate.action.CollectionUpdateAction; @@ -54,10 +52,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.Printer; import org.hibernate.util.IdentityMap; import org.hibernate.util.LazyIterator; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A convenience base class for listeners whose functionality results in flushing. @@ -83,7 +77,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void flushEverythingToExecutions(FlushEvent event) throws HibernateException { - LOG.flushingSession(); + LOG.trace("Flushing session"); EventSource session = event.getSession(); @@ -110,14 +104,13 @@ public abstract class AbstractFlushingEventListener implements Serializable { //some statistics if (LOG.isDebugEnabled()) { - LOG.flushedEntities(session.getActionQueue().numberOfInsertions(), - session.getActionQueue().numberOfUpdates(), - session.getActionQueue().numberOfDeletions(), - persistenceContext.getEntityEntries().size()); - LOG.flushedCollections(session.getActionQueue().numberOfCollectionCreations(), - session.getActionQueue().numberOfCollectionUpdates(), - session.getActionQueue().numberOfCollectionRemovals(), - persistenceContext.getCollectionEntries().size()); + LOG.debug("Flushed: " + session.getActionQueue().numberOfInsertions() + " insertions, " + + session.getActionQueue().numberOfUpdates() + " updates, " + session.getActionQueue().numberOfDeletions() + + " deletions to " + persistenceContext.getEntityEntries().size() + " objects"); + LOG.debug("Flushed: " + session.getActionQueue().numberOfCollectionCreations() + " (re)creations, " + + session.getActionQueue().numberOfCollectionUpdates() + " updates, " + + session.getActionQueue().numberOfCollectionRemovals() + " removals to " + + persistenceContext.getCollectionEntries().size() + " collections"); new Printer( session.getFactory() ).toString( persistenceContext.getEntitiesByKey().values().iterator(), session.getEntityMode() @@ -132,7 +125,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ private void prepareEntityFlushes(EventSource session) throws HibernateException { - LOG.processingFlushTimeCascades(); + LOG.debug("Processing flush-time cascades"); final Map.Entry[] list = IdentityMap.concurrentEntries( session.getPersistenceContext().getEntityEntries() ); //safe from concurrent modification because of how entryList() is implemented on IdentityMap @@ -175,7 +168,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { // Initialize dirty flags for arrays + collections with composite elements // and reset reached, doupdate, etc. - LOG.dirtyCheckingCollections(); + LOG.debug("Dirty checking collections"); final List list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); final int size = list.size(); @@ -192,7 +185,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ private void flushEntities(FlushEvent event) throws HibernateException { - LOG.flushingEntitiesAndProcessingReferencedCollections(); + LOG.trace("Flushing entities and processing referenced collections"); // Among other things, updateReachables() will recursively load all // collections that are moving roles. This might cause entities to @@ -231,7 +224,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ private void flushCollections(EventSource session) throws HibernateException { - LOG.processingUnreferencedCollections(); + LOG.trace("Processing unreferenced collections"); List list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); int size = list.size(); @@ -245,7 +238,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { // Schedule updates to collections: - LOG.schedulingCollectionChanges(); + LOG.trace("Scheduling collection removes/(re)creates/updates"); list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); size = list.size(); @@ -311,7 +304,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void performExecutions(EventSource session) throws HibernateException { - LOG.flush(); + LOG.trace("Executing flush"); try { session.getJDBCContext().getConnectionManager().flushBeginning(); @@ -342,7 +335,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void postFlush(SessionImplementor session) throws HibernateException { - LOG.postFlush(); + LOG.trace("Post flush"); final PersistenceContext persistenceContext = session.getPersistenceContext(); persistenceContext.getCollectionsByKey().clear(); @@ -376,61 +369,4 @@ public abstract class AbstractFlushingEventListener implements Serializable { session.getInterceptor().postFlush( new LazyIterator( persistenceContext.getEntitiesByKey() ) ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Dirty checking collections" ) - void dirtyCheckingCollections(); - - @LogMessage( level = TRACE ) - @Message( value = "Executing flush" ) - void flush(); - - @LogMessage( level = DEBUG ) - @Message( value = "Flushed: %d (re)creations, %d updates, %d removals to %d collections" ) - void flushedCollections( int numberOfCollectionCreations, - int numberOfCollectionUpdates, - int numberOfCollectionRemovals, - int size ); - - @LogMessage( level = DEBUG ) - @Message( value = "Flushed: %d insertions, %d updates, %d deletions to %d objects" ) - void flushedEntities( int numberOfInsertions, - int numberOfUpdates, - int numberOfDeletions, - int size ); - - @LogMessage( level = TRACE ) - @Message( value = "Flushing entities and processing referenced collections" ) - void flushingEntitiesAndProcessingReferencedCollections(); - - @LogMessage( level = TRACE ) - @Message( value = "Flushing session" ) - void flushingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Post flush" ) - void postFlush(); - - @LogMessage( level = DEBUG ) - @Message( value = "Processing flush-time cascades" ) - void processingFlushTimeCascades(); - - @LogMessage( level = TRACE ) - @Message( value = "Processing unreferenced collections" ) - void processingUnreferencedCollections(); - - @LogMessage( level = TRACE ) - @Message( value = "Scheduling collection removes/(re)creates/updates" ) - void schedulingCollectionChanges(); - - @LogMessage( level = ERROR ) - @Message( value = "Could not synchronize database state with session: %s" ) - void unableToSynchronizeDatabaseStateWithSession( HibernateException he ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java index aaa2662ffd..7b759c41e2 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java @@ -24,9 +24,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.ObjectDeletedException; import org.hibernate.cache.CacheKey; import org.hibernate.cache.access.SoftLock; @@ -35,10 +35,6 @@ import org.hibernate.engine.Status; import org.hibernate.event.EventSource; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A convenience base class for listeners that respond to requests to perform a @@ -76,8 +72,9 @@ public class AbstractLockUpgradeEventListener extends AbstractReassociateEventLi final EntityPersister persister = entry.getPersister(); - if (LOG.isTraceEnabled()) LOG.locking(MessageHelper.infoString(persister, entry.getId(), source.getFactory()), - requestedLockMode); + if (LOG.isTraceEnabled()) LOG.trace("Locking " + + MessageHelper.infoString(persister, entry.getId(), source.getFactory()) + + " in mode: " + requestedLockMode); final SoftLock lock; final CacheKey ck; @@ -119,16 +116,4 @@ public class AbstractLockUpgradeEventListener extends AbstractReassociateEventLi } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Locking %s in mode: %s" ) - void locking( String infoString, - LockMode requestedLockMode ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractReassociateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractReassociateEventListener.java index 03c696e9d3..80e0043670 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractReassociateEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractReassociateEventListener.java @@ -23,9 +23,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityKey; import org.hibernate.engine.Status; @@ -35,10 +35,6 @@ import org.hibernate.event.EventSource; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.TypeHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A convenience base class for listeners that respond to requests to reassociate an entity @@ -64,9 +60,8 @@ public class AbstractReassociateEventListener implements Serializable { */ protected final EntityEntry reassociate(AbstractEvent event, Object object, Serializable id, EntityPersister persister) { - if (LOG.isTraceEnabled()) LOG.reassociatingTransientInstance(MessageHelper.infoString(persister, - id, - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Reassociating transient instance: " + + MessageHelper.infoString(persister, id, event.getSession().getFactory())); EventSource source = event.getSession(); EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); @@ -104,15 +99,4 @@ public class AbstractReassociateEventListener implements Serializable { return newEntry; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Reassociating transient instance: %s" ) - void reassociatingTransientInstance( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java index d7054eb18d..66308d8767 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java @@ -23,11 +23,10 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Map; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.NonUniqueObjectException; import org.hibernate.action.EntityIdentityInsertAction; import org.hibernate.action.EntityInsertAction; @@ -51,10 +50,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A convenience bas class for listeners responding to save events. @@ -133,9 +128,9 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent } else { // TODO: define toString()s for generators - if (LOG.isDebugEnabled()) LOG.generatedIdentifier(persister.getIdentifierType().toLoggableString(generatedId, - source.getFactory()), - persister.getIdentifierGenerator().getClass().getName()); + if (LOG.isDebugEnabled()) LOG.debug("Generated identifier: " + + persister.getIdentifierType().toLoggableString(generatedId, source.getFactory()) + + ", using strategy: " + persister.getIdentifierGenerator().getClass().getName()); return performSave( entity, generatedId, persister, false, anything, source, true ); } @@ -168,7 +163,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent EventSource source, boolean requiresImmediateIdAccess) { - if (LOG.isTraceEnabled()) LOG.saving(MessageHelper.infoString(persister, id, source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Saving " + MessageHelper.infoString(persister, id, source.getFactory())); EntityKey key; if ( !useIdentityColumn ) { @@ -207,9 +202,9 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent // Sub-insertions should occur before containing insertion so // Try to do the callback now if ( persister.implementsLifecycle( source.getEntityMode() ) ) { - LOG.callingOnSave(); + LOG.debug("Calling onSave()"); if ( ( ( Lifecycle ) entity ).onSave( source ) ) { - LOG.insertionVetoed(); + LOG.debug("Insertion vetoed by onSave()"); return true; } } @@ -274,7 +269,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent cascadeBeforeSave( source, persister, entity, anything ); if ( useIdentityColumn && !shouldDelayIdentityInserts ) { - LOG.executingInsertions(); + LOG.trace("Executing insertions"); source.getActionQueue().executeInserts(); } @@ -308,14 +303,14 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent values, entity, persister, source, shouldDelayIdentityInserts ); if ( !shouldDelayIdentityInserts ) { - LOG.executingIdentityInsert(); + LOG.debug("Executing identity-insert immediately"); source.getActionQueue().execute( insert ); id = insert.getGeneratedId(); key = new EntityKey( id, persister, source.getEntityMode() ); source.getPersistenceContext().checkUniqueness( key, entity ); } else { - LOG.delayingIdentityInsert(); + LOG.debug("Delaying identity-insert due to no transaction in progress"); source.getActionQueue().addAction( insert ); key = insert.getDelayedEntityKey(); } @@ -495,31 +490,25 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent //the entity is associated with the session, so check its status if ( entry.getStatus() != Status.DELETED ) { // do nothing for persistent instances - if (LOG.isTraceEnabled()) LOG.persistentInstanceOf(getLoggableName(entityName, entity)); + if (LOG.isTraceEnabled()) LOG.trace("Persistent instance of: " + getLoggableName(entityName, entity)); return PERSISTENT; } - else { - //ie. e.status==DELETED - if (LOG.isTraceEnabled()) LOG.deletedInstanceOf(getLoggableName(entityName, entity)); - return DELETED; - } + // ie. e.status==DELETED + if (LOG.isTraceEnabled()) LOG.trace("Deleted instance of: " + getLoggableName(entityName, entity)); + return DELETED; } - else { // the object is transient or detached + // the object is transient or detached - //the entity is not associated with the session, so - //try interceptor and unsaved-value - - if ( ForeignKeys.isTransient( entityName, entity, getAssumedUnsaved(), source ) ) { - if (LOG.isTraceEnabled()) LOG.transientInstanceOf(getLoggableName(entityName, entity)); - return TRANSIENT; - } - else { - if (LOG.isTraceEnabled()) LOG.detachedInstanceOf(getLoggableName(entityName, entity)); - return DETACHED; - } + // the entity is not associated with the session, so + // try interceptor and unsaved-value + if (ForeignKeys.isTransient(entityName, entity, getAssumedUnsaved(), source)) { + if (LOG.isTraceEnabled()) LOG.trace("Transient instance of: " + getLoggableName(entityName, entity)); + return TRANSIENT; } + if (LOG.isTraceEnabled()) LOG.trace("Detached instance of: " + getLoggableName(entityName, entity)); + return DETACHED; } protected String getLoggableName(String entityName, Object entity) { @@ -529,56 +518,4 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent protected Boolean getAssumedUnsaved() { return null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Calling onSave()" ) - void callingOnSave(); - - @LogMessage( level = DEBUG ) - @Message( value = "Delaying identity-insert due to no transaction in progress" ) - void delayingIdentityInsert(); - - @LogMessage( level = TRACE ) - @Message( value = "Deleted instance of: %s" ) - void deletedInstanceOf( String loggableName ); - - @LogMessage( level = TRACE ) - @Message( value = "Detached instance of: %s" ) - void detachedInstanceOf( String loggableName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Executing identity-insert immediately" ) - void executingIdentityInsert(); - - @LogMessage( level = TRACE ) - @Message( value = "Executing insertions" ) - void executingInsertions(); - - @LogMessage( level = DEBUG ) - @Message( value = "Generated identifier: %s, using strategy: %s" ) - void generatedIdentifier( String loggableString, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Insertion vetoed by onSave()" ) - void insertionVetoed(); - - @LogMessage( level = TRACE ) - @Message( value = "Persistent instance of: %s" ) - void persistentInstanceOf( String loggableName ); - - @LogMessage( level = TRACE ) - @Message( value = "Saving %s" ) - void saving( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Transient instance of: %s" ) - void transientInstanceOf( String loggableName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultAutoFlushEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultAutoFlushEventListener.java index cf555d0a23..866d07f0b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultAutoFlushEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultAutoFlushEventListener.java @@ -24,16 +24,12 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.FlushMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.event.AutoFlushEvent; import org.hibernate.event.AutoFlushEventListener; import org.hibernate.event.EventSource; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default flush event listeners used by hibernate for @@ -52,39 +48,27 @@ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener * @throws HibernateException */ public void onAutoFlush(AutoFlushEvent event) throws HibernateException { - final EventSource source = event.getSession(); - if ( flushMightBeNeeded(source) ) { - final int oldSize = source.getActionQueue().numberOfCollectionRemovals(); - flushEverythingToExecutions(event); - if ( flushIsReallyNeeded(event, source) ) { - - LOG.needToExecuteFlush(); + LOG.trace("Need to execute flush"); performExecutions(source); postFlush(source); // note: performExecutions() clears all collectionXxxxtion // collections (the collection actions) in the session - if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { - source.getFactory().getStatisticsImplementor().flush(); - } - + if (source.getFactory().getStatistics().isStatisticsEnabled()) source.getFactory().getStatisticsImplementor().flush(); } else { - - LOG.dontNeedToExecuteFlush(); + LOG.trace("Don't need to execute flush"); source.getActionQueue().clearFromFlushNeededCheck( oldSize ); } event.setFlushRequired( flushIsReallyNeeded( event, source ) ); - } - } private boolean flushIsReallyNeeded(AutoFlushEvent event, final EventSource source) { @@ -99,19 +83,4 @@ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener ( source.getPersistenceContext().getEntityEntries().size() > 0 || source.getPersistenceContext().getCollectionEntries().size() > 0 ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Don't need to execute flush" ) - void dontNeedToExecuteFlush(); - - @LogMessage( level = TRACE ) - @Message( value = "Need to execute flush" ) - void needToExecuteFlush(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java index c8f7f62cb9..a9675dcc90 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java @@ -23,14 +23,12 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Set; import org.hibernate.CacheMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.TransientObjectException; import org.hibernate.action.EntityDeleteAction; import org.hibernate.classic.Lifecycle; @@ -50,10 +48,6 @@ import org.hibernate.pretty.MessageHelper; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; import org.hibernate.util.IdentitySet; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default delete event listener used by hibernate for deleting entities @@ -98,7 +92,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener { final Object version; if ( entityEntry == null ) { - LOG.entityNotpersistentInDeleteProcessing(); + LOG.trace("Entity was not persistent in delete processing"); persister = source.getEntityPersister( event.getEntityName(), entity ); @@ -107,9 +101,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener { // EARLY EXIT!!! return; } - else { - performDetachedEntityDeletionCheck( event ); - } + performDetachedEntityDeletionCheck(event); id = persister.getIdentifier( entity, source ); @@ -141,10 +133,10 @@ public class DefaultDeleteEventListener implements DeleteEventListener { ); } else { - LOG.deletingPersistentInstance(); + LOG.trace("Deleting a persistent instance"); if ( entityEntry.getStatus() == Status.DELETED || entityEntry.getStatus() == Status.GONE ) { - LOG.objectAlreadyDeleted(); + LOG.trace("Object was already deleted"); return; } persister = entityEntry.getPersister(); @@ -206,7 +198,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener { Set transientEntities) { LOG.handlingTransientEntity(); if ( transientEntities.contains( entity ) ) { - LOG.alreadyHandledTransientEntity(); + LOG.trace("Already handled transient entity; skipping"); return; } transientEntities.add( entity ); @@ -234,7 +226,8 @@ public class DefaultDeleteEventListener implements DeleteEventListener { final EntityPersister persister, final Set transientEntities) { - if (LOG.isTraceEnabled()) LOG.deleting(MessageHelper.infoString(persister, entityEntry.getId(), session.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Deleting " + + MessageHelper.infoString(persister, entityEntry.getId(), session.getFactory())); final PersistenceContext persistenceContext = session.getPersistenceContext(); final Type[] propTypes = persister.getPropertyTypes(); @@ -303,9 +296,9 @@ public class DefaultDeleteEventListener implements DeleteEventListener { protected boolean invokeDeleteLifecycle(EventSource session, Object entity, EntityPersister persister) { if ( persister.implementsLifecycle( session.getEntityMode() ) ) { - LOG.callingOnDelete(); + LOG.debug("Calling onDelete()"); if ( ( ( Lifecycle ) entity ).onDelete( session ) ) { - LOG.deletionVetoed(); + LOG.debug("Deletion vetoed by onDelete()"); return true; } } @@ -352,43 +345,4 @@ public class DefaultDeleteEventListener implements DeleteEventListener { session.setCacheMode( cacheMode ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Already handled transient entity; skipping" ) - void alreadyHandledTransientEntity(); - - @LogMessage( level = DEBUG ) - @Message( value = "Calling onDelete()" ) - void callingOnDelete(); - - @LogMessage( level = TRACE ) - @Message( value = "Deleting %s" ) - void deleting( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Deleting a persistent instance" ) - void deletingPersistentInstance(); - - @LogMessage( level = DEBUG ) - @Message( value = "Deletion vetoed by onDelete()" ) - void deletionVetoed(); - - @LogMessage( level = TRACE ) - @Message( value = "Entity was not persistent in delete processing" ) - void entityNotpersistentInDeleteProcessing(); - - @LogMessage( level = INFO ) - @Message( value = "Handling transient entity in delete processing" ) - void handlingTransientEntity(); - - @LogMessage( level = TRACE ) - @Message( value = "Object was already deleted" ) - void objectAlreadyDeleted(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDirtyCheckEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDirtyCheckEventListener.java index 434e2d14c1..c8f3fad721 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDirtyCheckEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultDirtyCheckEventListener.java @@ -24,14 +24,10 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.event.DirtyCheckEvent; import org.hibernate.event.DirtyCheckEventListener; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default dirty-check event listener used by hibernate for @@ -57,8 +53,8 @@ public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListene try { flushEverythingToExecutions(event); boolean wasNeeded = event.getSession().getActionQueue().hasAnyQueuedActions(); - if (wasNeeded) LOG.sessionDirty(); - else LOG.sessionNotDirty(); + if (wasNeeded) LOG.debug("Session dirty"); + else LOG.debug("Session not dirty"); event.setDirty( wasNeeded ); } finally { @@ -66,19 +62,4 @@ public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListene } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Session dirty" ) - void sessionDirty(); - - @LogMessage( level = DEBUG ) - @Message( value = "Session not dirty" ) - void sessionNotDirty(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultEvictEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultEvictEventListener.java index 37d7e7f150..70d672ca1c 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultEvictEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultEvictEventListener.java @@ -24,9 +24,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.Cascade; import org.hibernate.engine.CascadingAction; import org.hibernate.engine.EntityEntry; @@ -39,10 +39,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default evict event listener used by hibernate for evicting entities @@ -104,7 +100,7 @@ public class DefaultEvictEventListener implements EvictEventListener { final EventSource session) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.evicting(MessageHelper.infoString(persister)); + if (LOG.isTraceEnabled()) LOG.trace("Evicting " + MessageHelper.infoString(persister)); // remove all collections for the entity from the session-level cache if ( persister.hasCollections() ) { @@ -120,15 +116,4 @@ public class DefaultEvictEventListener implements EvictEventListener { new Cascade( CascadingAction.EVICT, Cascade.AFTER_EVICT, session ) .cascade( persister, object ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Evicting %s" ) - void evicting( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java index c403483e91..20102dd926 100755 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultFlushEntityEventListener.java @@ -24,11 +24,11 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.StaleObjectStateException; import org.hibernate.action.DelayedPostInsertIdentifier; import org.hibernate.action.EntityUpdateAction; @@ -47,10 +47,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An event that occurs for each entity instance at flush time @@ -256,15 +252,15 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener if (LOG.isTraceEnabled()) { if ( status == Status.DELETED ) { - if (!persister.isMutable()) LOG.updatingImmutableDeletedEntity(MessageHelper.infoString(persister, - entry.getId(), - session.getFactory())); - else if (!entry.isModifiableEntity()) LOG.updatingNonModifiableDeletedEntity(MessageHelper.infoString(persister, - entry.getId(), - session.getFactory())); - else LOG.updatingDeletedEntity(MessageHelper.infoString(persister, entry.getId(), session.getFactory())); - } - else LOG.updatingEntity(MessageHelper.infoString(persister, entry.getId(), session.getFactory())); + if (!persister.isMutable()) LOG.trace("Updating immutable, deleted entity: " + + MessageHelper.infoString(persister, entry.getId(), session.getFactory())); + else if (!entry.isModifiableEntity()) LOG.trace("Updating non-modifiable, deleted entity: " + + MessageHelper.infoString(persister, + entry.getId(), + session.getFactory())); + else LOG.trace("Updating deleted entity: " + + MessageHelper.infoString(persister, entry.getId(), session.getFactory())); + } else LOG.trace("Updating entity: " + MessageHelper.infoString(persister, entry.getId(), session.getFactory())); } final boolean intercepted; @@ -558,7 +554,8 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener for ( int i = 0; i < dirtyProperties.length; i++ ) { dirtyPropertyNames[i] = allPropertyNames[ dirtyProperties[i]]; } - LOG.foundDirtyProperties(MessageHelper.infoString(persister.getEntityName(), id), dirtyPropertyNames); + LOG.trace("Found dirty properties [" + MessageHelper.infoString(persister.getEntityName(), id) + "] : " + + dirtyPropertyNames); } } @@ -580,32 +577,4 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener EntityKey entityKey = new EntityKey(id, persister, session.getEntityMode()); return session.getPersistenceContext().getCachedDatabaseSnapshot(entityKey); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Found dirty properties [%s] : %s" ) - void foundDirtyProperties( String infoString, - String[] dirtyPropertyNames ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating deleted entity: %s" ) - void updatingDeletedEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating entity: %s" ) - void updatingEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating immutable, deleted entity: %s" ) - void updatingImmutableDeletedEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating non-modifiable, deleted entity: %s" ) - void updatingNonModifiableDeletedEntity( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultInitializeCollectionEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultInitializeCollectionEventListener.java index e399561aae..1bb7f145ee 100755 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultInitializeCollectionEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultInitializeCollectionEventListener.java @@ -24,9 +24,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cache.CacheKey; import org.hibernate.cache.entry.CollectionCacheEntry; import org.hibernate.collection.PersistentCollection; @@ -38,10 +38,6 @@ import org.hibernate.event.InitializeCollectionEvent; import org.hibernate.event.InitializeCollectionEventListener; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Gavin King @@ -63,11 +59,12 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle CollectionEntry ce = source.getPersistenceContext().getCollectionEntry(collection); if (ce==null) throw new HibernateException("collection was evicted"); if ( !collection.wasInitialized() ) { - if (LOG.isTraceEnabled()) LOG.initializingCollection(MessageHelper.collectionInfoString(ce.getLoadedPersister(), - ce.getLoadedKey(), - source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Initializing collection " + + MessageHelper.collectionInfoString(ce.getLoadedPersister(), + ce.getLoadedKey(), + source.getFactory())); - LOG.checkingSecondLevelCache(); + LOG.trace("Checking second-level cache"); final boolean foundInCache = initializeCollectionFromCache( ce.getLoadedKey(), ce.getLoadedPersister(), @@ -75,11 +72,11 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle source ); - if (foundInCache) LOG.collectionInitializedFromCache(); + if (foundInCache) LOG.trace("Collection initialized from cache"); else { - LOG.collectionNotCached(); + LOG.trace("Collection not cached"); ce.getLoadedPersister().initialize( ce.getLoadedKey(), source ); - LOG.collectionInitialized(); + LOG.trace("Collection initialized"); if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { source.getFactory().getStatisticsImplementor().fetchCollection( @@ -107,7 +104,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle SessionImplementor source) { if ( !source.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) { - LOG.ignoringCachedVersionOfCollection(); + LOG.trace("Disregarding cached version (if any) of collection due to enabled filters"); return false; } @@ -143,35 +140,4 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle // addInitializedCollection(collection, persister, id); return true; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Checking second-level cache" ) - void checkingSecondLevelCache(); - - @LogMessage( level = TRACE ) - @Message( value = "Collection initialized" ) - void collectionInitialized(); - - @LogMessage( level = TRACE ) - @Message( value = "Collection initialized from cache" ) - void collectionInitializedFromCache(); - - @LogMessage( level = TRACE ) - @Message( value = "Collection not cached" ) - void collectionNotCached(); - - @LogMessage( level = TRACE ) - @Message( value = "Disregarding cached version (if any) of collection due to enabled filters " ) - void ignoringCachedVersionOfCollection(); - - @LogMessage( level = TRACE ) - @Message( value = "Initializing collection %s" ) - void initializingCollection( String collectionInfoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java index dfcd3ef5d0..63d5c152a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java @@ -23,13 +23,11 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.NonUniqueObjectException; import org.hibernate.PersistentObjectException; import org.hibernate.TypeMismatchException; @@ -57,10 +55,6 @@ import org.hibernate.type.EmbeddedComponentType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default load event listeners used by hibernate for loading entities @@ -262,33 +256,21 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EntityKey keyToLoad, final LoadEventListener.LoadType options) { - if (LOG.isTraceEnabled()) LOG.loadingEntity(MessageHelper.infoString(persister, + if (LOG.isTraceEnabled()) LOG.trace("Loading entity: " + + MessageHelper.infoString(persister, event.getEntityId(), event.getSession().getFactory())); - if ( !persister.hasProxy() ) { - // this class has no proxies (so do a shortcut) - return load(event, persister, keyToLoad, options); - } - else { - final PersistenceContext persistenceContext = event.getSession().getPersistenceContext(); + // this class has no proxies (so do a shortcut) + if (!persister.hasProxy()) return load(event, persister, keyToLoad, options); + final PersistenceContext persistenceContext = event.getSession().getPersistenceContext(); - // look for a proxy - Object proxy = persistenceContext.getProxy(keyToLoad); - if ( proxy != null ) { - return returnNarrowedProxy( event, persister, keyToLoad, options, persistenceContext, proxy ); - } - else { - if ( options.isAllowProxyCreation() ) { - return createProxyIfNecessary( event, persister, keyToLoad, options, persistenceContext ); - } - else { - // return a newly loaded object - return load(event, persister, keyToLoad, options); - } - } - - } + // look for a proxy + Object proxy = persistenceContext.getProxy(keyToLoad); + if (proxy != null) return returnNarrowedProxy(event, persister, keyToLoad, options, persistenceContext, proxy); + if (options.isAllowProxyCreation()) return createProxyIfNecessary(event, persister, keyToLoad, options, persistenceContext); + // return a newly loaded object + return load(event, persister, keyToLoad, options); } /** @@ -310,7 +292,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final LoadEventListener.LoadType options, final PersistenceContext persistenceContext, final Object proxy) { - LOG.entityProxyFoundInSessionCache(); + LOG.trace("Entity proxy found in session cache"); LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer(); if ( li.isUnwrap() ) { return li.getImplementation(); @@ -346,7 +328,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i Object existing = persistenceContext.getEntity( keyToLoad ); if ( existing != null ) { // return existing object or initialized proxy (unless deleted) - LOG.entityFoundInSessionCache(); + LOG.trace("Entity found in session cache"); if ( options.isCheckDeleted() ) { EntityEntry entry = persistenceContext.getEntry( existing ); Status status = entry.getStatus(); @@ -356,14 +338,12 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i } return existing; } - else { - LOG.creatingNewProxyForEntity(); - // return new uninitialized proxy - Object proxy = persister.createProxy( event.getEntityId(), event.getSession() ); - persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(keyToLoad); - persistenceContext.addProxy(keyToLoad, proxy); - return proxy; - } + LOG.trace("Creating new proxy for entity"); + // return new uninitialized proxy + Object proxy = persister.createProxy(event.getEntityId(), event.getSession()); + persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(keyToLoad); + persistenceContext.addProxy(keyToLoad, proxy); + return proxy; } /** @@ -432,37 +412,41 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EntityKey keyToLoad, final LoadEventListener.LoadType options) { - if (LOG.isTraceEnabled()) LOG.attemptingToResolve(MessageHelper.infoString(persister, - event.getEntityId(), - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Attempting to resolve: " + + MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); Object entity = loadFromSessionCache( event, keyToLoad, options ); if ( entity == REMOVED_ENTITY_MARKER ) { - LOG.entityScheduledForRemoval(); + LOG.debug("Load request found matching entity in context, but it is scheduled for removal; returning null"); return null; } if ( entity == INCONSISTENT_RTN_CLASS_MARKER ) { - LOG.entityHasInconsistentReturnType(); + LOG.debug("Load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null"); return null; } if ( entity != null ) { - if (LOG.isTraceEnabled()) LOG.resolvedObjectInSessionCache(MessageHelper.infoString(persister, - event.getEntityId(), - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Resolved object in session cache: " + + MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return entity; } entity = loadFromSecondLevelCache(event, persister, options); if ( entity != null ) { - if (LOG.isTraceEnabled()) LOG.resolvedObjectInSecondLevelCache(MessageHelper.infoString(persister, - event.getEntityId(), - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Resolved object in second-level cache: " + + MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return entity; } - if (LOG.isTraceEnabled()) LOG.objectNotResolvedInAnyCache(MessageHelper.infoString(persister, - event.getEntityId(), - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Object not resolved in any cache: " + + MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return loadFromDatasource(event, persister, keyToLoad, options); } @@ -614,7 +598,8 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EventSource session = event.getSession(); final SessionFactoryImplementor factory = session.getFactory(); - if (LOG.isTraceEnabled()) LOG.assemblingEntityFromSecondLevelCache(MessageHelper.infoString(persister, id, factory)); + if (LOG.isTraceEnabled()) LOG.trace("Assembling entity from second-level cache: " + + MessageHelper.infoString(persister, id, factory)); EntityPersister subclassPersister = factory.getEntityPersister( entry.getSubclass() ); Object result = optionalObject == null ? @@ -643,7 +628,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i ); Object version = Versioning.getVersion( values, subclassPersister ); - if (LOG.isTraceEnabled()) LOG.cachedVersion(version); + if (LOG.isTraceEnabled()) LOG.trace("Cached Version: " + version); final PersistenceContext persistenceContext = session.getPersistenceContext(); boolean isReadOnly = session.isDefaultReadOnly(); @@ -687,63 +672,4 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i return result; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Assembling entity from second-level cache: %s" ) - void assemblingEntityFromSecondLevelCache( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to resolve: %s" ) - void attemptingToResolve( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Cached Version: %s" ) - void cachedVersion( Object version ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating new proxy for entity" ) - void creatingNewProxyForEntity(); - - @LogMessage( level = TRACE ) - @Message( value = "Entity found in session cache" ) - void entityFoundInSessionCache(); - - @LogMessage( level = DEBUG ) - @Message( value = "Load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null" ) - void entityHasInconsistentReturnType(); - - @LogMessage( level = TRACE ) - @Message( value = "Entity proxy found in session cache" ) - void entityProxyFoundInSessionCache(); - - @LogMessage( level = DEBUG ) - @Message( value = "Load request found matching entity in context, but it is scheduled for removal; returning null" ) - void entityScheduledForRemoval(); - - @LogMessage( level = TRACE ) - @Message( value = "Loading entity: %s" ) - void loadingEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Object not resolved in any cache: %s" ) - void objectNotResolvedInAnyCache( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Resolved object in second-level cache: %s" ) - void resolvedObjectInSecondLevelCache( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Resolved object in session cache: %s" ) - void resolvedObjectInSessionCache( String infoString ); - - @LogMessage( level = INFO ) - @Message( value = "Error performing load command : %s" ) - void unableToLoadCommand( HibernateException e ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java index 996594be30..1aec658858 100755 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java @@ -24,7 +24,6 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; @@ -54,10 +53,6 @@ import org.hibernate.proxy.LazyInitializer; import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default copy event listener used by hibernate for copying entities @@ -101,18 +96,15 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener Object transientEntity = ( ( Map.Entry ) it.next() ).getKey(); String transientEntityName = event.getSession().guessEntityName( transientEntity ); transientEntityNames.add( transientEntityName ); - LOG.transientInstanceNotProcessedDueToNullability(transientEntityName, transientEntity); + LOG.trace("Transient instance could not be processed by merge when checking nullability: " + + transientEntityName + "[" + transientEntity + "]"); } - if ( isNullabilityCheckedGlobal( event.getSession() ) ) { - throw new TransientObjectException( + if (isNullabilityCheckedGlobal(event.getSession())) throw new TransientObjectException( "one or more objects is an unsaved transient instance - save transient instance(s) before merging: " + transientEntityNames ); - } - else { - LOG.retrySavingTransientInstancesIgnoringNullability(); - // failures will be detected later... - retryMergeTransientEntities( event, transientCopyCache, copyCache, false ); - } + LOG.trace("Retry saving transient instances without checking nullability"); + // failures will be detected later... + retryMergeTransientEntities(event, transientCopyCache, copyCache, false); } } copyCache.clear(); @@ -132,7 +124,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( copyEntry == null ) { // entity name will not be available for non-POJO entities // TODO: cache the entity name somewhere so that it is available to this exception - LOG.transientInstanceNotProcessed(event.getSession().guessEntityName(copy), entity); + LOG.trace("Transient instance could not be processed by merge: " + event.getSession().guessEntityName(copy) + "[" + + entity + "]"); // merge did not cascade to this entity; it's in copyCache because a // different entity has a non-nullable reference to this entity; // this entity should not be put in transientCopyCache, because it was @@ -201,7 +194,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( original instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) original ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { - LOG.ignoringUninitializedProxy(); + LOG.trace("Ignoring uninitialized proxy"); event.setResult( source.load( li.getEntityName(), li.getIdentifier() ) ); return; //EARLY EXIT! } @@ -215,12 +208,12 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( copyCache.containsKey( entity ) && ( copyCache.isOperatedOn( entity ) ) ) { - LOG.alreadyInMergeProcess(); + LOG.trace("Already in merge process"); event.setResult( entity ); } else { if ( copyCache.containsKey( entity ) ) { - LOG.alreadyInCopyCache(); + LOG.trace("Already in copyCache; setting in merge process"); copyCache.setOperatedOn( entity, true ); } event.setEntity( entity ); @@ -275,7 +268,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } protected void entityIsPersistent(MergeEvent event, Map copyCache) { - LOG.ignoringPersistentInstance(); + LOG.trace("Ignoring persistent instance"); //TODO: check that entry.getIdentifier().equals(requestedId) @@ -293,7 +286,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener protected void entityIsTransient(MergeEvent event, Map copyCache) { - LOG.mergingTransientInstance(); + LOG.trace("Merging transient instance"); final Object entity = event.getEntity(); final EventSource source = event.getSession(); @@ -316,7 +309,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener Map copyCache, boolean isNullabilityChecked) { - LOG.mergingTransientInstance(); + LOG.trace("Merging transient instance"); final EntityPersister persister = source.getEntityPersister( entityName, entity ); @@ -351,35 +344,39 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener propertyFromEntity == null || ! propertyType.isEntityType() || ! copyCache.containsKey( propertyFromEntity ) ) { - if ( log.isTraceEnabled() ) { - String fullPropertyName = "property '" + copyEntry.getEntityName() + "." + propertyName; - log.trace( fullPropertyName + " in copy is " + ( propertyFromCopy == null ? "null" : propertyFromCopy ) ); - log.trace( fullPropertyName + " in original is " + ( propertyFromCopy == null ? "null" : propertyFromCopy ) ); - log.trace( fullPropertyName + ( propertyType.isEntityType() ? " is" : " is not" ) + " an entity type" ); - if ( propertyFromEntity != null && ! copyCache.containsKey( propertyFromEntity ) ) { - log.trace( fullPropertyName + " is not in copy cache" ); - } - } - if ( isNullabilityCheckedGlobal( source ) ) { - throw ex; - } - else { - // retry save w/o checking for non-nullable properties - // (the failure will be detected later) - saveTransientEntity( copy, entityName, requestedId, source, copyCache, false ); + if ( LOG.isTraceEnabled() ) { + LOG.trace("Property '" + copyEntry.getEntityName() + "." + propertyName + "' in copy is " + + (propertyFromCopy == null ? "null" : propertyFromCopy)); + LOG.trace("Property '" + copyEntry.getEntityName() + "." + propertyName + "' in original is " + + (propertyFromCopy == null ? "null" : propertyFromCopy)); + LOG.trace("Property '" + copyEntry.getEntityName() + "." + propertyName + "' is" + + (propertyType.isEntityType() ? "" : " not") + " an entity type"); + if (propertyFromEntity != null && !copyCache.containsKey(propertyFromEntity)) LOG.trace("Property '" + + copyEntry.getEntityName() + + "." + + propertyName + + "' is not in copy cache"); + } + if ( isNullabilityCheckedGlobal( source ) ) { + throw ex; + } + else { + // retry save w/o checking for non-nullable properties + // (the failure will be detected later) + saveTransientEntity( copy, entityName, requestedId, source, copyCache, false ); } } - if ( log.isTraceEnabled() && propertyFromEntity != null ) { - if ( ( ( EventCache ) copyCache ).isOperatedOn( propertyFromEntity ) ) { - log.trace( "property '" + copyEntry.getEntityName() + "." + propertyName + - "' from original entity is in copyCache and is in the process of being merged; " + - propertyName + " =["+propertyFromEntity+"]"); - } - else { - log.trace( "property '" + copyEntry.getEntityName() + "." + propertyName + - "' from original entity is in copyCache and is not in the process of being merged; " + - propertyName + " =["+propertyFromEntity+"]"); - } + if ( LOG.isTraceEnabled() && propertyFromEntity != null ) { + if (((EventCache)copyCache).isOperatedOn(propertyFromEntity)) LOG.trace("Property '" + + copyEntry.getEntityName() + + "." + + propertyName + + "' from original entity is in copyCache and is in the process of being merged; " + + propertyName + " =[" + propertyFromEntity + + "]"); + else LOG.trace("Property '" + copyEntry.getEntityName() + "." + propertyName + + "' from original entity is in copyCache and is not in the process of being merged; " + + propertyName + " =[" + propertyFromEntity + "]"); } // continue...; we'll find out if it ends up not getting saved later } @@ -425,7 +422,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } protected void entityIsDetached(MergeEvent event, Map copyCache) { - LOG.mergingDetachedInstance(); + LOG.trace("Merging detached instance"); final Object entity = event.getEntity(); final EventSource source = event.getSession(); @@ -662,77 +659,4 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener protected void cascadeBeforeSave(EventSource source, EntityPersister persister, Object entity, Object anything) throws HibernateException { } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Already in copyCache; setting in merge process" ) - void alreadyInCopyCache(); - - @LogMessage( level = TRACE ) - @Message( value = "Already in merge process" ) - void alreadyInMergeProcess(); - - @LogMessage( level = TRACE ) - @Message( value = "Ignoring persistent instance" ) - void ignoringPersistentInstance(); - - @LogMessage( level = TRACE ) - @Message( value = "Ignoring uninitialized proxy" ) - void ignoringUninitializedProxy(); - - @LogMessage( level = TRACE ) - @Message( value = "Merging detached instance" ) - void mergingDetachedInstance(); - - @LogMessage( level = TRACE ) - @Message( value = "Merging transient instance" ) - void mergingTransientInstance(); - - @LogMessage( level = TRACE ) - @Message( value = "Property '%s.%s' from original entity is in copyCache and is in the process of being merged; %s =[%s]" ) - void propertyBeingMerged( String entityName, - String propertyName, - String propertyName2, - Object propertyFromEntity ); - - @LogMessage( level = TRACE ) - @Message( value = "Property '%s.%s' from original entity is in copyCache and is not in the process of being merged; %s =[%s]" ) - void propertyNotBeingMerged( String entityName, - String propertyName, - String propertyName2, - Object propertyFromEntity ); - - @LogMessage( level = TRACE ) - @Message( value = "Property '%s.%s' from original entity is not in copyCache; %s =[%s]" ) - void propertyNotInCopyCache( String entityName, - String propertyName, - String propertyName2, - Object propertyFromEntity ); - - @LogMessage( level = TRACE ) - @Message( value = "Property '%s.%s' is null or not an entity; %s =[%s]" ) - void propertyNullOrNotAnEntity( String entityName, - String propertyName, - String propertyName2, - Object propertyFromCopy ); - - @LogMessage( level = TRACE ) - @Message( value = "Retry saving transient instances without checking nullability" ) - void retrySavingTransientInstancesIgnoringNullability(); - - @LogMessage( level = TRACE ) - @Message( value = "Transient instance could not be processed by merge: %s[%s]" ) - void transientInstanceNotProcessed( String guessEntityName, - Object entity ); - - @LogMessage( level = TRACE ) - @Message( value = "Transient instance could not be processed by merge when checking nullability: %s[%s]" ) - void transientInstanceNotProcessedDueToNullability( String transientEntityName, - Object transientEntity ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultPersistEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultPersistEventListener.java index 0375892d2a..771cff4b50 100755 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultPersistEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultPersistEventListener.java @@ -23,10 +23,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.ObjectDeletedException; import org.hibernate.PersistentObjectException; import org.hibernate.engine.CascadingAction; @@ -40,10 +39,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import org.hibernate.util.IdentityMap; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default create event listener used by hibernate for creating @@ -117,7 +112,7 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple // NOTE: entityEntry must be null to get here, so we cannot use any of its values EntityPersister persister = source.getFactory().getEntityPersister( entityName ); if ( ForeignGenerator.class.isInstance( persister.getIdentifierGenerator() ) ) { - if (LOG.isDebugEnabled() && persister.getIdentifier(entity, source) != null) LOG.resettingEntityIdAttributeToNull(); + if (LOG.isDebugEnabled() && persister.getIdentifier(entity, source) != null) LOG.debug("Resetting entity id attribute to null for foreign generator"); persister.setIdentifier( entity, null, source ); entityState = getEntityState( entity, entityName, entityEntry, source ); } @@ -146,7 +141,7 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple } protected void entityIsPersistent(PersistEvent event, Map createCache) { - LOG.ignoringPersistentInstance(); + LOG.trace("Ignoring persistent instance"); final EventSource source = event.getSession(); //TODO: check that entry.getIdentifier().equals(requestedId) @@ -170,7 +165,7 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple */ protected void entityIsTransient(PersistEvent event, Map createCache) throws HibernateException { - LOG.savingTransientInstance(); + LOG.trace("Saving transient instance"); final EventSource source = event.getSession(); @@ -191,23 +186,4 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple protected Boolean getAssumedUnsaved() { return Boolean.TRUE; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Ignoring persistent instance" ) - void ignoringPersistentInstance(); - - @LogMessage( level = DEBUG ) - @Message( value = "Resetting entity id attribute to null for foreign generator" ) - void resettingEntityIdAttributeToNull(); - - @LogMessage( level = TRACE ) - @Message( value = "Saving transient instance" ) - void savingTransientInstance(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java index f33923796b..e613f4ef10 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java @@ -23,10 +23,10 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.PersistentObjectException; import org.hibernate.UnresolvableObjectException; import org.hibernate.cache.CacheKey; @@ -44,10 +44,6 @@ import org.hibernate.type.CollectionType; import org.hibernate.type.CompositeType; import org.hibernate.type.Type; import org.hibernate.util.IdentityMap; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default refresh event listener used by hibernate for refreshing entities @@ -84,7 +80,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener { final Object object = source.getPersistenceContext().unproxyAndReassociate( event.getObject() ); if ( refreshedAlready.containsKey(object) ) { - LOG.alreadyRefreshed(); + LOG.trace("Already refreshed"); return; } @@ -95,7 +91,8 @@ public class DefaultRefreshEventListener implements RefreshEventListener { if ( e == null ) { persister = source.getEntityPersister(null, object); //refresh() does not pass an entityName id = persister.getIdentifier( object, event.getSession() ); - if (LOG.isTraceEnabled()) LOG.refreshingTransient(MessageHelper.infoString(persister, id, source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Refreshing transient " + + MessageHelper.infoString(persister, id, source.getFactory())); EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); if ( source.getPersistenceContext().getEntry(key) != null ) { throw new PersistentObjectException( @@ -105,7 +102,8 @@ public class DefaultRefreshEventListener implements RefreshEventListener { } } else { - if (LOG.isTraceEnabled()) LOG.refreshing(MessageHelper.infoString(e.getPersister(), e.getId(), source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Refreshing " + + MessageHelper.infoString(e.getPersister(), e.getId(), source.getFactory())); if ( !e.isExistsInDatabase() ) { throw new HibernateException( "this instance does not yet exist as a row in the database" ); } @@ -174,23 +172,4 @@ public class DefaultRefreshEventListener implements RefreshEventListener { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Already refreshed" ) - void alreadyRefreshed(); - - @LogMessage( level = TRACE ) - @Message( value = "Refreshing %s" ) - void refreshing( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Refreshing transient %s" ) - void refreshingTransient( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultReplicateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultReplicateEventListener.java index 7c51f1cc10..3f5c984d7f 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultReplicateEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultReplicateEventListener.java @@ -24,10 +24,10 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.ReplicationMode; import org.hibernate.TransientObjectException; import org.hibernate.engine.Cascade; @@ -41,10 +41,6 @@ import org.hibernate.event.ReplicateEventListener; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default replicate event listener used by Hibernate to replicate @@ -67,14 +63,14 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp public void onReplicate(ReplicateEvent event) { final EventSource source = event.getSession(); if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) { - LOG.uninitializedProxy(); + LOG.trace("Uninitialized proxy passed to replicate()"); return; } Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() ); if ( source.getPersistenceContext().isEntryFor( entity ) ) { - LOG.ignoringPersistentInstance(); + LOG.trace("Ignoring persistent instance passed to replicate()"); //hum ... should we cascade anyway? throw an exception? fine like it is? return; } @@ -103,7 +99,8 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp } if ( oldVersion != null ) { - if (LOG.isTraceEnabled()) LOG.foundExistingRow(MessageHelper.infoString(persister, id, source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Found existing row for " + + MessageHelper.infoString(persister, id, source.getFactory())); /// HHH-2378 final Object realOldVersion = persister.isVersioned() ? oldVersion : null; @@ -118,13 +115,14 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp // if can replicate, will result in a SQL UPDATE // else do nothing (don't even reassociate object!) if (canReplicate) performReplication(entity, id, realOldVersion, persister, replicationMode, source); - else LOG.noNeedToReplicate(); + else LOG.trace("No need to replicate"); //TODO: would it be better to do a refresh from db? } else { // no existing row - do an insert - if (LOG.isTraceEnabled()) LOG.noExistingRow(MessageHelper.infoString(persister, id, source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("No existing row, replicating new instance " + + MessageHelper.infoString(persister, id, source.getFactory())); final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity! final EntityKey key = regenerate ? @@ -174,7 +172,8 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp ReplicationMode replicationMode, EventSource source) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.replicatingChanges(MessageHelper.infoString(persister, id, source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Replicating changes to " + + MessageHelper.infoString(persister, id, source.getFactory())); new OnReplicateVisitor( source, id, entity, true ).process( entity, persister ); @@ -213,35 +212,4 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp protected CascadingAction getCascadeAction() { return CascadingAction.REPLICATE; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Found existing row for %s" ) - void foundExistingRow( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Ignoring persistent instance passed to replicate()" ) - void ignoringPersistentInstance(); - - @LogMessage( level = TRACE ) - @Message( value = "No existing row, replicating new instance %s" ) - void noExistingRow( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "No need to replicate" ) - void noNeedToReplicate(); - - @LogMessage( level = TRACE ) - @Message( value = "Replicating changes to %s" ) - void replicatingChanges( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Uninitialized proxy passed to replicate()" ) - void uninitializedProxy(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java index 8d189c15b1..fb42614ef1 100755 --- a/hibernate-core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java @@ -24,12 +24,11 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.PersistentObjectException; import org.hibernate.TransientObjectException; import org.hibernate.classic.Lifecycle; @@ -47,10 +46,6 @@ import org.hibernate.event.SaveOrUpdateEventListener; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines the default listener used by Hibernate for handling save-update @@ -83,7 +78,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } // For an uninitialized proxy, noop, don't even need to return an id, since it is never a save() - if (reassociateIfUninitializedProxy(object, source)) LOG.reassociatedUninitializedProxy(); + if (reassociateIfUninitializedProxy(object, source)) LOG.trace("Reassociated uninitialized proxy"); else { //initialize properties of the event: final Object entity = source.getPersistenceContext().unproxyAndReassociate( object ); @@ -119,7 +114,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException { - LOG.ignoringPersistentInstance(); + LOG.trace("Ignoring persistent instance"); EntityEntry entityEntry = event.getEntry(); if ( entityEntry == null ) { @@ -155,9 +150,8 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } - if (LOG.isTraceEnabled()) LOG.objectAlreadyAssociatedWithSession(MessageHelper.infoString(entityEntry.getPersister(), - savedId, - factory)); + if (LOG.isTraceEnabled()) LOG.trace("Object already associated with session: " + + MessageHelper.infoString(entityEntry.getPersister(), savedId, factory)); return savedId; @@ -175,7 +169,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener */ protected Serializable entityIsTransient(SaveOrUpdateEvent event) { - LOG.savingTransientInstance(); + LOG.trace("Saving transient instance"); final EventSource source = event.getSession(); @@ -222,8 +216,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener */ protected void entityIsDetached(SaveOrUpdateEvent event) { - LOG.updatingDetachedInstance(); - + LOG.trace("Updating detached instance"); if ( event.getSession().getPersistenceContext().isEntryFor( event.getEntity() ) ) { //TODO: assertion only, could be optimized away @@ -282,11 +275,12 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener Object entity, EntityPersister persister) throws HibernateException { - if (!persister.isMutable()) LOG.immutableInstancePassedToPerformUpdate(); + if (!persister.isMutable()) LOG.trace("Immutable instance passed to performUpdate()"); - if (LOG.isTraceEnabled()) LOG.updating(MessageHelper.infoString(persister, - event.getRequestedId(), - event.getSession().getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Updating " + + MessageHelper.infoString(persister, + event.getRequestedId(), + event.getSession().getFactory())); final EventSource source = event.getSession(); @@ -327,16 +321,17 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener persister.afterReassociate(entity, source); - if (LOG.isTraceEnabled()) LOG.updating(MessageHelper.infoString(persister, event.getRequestedId(), source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Updating " + + MessageHelper.infoString(persister, event.getRequestedId(), source.getFactory())); cascadeOnUpdate(event, persister, entity); } protected boolean invokeUpdateLifecycle(Object entity, EntityPersister persister, EventSource source) { if ( persister.implementsLifecycle( source.getEntityMode() ) ) { - LOG.callingOnUpdate(); - if ( ( ( Lifecycle ) entity ).onUpdate( source ) ) { - LOG.updateVetoedByOnUpdate(); + LOG.debug("Calling onUpdate()"); + if (((Lifecycle)entity).onUpdate(source)) { + LOG.debug("Update vetoed by onUpdate()"); return true; } } @@ -367,47 +362,4 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener protected CascadingAction getCascadeAction() { return CascadingAction.SAVE_UPDATE; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Calling onUpdate()" ) - void callingOnUpdate(); - - @LogMessage( level = TRACE ) - @Message( value = "Ignoring persistent instance" ) - void ignoringPersistentInstance(); - - @LogMessage( level = TRACE ) - @Message( value = "Immutable instance passed to performUpdate()" ) - void immutableInstancePassedToPerformUpdate(); - - @LogMessage( level = TRACE ) - @Message( value = "Object already associated with session: %s" ) - void objectAlreadyAssociatedWithSession( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Reassociated uninitialized proxy" ) - void reassociatedUninitializedProxy(); - - @LogMessage( level = TRACE ) - @Message( value = "Saving transient instance" ) - void savingTransientInstance(); - - @LogMessage( level = DEBUG ) - @Message( value = "Update vetoed by onUpdate()" ) - void updateVetoedByOnUpdate(); - - @LogMessage( level = TRACE ) - @Message( value = "Updating %s" ) - void updating( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating detached instance" ) - void updatingDetachedInstance(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/EvictVisitor.java b/hibernate-core/src/main/java/org/hibernate/event/def/EvictVisitor.java index f56f056094..e48282ac6e 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/EvictVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/EvictVisitor.java @@ -24,18 +24,14 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.CollectionEntry; import org.hibernate.engine.CollectionKey; import org.hibernate.event.EventSource; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.CollectionType; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Evict any collections referenced by the object from the session cache. @@ -80,9 +76,10 @@ public class EvictVisitor extends AbstractVisitor { private void evictCollection(PersistentCollection collection) { CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection); - if (LOG.isDebugEnabled()) LOG.evictingCollection(MessageHelper.collectionInfoString(ce.getLoadedPersister(), - ce.getLoadedKey(), - getSession().getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Evicting collection: " + + MessageHelper.collectionInfoString(ce.getLoadedPersister(), + ce.getLoadedKey(), + getSession().getFactory())); if ( ce.getLoadedPersister() != null && ce.getLoadedKey() != null ) { //TODO: is this 100% correct? getSession().getPersistenceContext().getCollectionsByKey().remove( @@ -90,15 +87,4 @@ public class EvictVisitor extends AbstractVisitor { ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Evicting collection: %s" ) - void evictingCollection( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/ReattachVisitor.java b/hibernate-core/src/main/java/org/hibernate/event/def/ReattachVisitor.java index 67428a5ac4..9d7aef1614 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/ReattachVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/ReattachVisitor.java @@ -23,19 +23,15 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.action.CollectionRemoveAction; import org.hibernate.event.EventSource; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.CompositeType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Abstract superclass of visitors that reattach collections. @@ -99,9 +95,8 @@ public abstract class ReattachVisitor extends ProxyVisitor { * @throws HibernateException */ void removeCollection(CollectionPersister role, Serializable collectionKey, EventSource source) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.collectionDereferencedWhileTransient(MessageHelper.collectionInfoString(role, - ownerIdentifier, - source.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Collection dereferenced while transient " + + MessageHelper.collectionInfoString(role, ownerIdentifier, source.getFactory())); source.getActionQueue().addAction( new CollectionRemoveAction( owner, role, collectionKey, false, source ) ); } @@ -120,15 +115,4 @@ public abstract class ReattachVisitor extends ProxyVisitor { role.getCollectionType().getLHSPropertyName(), getSession().getEntityMode()); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Collection dereferenced while transient %s" ) - void collectionDereferencedWhileTransient( String collectionInfoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/def/WrapVisitor.java b/hibernate-core/src/main/java/org/hibernate/event/def/WrapVisitor.java index afb1d8e1a3..a9a431ffaa 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/def/WrapVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/event/def/WrapVisitor.java @@ -23,9 +23,9 @@ */ package org.hibernate.event.def; -import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.PersistenceContext; import org.hibernate.engine.SessionImplementor; @@ -35,10 +35,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.CollectionType; import org.hibernate.type.CompositeType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Wrap collections in a Hibernate collection @@ -111,7 +107,7 @@ public class WrapVisitor extends ProxyVisitor { PersistentCollection persistentCollection = collectionType.wrap(session, collection); persistenceContext.addNewCollection( persister, persistentCollection ); - if (LOG.isTraceEnabled()) LOG.wrappedCollectionInRole(collectionType.getRole()); + if (LOG.isTraceEnabled()) LOG.trace("Wrapped collection in role: " + collectionType.getRole()); return persistentCollection; //Force a substitution! @@ -163,15 +159,4 @@ public class WrapVisitor extends ProxyVisitor { persister.setPropertyValues( object, values, entityMode ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Wrapped collection in role: %s" ) - void wrappedCollectionInRole( String role ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java b/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java index 280e41d061..33243ca2df 100644 --- a/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java @@ -24,21 +24,16 @@ */ package org.hibernate.exception; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.JDBCException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A factory for building SQLExceptionConverter instances. @@ -76,7 +71,7 @@ public class SQLExceptionConverterFactory { } if ( converter == null ) { - LOG.usingDialectDefinedConverter(); + LOG.trace("Using dialect defined converter"); converter = dialect.buildSQLExceptionConverter(); } @@ -109,7 +104,7 @@ public class SQLExceptionConverterFactory { private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) { try { - LOG.attemptingToConstructSqlExceptionConverter(converterClassName); + LOG.trace("Attempting to construct instance of specified SQLExceptionConverter [" + converterClassName + "]"); Class converterClass = ReflectHelper.classForName( converterClassName ); // First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param... @@ -138,27 +133,4 @@ public class SQLExceptionConverterFactory { return null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to construct instance of specified SQLExceptionConverter [%s]" ) - void attemptingToConstructSqlExceptionConverter( String converterClassName ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to configure SQLExceptionConverter : %s" ) - void unableToConfigureSqlExceptionConverter( HibernateException e ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to construct instance of specified SQLExceptionConverter : %s" ) - void unableToConstructSqlExceptionConverter( Throwable t ); - - @LogMessage( level = TRACE ) - @Message( value = "Using dialect defined converter" ) - void usingDialectDefinedConverter(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java b/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java index 304690879e..a45bc097d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java @@ -24,18 +24,14 @@ */ package org.hibernate.hql; -import static org.jboss.logging.Logger.Level.WARN; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.classic.ParserHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Provides query splitting methods, which were originally in QueryTranslator. @@ -157,15 +153,4 @@ public final class QuerySplitter { public static String getImportedClass(String name, SessionFactoryImplementor factory) { return factory.getImportedClassName( name ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "no persistent classes found for query class: %s" ) - void noPersistentClassesFound( String query ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/ASTQueryTranslatorFactory.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/ASTQueryTranslatorFactory.java index 995521c30a..ddf7a0382a 100755 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/ASTQueryTranslatorFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/ASTQueryTranslatorFactory.java @@ -24,16 +24,12 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.INFO; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.FilterTranslator; import org.hibernate.hql.QueryTranslator; import org.hibernate.hql.QueryTranslatorFactory; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Generates translators which uses the Antlr-based parser to perform @@ -71,15 +67,4 @@ public class ASTQueryTranslatorFactory implements QueryTranslatorFactory { SessionFactoryImplementor factory) { return new QueryTranslatorImpl( queryIdentifier, queryString, filters, factory ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Using ASTQueryTranslatorFactory" ) - void usingAstQueryTranslatorFactory(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/ErrorCounter.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/ErrorCounter.java index e78bd8cbeb..bcbf0d14a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/ErrorCounter.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/ErrorCounter.java @@ -24,15 +24,11 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.hibernate.Logger; import org.hibernate.QueryException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.RecognitionException; /** @@ -82,17 +78,6 @@ public class ErrorCounter implements ParseErrorHandler { if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert((RecognitionException)recognitionExceptions.get(0)); throw new QueryException(getErrorString()); } - LOG.throwQueryException(); + LOG.debug("throwQueryException() : no errors"); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "throwQueryException() : no errors" ) - void throwQueryException(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlParser.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlParser.java index f0b3170c78..fdc85ae9d0 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlParser.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlParser.java @@ -24,21 +24,16 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.WARN; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.hql.antlr.HqlBaseParser; import org.hibernate.hql.antlr.HqlTokenTypes; import org.hibernate.hql.ast.util.ASTPrinter; import org.hibernate.hql.ast.util.ASTUtil; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.ASTPair; import antlr.MismatchedTokenException; import antlr.RecognitionException; @@ -339,7 +334,7 @@ public final class HqlParser extends HqlBaseParser { // The next token ( LT(2) ) should be 'by'... otherwise, this is just an ident. if ( LA( 2 ) != LITERAL_by ) { LT( 1 ).setType( IDENT ); - LOG.weakKeywords( LT( 1 ) ); + LOG.debug("weakKeywords() : new LT(1) token - " + LT(1)); } break; default: @@ -348,7 +343,7 @@ public final class HqlParser extends HqlBaseParser { HqlToken hqlToken = (HqlToken)LT(1); if (hqlToken.isPossibleID()) { hqlToken.setType(IDENT); - LOG.weakKeywords(LT(1)); + LOG.debug("weakKeywords() : new LT(1) token - " + LT(1)); } } break; @@ -366,7 +361,7 @@ public final class HqlParser extends HqlBaseParser { { // Set it! LT( 2 ).setType( IDENT ); - LOG.handleDotIdent(LT(1)); + LOG.debug("handleDotIdent() : new LT(2) token - " + LT(1)); } } } @@ -384,23 +379,4 @@ public final class HqlParser extends HqlBaseParser { //overriden to avoid System.exit throw new QueryException("Parser: panic"); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "handleDotIdent() : new LT(2) token - %s" ) - void handleDotIdent( Token lt ); - - @LogMessage( level = WARN ) - @Message( value = "processEqualityExpression() : No expression to process!" ) - void processEqualityExpression(); - - @LogMessage( level = DEBUG ) - @Message( value = "weakKeywords() : new LT(1) token - %s" ) - void weakKeywords( Token lt ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java index 4514e51f5a..cfd215a3b9 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java @@ -24,8 +24,6 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; @@ -38,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.ParameterBinder; @@ -99,10 +98,6 @@ import org.hibernate.type.VersionType; import org.hibernate.usertype.UserVersionType; import org.hibernate.util.ArrayHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.ASTFactory; import antlr.RecognitionException; import antlr.SemanticException; @@ -254,7 +249,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par ASTUtil.createSibling( inputAstFactory, HqlTokenTypes.ALIAS, "this", fromElement ); fromClauseInput.addChild( fromElement ); // Show the modified AST. - LOG.prepareFromClauseInputTree(); + LOG.debug("prepareFromClauseInputTree() : Filter - Added 'this' as a from element..."); queryTranslatorImpl.showHqlAst( hqlParser.getAST() ); // Create a parameter specification for the collection filter... @@ -351,7 +346,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par join.addCondition( fkTableAlias, keyColumnNames, " = ?" ); fromElement.setJoinSequence( join ); fromElement.setFilter( true ); - LOG.createFromFilterElement(); + LOG.debug("createFromFilterElement() : processed filter FROM element."); return fromElement; } @@ -403,13 +398,16 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - if (LOG.isDebugEnabled()) LOG.createFromJoinElement(getASTPrinter().showAsString(fromElement, LOG.joinTreeHeader())); + if (LOG.isDebugEnabled()) LOG.debug("createFromJoinElement() : " + + getASTPrinter().showAsString(fromElement, "-- join tree --")); } + private void handleWithFragment(FromElement fromElement, AST hqlWithNode) throws SemanticException { try { withClause( hqlWithNode ); AST hqlSqlWithNode = returnAST; - if (LOG.isDebugEnabled()) LOG.handleWithFragment(getASTPrinter().showAsString(hqlSqlWithNode, LOG.withClauseHeader())); + if (LOG.isDebugEnabled()) LOG.debug("handleWithFragment() : " + + getASTPrinter().showAsString(hqlSqlWithNode, "-- with clause --")); WithClauseVisitor visitor = new WithClauseVisitor( fromElement ); NodeTraverser traverser = new NodeTraverser( visitor ); traverser.traverseDepthFirst( hqlSqlWithNode ); @@ -560,7 +558,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par switch ( rhs.getType() ) { case SqlTokenTypes.ELEMENTS: case SqlTokenTypes.INDICES: - if (LOG.isDebugEnabled()) LOG.lookupProperty(dotNode.getPath(), rhs.getText(), lhs.getPath()); + if (LOG.isDebugEnabled()) LOG.debug("lookupProperty() " + dotNode.getPath() + " => " + rhs.getText() + "(" + + lhs.getPath() + ")"); CollectionFunction f = ( CollectionFunction ) rhs; // Re-arrange the tree so that the collection function is the root and the lhs is the path. f.setFirstChild( lhs ); @@ -587,7 +586,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par if ( fromElements.size() == 1 ) { final FromElement fromElement = ( FromElement ) fromElements.get( 0 ); try { - LOG.resolvingPropertyAsNonQualifiedReference(identText); + LOG.trace("Attempting to resolve property [" + identText + "] as a non-qualified ref"); return fromElement.getPropertyMapping( identText ).toType( identText ) != null; } catch( QueryException e ) { @@ -622,7 +621,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par @Override protected void processQuery(AST select, AST query) throws SemanticException { - LOG.processQuery(query.toStringTree()); + LOG.debug("processQuery() : " + query.toStringTree()); try { QueryNode qn = ( QueryNode ) query; @@ -866,7 +865,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par select.setNextSibling( sibling ); selectClause = ( SelectClause ) select; selectClause.initializeDerivedSelectClause( currentFromClause ); - LOG.derivedSelectClauseCreated(); + LOG.debug("Derived SELECT clause created."); } @Override @@ -1243,51 +1242,4 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par public static void panic() { throw new QueryException( "TreeWalker: panic" ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "createFromFilterElement() : processed filter FROM element." ) - void createFromFilterElement(); - - @LogMessage( level = DEBUG ) - @Message( value = "createFromJoinElement() : %s" ) - void createFromJoinElement( String showAsString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Derived SELECT clause created." ) - void derivedSelectClauseCreated(); - - @LogMessage( level = DEBUG ) - @Message( value = "handleWithFragment() : %s" ) - void handleWithFragment( String showAsString ); - - @Message( value = "-- join tree --" ) - String joinTreeHeader(); - - @LogMessage( level = DEBUG ) - @Message( value = "lookupProperty() %s => %s(%s)" ) - void lookupProperty( String path, - String text, - String path2 ); - - @LogMessage( level = DEBUG ) - @Message( value = "prepareFromClauseInputTree() : Filter - Added 'this' as a from element..." ) - void prepareFromClauseInputTree(); - - @LogMessage( level = DEBUG ) - @Message( value = "processQuery() : %s" ) - void processQuery( String stringTree ); - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to resolve property [%s] as a non-qualified ref" ) - void resolvingPropertyAsNonQualifiedReference( String identText ); - - @Message( value = "-- with clause --" ) - String withClauseHeader(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/QueryTranslatorImpl.java index de1724c7ec..e0794acb65 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/QueryTranslatorImpl.java @@ -24,8 +24,6 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.WARN; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -33,6 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.ScrollableResults; @@ -64,10 +63,6 @@ import org.hibernate.type.Type; import org.hibernate.util.IdentitySet; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.ANTLRException; import antlr.RecognitionException; import antlr.TokenStreamException; @@ -167,7 +162,7 @@ public class QueryTranslatorImpl implements FilterTranslator { private synchronized void doCompile(Map replacements, boolean shallow, String collectionRole) { // If the query is already compiled, skip the compilation. if ( compiled ) { - LOG.compile(); + LOG.debug("compile() : The query is already compiled, skipping..."); return; } @@ -216,13 +211,13 @@ public class QueryTranslatorImpl implements FilterTranslator { catch ( RecognitionException e ) { // we do not actually propagate ANTLRExceptions as a cause, so // log it here for diagnostic purposes - LOG.trace(LOG.convertedRecognitionException(), e); + LOG.trace("Converted antlr.RecognitionException", e); throw QuerySyntaxException.convert( e, hql ); } catch ( ANTLRException e ) { // we do not actually propagate ANTLRExceptions as a cause, so // log it here for diagnostic purposes - LOG.trace(LOG.convertedAntlrException(), e); + LOG.trace("Converted antlr.ANTLRException", e); throw new QueryException( e.getMessage(), hql ); } @@ -594,25 +589,4 @@ public class QueryTranslatorImpl implements FilterTranslator { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "compile() : The query is already compiled, skipping..." ) - void compile(); - - @Message( value = "Converted antlr.ANTLRException" ) - Object convertedAntlrException(); - - @Message( value = "Converted antlr.RecognitionException" ) - Object convertedRecognitionException(); - - @LogMessage( level = WARN ) - @Message( value = "firstResult/maxResults specified with collection fetch; applying in memory!" ) - void firstOrMaxResultsSpecifiedWithCollectionFetch(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/SqlGenerator.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/SqlGenerator.java index b58028cdcd..571ee0814a 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/SqlGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/SqlGenerator.java @@ -24,11 +24,11 @@ */ package org.hibernate.hql.ast; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.engine.SessionFactoryImplementor; @@ -43,10 +43,6 @@ import org.hibernate.hql.ast.util.ASTPrinter; import org.hibernate.param.ParameterSpecification; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.RecognitionException; import antlr.collections.AST; @@ -366,15 +362,4 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { out( d ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Evicting %s" ) - void evicting( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/AbstractStatementExecutor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/AbstractStatementExecutor.java index f782e7c531..6b8a4053c8 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/AbstractStatementExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/AbstractStatementExecutor.java @@ -30,6 +30,7 @@ import java.sql.Statement; import java.util.Collections; import java.util.List; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.action.BulkOperationCleanupAction; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; @@ -156,7 +157,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { } } catch( Exception e ) { - LOG.unableToCreateTemporaryIdTable(e.getMessage()); + LOG.debug("Unable to create temporary id table [" + e.getMessage() + "]"); } } }; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/Logger.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/Logger.java deleted file mode 100644 index 0ec0b5881d..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/Logger.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.hql.ast.exec; - -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; -import java.sql.SQLWarning; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Generated ID-INSERT-SELECT SQL (multi-table delete) : %s" ) - void generatedIdInsertSelectDelete( String idInsertSelect ); - - @LogMessage( level = TRACE ) - @Message( value = "Generated ID-INSERT-SELECT SQL (multi-table update) : %s" ) - void generatedIdInsertSelectUpdate( String idInsertSelect ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to cleanup temporary id table after use [%s]" ) - void unableToCleanupTemporaryIdTable( Throwable t ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to create temporary id table [%s]" ) - void unableToCreateTemporaryIdTable( String message ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to drop temporary id table after use [%s]" ) - void unableToDropTemporaryIdTable( String message ); - - @LogMessage( level = WARN ) - @Message( value = "Warnings creating temp table : %s" ) - void warningsCreatingTempTable( SQLWarning warning ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableDeleteExecutor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableDeleteExecutor.java index 836682f7e6..b68967f005 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableDeleteExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableDeleteExecutor.java @@ -28,6 +28,7 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionImplementor; import org.hibernate.hql.ast.HqlSqlWalker; @@ -65,7 +66,7 @@ public class MultiTableDeleteExecutor extends AbstractStatementExecutor { this.persister = fromElement.getQueryable(); this.idInsertSelect = generateIdInsertSelect( persister, bulkTargetAlias, deleteStatement.getWhereClause() ); - LOG.generatedIdInsertSelectDelete(idInsertSelect); + LOG.trace("Generated ID-INSERT-SELECT SQL (multi-table delete) : " + idInsertSelect); String[] tableNames = persister.getConstraintOrderedTableNameClosure(); String[][] columnNames = persister.getContraintOrderedTableKeyColumnClosure(); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableUpdateExecutor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableUpdateExecutor.java index d91c74a254..519fdd1365 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableUpdateExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/MultiTableUpdateExecutor.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionImplementor; import org.hibernate.hql.ast.HqlSqlWalker; @@ -69,7 +70,7 @@ public class MultiTableUpdateExecutor extends AbstractStatementExecutor { this.persister = fromElement.getQueryable(); this.idInsertSelect = generateIdInsertSelect( persister, bulkTargetAlias, updateStatement.getWhereClause() ); - LOG.generatedIdInsertSelectUpdate(idInsertSelect); + LOG.trace("Generated ID-INSERT-SELECT SQL (multi-table update) : " + idInsertSelect); String[] tableNames = persister.getConstraintOrderedTableNameClosure(); String[][] columnNames = persister.getContraintOrderedTableKeyColumnClosure(); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AbstractRestrictableStatement.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AbstractRestrictableStatement.java index e45226ce7d..b887d143d7 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AbstractRestrictableStatement.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AbstractRestrictableStatement.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; import antlr.collections.AST; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AggregateNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AggregateNode.java index 12b29b6e06..14023ed1aa 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AggregateNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/AggregateNode.java @@ -23,15 +23,11 @@ */ package org.hibernate.hql.ast.tree; -import static org.jboss.logging.Logger.Level.INFO; +import org.hibernate.Logger; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.hql.ast.util.ColumnHelper; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.SemanticException; import antlr.collections.AST; @@ -96,15 +92,4 @@ public class AggregateNode extends AbstractSelectExpression implements SelectExp // functions in a SELECT should always be considered scalar. return true; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Could not resolve aggregate function {}; using standard definition" ) - void unableToResolveAggregateFunction( String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DeleteStatement.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DeleteStatement.java index e89417973a..f8daf5ba9f 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DeleteStatement.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DeleteStatement.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DotNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DotNode.java index 4a26109312..1d006d1188 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DotNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/DotNode.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; import org.hibernate.hql.CollectionProperties; @@ -301,7 +302,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec ); FromElement elem = factory.createCollection( queryableCollection, role, joinType, fetch, indexed ); - LOG.dereferenceCollection(propName, elem); + LOG.debug("dereferenceCollection() : Created new FROM element for " + propName + " : " + elem); setImpliedJoin( elem ); setFromElement( elem ); // This 'dot' expression now refers to the resulting from element. @@ -382,10 +383,10 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec private void dereferenceEntityJoin(String classAlias, EntityType propertyType, boolean impliedJoin, AST parent) throws SemanticException { dereferenceType = DEREF_ENTITY; - if (LOG.isDebugEnabled()) LOG.dereferenceEntityJoin(propertyName, - getFromElement().getClassName(), - (classAlias == null) ? LOG.noAlias() : classAlias, - ASTUtil.getDebugString(parent)); + if (LOG.isDebugEnabled()) LOG.debug("dereferenceEntityJoin() : generating join for " + propertyName + " in " + + getFromElement().getClassName() + " (" + + (classAlias == null ? "" : classAlias) + ") parent = " + + ASTUtil.getDebugString(parent)); // Create a new FROM node for the referenced class. String associatedEntityName = propertyType.getAssociatedEntityName(); String tableAlias = getAliasGenerator().createName( associatedEntityName ); @@ -536,7 +537,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec } private void checkForCorrelatedSubquery(String methodName) { - if (isCorrelatedSubselect()) LOG.correlatedSubquery(methodName); + if (isCorrelatedSubselect()) LOG.debug(methodName + "() : correlated subquery"); } private boolean isCorrelatedSubselect() { @@ -557,7 +558,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec private void dereferenceEntityIdentifier(String propertyName, DotNode dotParent) { // special shortcut for id properties, skip the join! // this must only occur at the _end_ of a path expression - LOG.dereferenceShortcut(propertyName, getFromElement().getClassName()); + LOG.debug("dereferenceShortcut() : property " + propertyName + " in " + getFromElement().getClassName() + + " does not require a join."); initText(); setPropertyNameAndPath( dotParent ); // Set the unresolved path in this node and the parent. @@ -577,8 +579,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec propertyName = rhs.getText(); propertyPath = propertyPath + "." + propertyName; // Append the new property name onto the unresolved path. dotNode.propertyPath = propertyPath; - LOG.unresolvedPropertyPathIsNow(dotNode.propertyPath); - } else LOG.terminalPropertyPath(propertyPath); + LOG.debug("Unresolved property path is now '" + dotNode.propertyPath + "'"); + } else LOG.debug("Terminal propertyPath = [" + propertyPath + "]"); } @Override @@ -588,7 +590,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec if (fromElement == null) return null; // If the lhs is a collection, use CollectionPropertyMapping Type propertyType = fromElement.getPropertyType( propertyName, propertyPath ); - LOG.getDataType(propertyPath, propertyType); + LOG.debug("getDataType() : " + propertyPath + " -> " + propertyType); super.setDataType( propertyType ); } return super.getDataType(); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromClause.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromClause.java index bb84de9dc4..eed3446942 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromClause.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromClause.java @@ -31,6 +31,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.ast.util.ASTIterator; import org.hibernate.hql.ast.util.ASTUtil; @@ -276,7 +277,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } void addJoinByPathMap(String path, FromElement destination) { - LOG.addJoinByPathMap(path, destination.getDisplayText()); + LOG.debug("addJoinByPathMap() : " + path + " -> " + destination.getDisplayText()); fromElementsByPath.put( path, destination ); } @@ -346,7 +347,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } public void promoteJoin(FromElement elem) { - LOG.promoting(elem, this); + LOG.debug("Promoting [" + elem + "] to [" + this + "]"); //TODO: implement functionality // this might be painful to do here, as the "join post processing" for // the subquery has already been performed (meaning that for @@ -362,7 +363,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } void addCollectionJoinFromElementByPath(String path, FromElement destination) { - LOG.addCollectionJoinFromElementByPath(path, destination); + LOG.debug("addCollectionJoinFromElementByPath() : " + path + " -> " + destination); collectionJoinFromElementsByPath.put( path, destination ); // Add the new node to the map so that we don't create it twice. } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElement.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElement.java index b4a873ca65..19569187b8 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElement.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElement.java @@ -27,6 +27,7 @@ package org.hibernate.hql.ast.tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; import org.hibernate.hql.CollectionProperties; @@ -151,7 +152,7 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa this.elementType = new FromElementType( this, persister, type ); // Register the FromElement with the FROM clause, now that we have the names and aliases. fromClause.registerFromElement( this ); - LOG.fromClause(fromClause, className, classAlias == null ? LOG.noAlias() : classAlias, tableAlias); + LOG.debug(fromClause + " : " + className + " (" + (classAlias == null ? "" : classAlias) + ") -> " + tableAlias); } public EntityPersister getEntityPersister() { @@ -308,8 +309,9 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa } public void setIncludeSubclasses(boolean includeSubclasses) { - if (LOG.isTraceEnabled() && isDereferencedBySuperclassOrSubclassProperty() && !includeSubclasses) LOG.attemptToDisableSubclassInclusions(new Exception( - LOG.stackTraceSource())); + if (LOG.isTraceEnabled() && isDereferencedBySuperclassOrSubclassProperty() && !includeSubclasses) LOG.trace("Attempt to disable subclass-inclusions : " + + new Exception( + "Stack-trace source")); this.includeSubclasses = includeSubclasses; } @@ -617,7 +619,8 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa if ( persister != null ) { try { Queryable.Declarer propertyDeclarer = persister.getSubclassPropertyDeclarer( propertyName ); - LOG.handlingPropertyDereference(persister.getEntityName(), getClassAlias(), propertyName, propertyDeclarer); + LOG.trace("Handling property dereference [" + persister.getEntityName() + " (" + getClassAlias() + ") -> " + + propertyName + " (" + propertyDeclarer + ")]"); if ( propertyDeclarer == Queryable.Declarer.SUBCLASS ) { dereferencedBySubclassProperty = true; includeSubclasses = true; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementFactory.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementFactory.java index 5cb0a925cd..393f903693 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementFactory.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.engine.JoinSequence; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; @@ -124,7 +125,7 @@ public class FromElementFactory implements SqlTokenTypes { String pathAlias, FromElement parentFromElement, String classAlias) throws SemanticException { - LOG.createFromElementInSubselect(path); + LOG.debug("createFromElementInSubselect() : path = " + path); // Create an DotNode AST for the path and resolve it. FromElement fromElement = evaluateFromElementPath( path, classAlias ); EntityPersister entityPersister = fromElement.getEntityPersister(); @@ -143,7 +144,7 @@ public class FromElementFactory implements SqlTokenTypes { // If the from element isn't in the same clause, create a new from element. if ( fromElement.getFromClause() != fromClause ) { - LOG.createFromElementInSubselect(); + LOG.debug("createFromElementInSubselect() : creating a new FROM element..."); fromElement = createFromElement( entityPersister ); initializeAndAddFromElement( fromElement, path, @@ -153,7 +154,7 @@ public class FromElementFactory implements SqlTokenTypes { tableAlias ); } - LOG.createFromElementInSubselect(path, fromElement); + LOG.debug("createFromElementInSubselect() : " + path + " -> " + fromElement); return fromElement; } @@ -252,7 +253,7 @@ public class FromElementFactory implements SqlTokenTypes { EntityPersister entityPersister = elem.getEntityPersister(); int numberOfTables = entityPersister.getQuerySpaces().length; if ( numberOfTables > 1 && implied && !elem.useFromFragment() ) { - LOG.createEntityJoin(); + LOG.debug("createEntityJoin() : Implied multi-table entity join"); elem.setUseFromFragment( true ); } @@ -371,13 +372,14 @@ public class FromElementFactory implements SqlTokenTypes { String associatedEntityName = entityPersister.getEntityName(); // Get the class name of the associated entity. if ( queryableCollection.isOneToMany() ) { - LOG.createEntityAssociation(path, role, associatedEntityName); + LOG.debug("createEntityAssociation() : One to many - path = " + path + " role = " + role + " associatedEntityName = " + + associatedEntityName); JoinSequence joinSequence = createJoinSequence( roleAlias, joinType ); elem = createJoin( associatedEntityName, roleAlias, joinSequence, ( EntityType ) queryableCollection.getElementType(), false ); } else { - LOG.createManyToMany(path, role, associatedEntityName); + LOG.debug("createManyToMany() : path = " + path + " role = " + role + " associatedEntityName = " + associatedEntityName); elem = createManyToMany( role, associatedEntityName, roleAlias, entityPersister, ( EntityType ) queryableCollection.getElementType(), joinType ); fromClause.getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() ); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementType.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementType.java index 6204681ad5..17c2cca4c9 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementType.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromElementType.java @@ -26,6 +26,7 @@ package org.hibernate.hql.ast.tree; import java.util.List; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; @@ -339,7 +340,7 @@ class FromElementType { enabledFilters, propertyMapping.toColumns( tableAlias, path ) ); - LOG.toColumns(tableAlias, path, subquery); + LOG.debug("toColumns(" + tableAlias + "," + path + ") : subquery = " + subquery); return new String[]{"(" + subquery + ")"}; } if (forceAlias) { @@ -369,7 +370,7 @@ class FromElementType { return propertyMapping.toColumns(tableAlias, path); } else { String[] columns = propertyMapping.toColumns(path); - LOG.usingNonQualifiedColumnReference(path, ArrayHelper.toString(columns)); + LOG.trace("Using non-qualified column reference [" + path + " -> (" + ArrayHelper.toString(columns) + ")]"); return columns; } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromReferenceNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromReferenceNode.java index 68edac95a7..738f1442f7 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromReferenceNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/FromReferenceNode.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import antlr.SemanticException; import antlr.collections.AST; @@ -69,7 +70,7 @@ public abstract class FromReferenceNode extends AbstractSelectExpression public void setResolved() { this.resolved = true; - LOG.resolved(this.getPath(), this.getText()); + LOG.debug("Resolved : " + this.getPath() + " -> " + this.getText()); } public String getDisplayText() { diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/IndexNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/IndexNode.java index f9543be22c..bdf31250ae 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/IndexNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/IndexNode.java @@ -28,6 +28,7 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import java.util.List; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.QueryParameters; @@ -67,7 +68,7 @@ public class IndexNode extends FromReferenceNode { FromReferenceNode collectionNode = ( FromReferenceNode ) getFirstChild(); String path = collectionNode.getPath() + "[]." + propertyName; - LOG.creatingJoinForManyToManyElements(path); + LOG.debug("Creating join for many-to-many elements for " + path); FromElementFactory factory = new FromElementFactory( fromElement.getFromClause(), fromElement, path ); // This will add the new from element to the origin. FromElement elementJoin = factory.createElementJoin( queryableCollection ); @@ -108,8 +109,8 @@ public class IndexNode extends FromReferenceNode { if ( elem == null ) { FromElementFactory factory = new FromElementFactory( fromClause, fromElement, path ); elem = factory.createCollectionElementsJoin( queryableCollection, elementTable ); - LOG.noFromElementFound(path, elem); - } else LOG.fromElementFound(path); + LOG.debug("No FROM element found for the elements of collection join path " + path + ", created " + elem); + } else LOG.debug("FROM element found for collection join path " + path); // The 'from element' that represents the elements of the collection. setFromElement( fromElement ); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/Logger.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/Logger.java deleted file mode 100644 index 0bf3344a70..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/Logger.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.hql.ast.tree; - -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import org.hibernate.persister.entity.Queryable.Declarer; -import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; -import antlr.collections.AST; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "addCollectionJoinFromElementByPath() : %s -> %s" ) - void addCollectionJoinFromElementByPath( String path, - FromElement destination ); - - @LogMessage( level = DEBUG ) - @Message( value = "addJoinByPathMap() : %s -> %s" ) - void addJoinByPathMap( String path, - String displayText ); - - @LogMessage( level = TRACE ) - @Message( value = "Attempt to disable subclass-inclusions : %s" ) - void attemptToDisableSubclassInclusions( Exception exception ); - - @LogMessage( level = DEBUG ) - @Message( value = "collectionProperty() : name=%s type=%s" ) - void collectionProperty( AST name, - Type type ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s() : correlated subquery" ) - void correlatedSubquery( String methodName ); - - @LogMessage( level = DEBUG ) - @Message( value = "createEntityAssociation() : One to many - path = %s role = %s associatedEntityName = %s" ) - void createEntityAssociation( String path, - String role, - String associatedEntityName ); - - @LogMessage( level = DEBUG ) - @Message( value = "createEntityJoin() : Implied multi-table entity join" ) - void createEntityJoin(); - - @LogMessage( level = DEBUG ) - @Message( value = "createFromElementInSubselect() : creating a new FROM element..." ) - void createFromElementInSubselect(); - - @LogMessage( level = DEBUG ) - @Message( value = "createFromElementInSubselect() : path = %s" ) - void createFromElementInSubselect( String path ); - - @LogMessage( level = DEBUG ) - @Message( value = "createFromElementInSubselect() : %s -> %s" ) - void createFromElementInSubselect( String path, - FromElement fromElement ); - - @LogMessage( level = DEBUG ) - @Message( value = "Creating elements for %s" ) - void creatingElements( String path ); - - @LogMessage( level = DEBUG ) - @Message( value = "Creating join for many-to-many elements for %s" ) - void creatingJoinForManyToManyElements( String path ); - - @LogMessage( level = DEBUG ) - @Message( value = "createManyToMany() : path = %s role = %s associatedEntityName = %s" ) - void createManyToMany( String path, - String role, - String associatedEntityName ); - - @LogMessage( level = DEBUG ) - @Message( value = "dereferenceCollection() : Created new FROM element for %s : %s" ) - void dereferenceCollection( String propName, - FromElement elem ); - - @LogMessage( level = DEBUG ) - @Message( value = "dereferenceEntityJoin() : generating join for %s in %s (%s) parent = %s" ) - void dereferenceEntityJoin( String propertyName, - String className, - String string, - String debugString ); - - @LogMessage( level = DEBUG ) - @Message( value = "dereferenceShortcut() : property %s in %s does not require a join." ) - void dereferenceShortcut( String propertyName, - String className ); - - @LogMessage( level = DEBUG ) - @Message( value = "%s : %s (%s) -> %s" ) - void fromClause( FromClause fromClause, - String className, - String string, - String tableAlias ); - - @LogMessage( level = DEBUG ) - @Message( value = "FROM element found for collection join path %s" ) - void fromElementFound( String path ); - - @LogMessage( level = DEBUG ) - @Message( value = "getDataType() : %s -> %s" ) - void getDataType( String propertyPath, - Type propertyType ); - - @LogMessage( level = DEBUG ) - @Message( value = "getOrderByClause() : Creating a new ORDER BY clause" ) - void getOrderByClause(); - - @LogMessage( level = TRACE ) - @Message( value = "Handling property dereference [%s (%s) -> %s (%s)]" ) - void handlingPropertyDereference( String entityName, - String classAlias, - String propertyName, - Declarer propertyDeclarer ); - - @Message( value = "" ) - String noAlias(); - - @LogMessage( level = DEBUG ) - @Message( value = "No FROM element found for the elements of collection join path %s, created %s" ) - void noFromElementFound( String path, - FromElement elem ); - - @LogMessage( level = DEBUG ) - @Message( value = "Promoting [%s] to [%s]" ) - void promoting( FromElement elem, - FromClause fromClause ); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolved : %s -> %s" ) - void resolved( String path, - String text ); - - @Message( value = "Stack-trace source" ) - String stackTraceSource(); - - @LogMessage( level = DEBUG ) - @Message( value = "Terminal propertyPath = [%s]" ) - void terminalPropertyPath( String propertyPath ); - - @LogMessage( level = DEBUG ) - @Message( value = "toColumns(%s,%s) : subquery = %s" ) - void toColumns( String tableAlias, - String path, - String subquery ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unresolved property path is now '%s'" ) - void unresolvedPropertyPathIsNow( String propertyPath ); - - @LogMessage( level = TRACE ) - @Message( value = "Using non-qualified column reference [%s -> (%s)]" ) - void usingNonQualifiedColumnReference( String path, - String string ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/MethodNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/MethodNode.java index 7186e2bfce..2c2ecd20c7 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/MethodNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/MethodNode.java @@ -25,6 +25,7 @@ package org.hibernate.hql.ast.tree; import java.util.Arrays; +import org.hibernate.Logger; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.hql.CollectionProperties; import org.hibernate.hql.antlr.SqlTokenTypes; @@ -142,7 +143,7 @@ public class MethodNode extends AbstractSelectExpression implements FunctionNode SqlNode expr = ( SqlNode ) path; Type type = expr.getDataType(); - LOG.collectionProperty(name, type); + LOG.debug("collectionProperty() : name=" + name + " type=" + type); resolveCollectionProperty( expr ); } @@ -204,7 +205,7 @@ public class MethodNode extends AbstractSelectExpression implements FunctionNode QueryableCollection queryableCollection = collectionFromElement.getQueryableCollection(); String path = collectionNode.getPath() + "[]." + propertyName; - LOG.creatingElements(path); + LOG.debug("Creating elements for " + path); fromElement = collectionFromElement; if ( !collectionFromElement.isCollectionOfValuesOrComponents() ) { diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java index f143e79817..622c85324a 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; @@ -97,7 +98,7 @@ public class QueryNode extends AbstractRestrictableStatement implements SelectEx // if there is no order by, make one if ( orderByClause == null ) { - LOG.getOrderByClause(); + LOG.debug("getOrderByClause() : Creating a new ORDER BY clause"); orderByClause = ( OrderByClause ) ASTUtil.create( getWalker().getASTFactory(), SqlTokenTypes.ORDER, "ORDER" ); // Find the WHERE; if there is no WHERE, find the FROM... diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/UpdateStatement.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/UpdateStatement.java index 98e9e484f6..f2d7c5d4ae 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/UpdateStatement.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/UpdateStatement.java @@ -24,6 +24,7 @@ */ package org.hibernate.hql.ast.tree; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java index 310ee44ad2..f6ecb72033 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java @@ -24,8 +24,6 @@ */ package org.hibernate.hql.ast.util; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; @@ -33,6 +31,7 @@ import java.util.List; import java.util.ListIterator; import java.util.StringTokenizer; import org.hibernate.AssertionFailure; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.LoadQueryInfluencers; @@ -50,10 +49,6 @@ import org.hibernate.sql.JoinFragment; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Performs the post-processing of the join information gathered during semantic analysis. @@ -127,25 +122,25 @@ public class JoinProcessor implements SqlTokenTypes { while ( iter.hasNext() ) { final FromElement fromElement = ( FromElement ) iter.next(); JoinSequence join = fromElement.getJoinSequence(); - join.setSelector( - new JoinSequence.Selector() { - public boolean includeSubclasses(String alias) { - // The uber-rule here is that we need to include subclass joins if - // the FromElement is in any way dereferenced by a property from - // the subclass table; otherwise we end up with column references - // qualified by a non-existent table reference in the resulting SQL... - boolean containsTableAlias = fromClause.containsTableAlias( alias ); - if ( fromElement.isDereferencedBySubclassProperty() ) { - // TODO : or should we return 'containsTableAlias'?? - LOG.forcingInclusionOfExtraJoins(alias, containsTableAlias); - return true; - } - boolean shallowQuery = walker.isShallowQuery(); - boolean includeSubclasses = fromElement.isIncludeSubclasses(); - boolean subQuery = fromClause.isSubQuery(); - return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery; - } + join.setSelector(new JoinSequence.Selector() { + public boolean includeSubclasses( String alias ) { + // The uber-rule here is that we need to include subclass joins if + // the FromElement is in any way dereferenced by a property from + // the subclass table; otherwise we end up with column references + // qualified by a non-existent table reference in the resulting SQL... + boolean containsTableAlias = fromClause.containsTableAlias(alias); + if (fromElement.isDereferencedBySubclassProperty()) { + // TODO : or should we return 'containsTableAlias'?? + LOG.trace("Forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + + "]"); + return true; + } + boolean shallowQuery = walker.isShallowQuery(); + boolean includeSubclasses = fromElement.isIncludeSubclasses(); + boolean subQuery = fromClause.isSubQuery(); + return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery; } + } ); addJoinNodes( query, join, fromElement ); } @@ -175,7 +170,7 @@ public class JoinProcessor implements SqlTokenTypes { // If there is a FROM fragment and the FROM element is an explicit, then add the from part. if ( fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/ ) { String fromFragment = processFromFragment( frag, join ).trim(); - LOG.usingFromFragment(fromFragment); + LOG.debug("Using FROM fragment [" + fromFragment + "]"); processDynamicFilterParameters( fromFragment, fromElement, @@ -252,20 +247,4 @@ public class JoinProcessor implements SqlTokenTypes { private static boolean hasCollectionFilterParam(String sqlFragment) { return sqlFragment.indexOf( "?" ) < 0; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Forcing inclusion of extra joins [alias=%s, containsTableAlias=%s]" ) - void forcingInclusionOfExtraJoins( String alias, - boolean containsTableAlias ); - - @LogMessage( level = DEBUG ) - @Message( value = "Using FROM fragment [%s]" ) - void usingFromFragment( String fromFragment ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/LiteralProcessor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/LiteralProcessor.java index 2b8fa4835e..dce48f51f1 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/LiteralProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/LiteralProcessor.java @@ -24,13 +24,11 @@ */ package org.hibernate.hql.ast.util; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.dialect.Dialect; @@ -47,10 +45,6 @@ import org.hibernate.sql.InFragment; import org.hibernate.type.LiteralType; import org.hibernate.type.Type; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.SemanticException; import antlr.collections.AST; @@ -138,7 +132,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { } private void setSQLValue(DotNode node, String text, String value) { - LOG.setSqlValue(text, value); + LOG.debug("setSQLValue() " + text + " -> " + value); node.setFirstChild( null ); // Chop off the rest of the tree. node.setType( SqlTokenTypes.SQL_TOKEN ); node.setText(value); @@ -146,7 +140,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { } private void setConstantValue(DotNode node, String text, Object value) { - LOG.setConstantValue(text, value, value.getClass().getName()); + LOG.debug("setConstantValue() " + text + " -> " + value + " " + value.getClass().getName()); node.setFirstChild( null ); // Chop off the rest of the tree. if ( value instanceof String ) { node.setType( SqlTokenTypes.QUOTED_STRING ); @@ -214,7 +208,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { private void processLiteral(AST constant) { String replacement = ( String ) walker.getTokenReplacements().get( constant.getText() ); if ( replacement != null ) { - LOG.processConstant(constant.getText(), replacement); + LOG.debug("processConstant() : Replacing '" + constant.getText() + "' with '" + replacement + "'"); constant.setText( replacement ); } } @@ -245,7 +239,8 @@ public class LiteralProcessor implements HqlSqlTokenTypes { return Integer.valueOf( text ).toString(); } catch( NumberFormatException e ) { - LOG.unableToFormatIncomingText(text); + LOG.trace("Could not format incoming text [" + text + + "] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG"); } } String literalValue = text; @@ -321,35 +316,4 @@ public class LiteralProcessor implements HqlSqlTokenTypes { new ExactDecimalFormatter(), new ApproximateDecimalFormatter() }; - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "processConstant() : Replacing '%s' with '%s'" ) - void processConstant( String text, - String replacement ); - - @LogMessage( level = DEBUG ) - @Message( value = "setConstantValue() %s -> %s %s" ) - void setConstantValue( String text, - Object value, - String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "setSQLValue() %s -> %s" ) - void setSqlValue( String text, - String value ); - - @LogMessage( level = TRACE ) - @Message( value = "Could not format incoming text [%s] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG" ) - void unableToFormatIncomingText( String text ); - - @LogMessage( level = WARN ) - @Message( value = "Unexpected literal token type [%d] passed for numeric processing" ) - void unexpectedLiteralTokenType( int type ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/PathHelper.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/PathHelper.java index 7afb7d5f24..fb4045f3bc 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/PathHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/PathHelper.java @@ -24,13 +24,9 @@ */ package org.hibernate.hql.ast.util; -import static org.jboss.logging.Logger.Level.DEBUG; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.ASTFactory; import antlr.collections.AST; @@ -67,23 +63,11 @@ public final class PathHelper { lhs = ASTUtil.createBinarySubtree( factory, HqlSqlTokenTypes.DOT, ".", lhs, child ); } } - if (LOG.isDebugEnabled()) LOG.parsePath(path, ASTUtil.getDebugString(lhs)); + if (LOG.isDebugEnabled()) LOG.debug("parsePath() : " + path + " -> " + ASTUtil.getDebugString(lhs)); return lhs; } public static String getAlias(String path) { return StringHelper.root( path ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "parsePath() : %s -> %s" ) - void parsePath( String path, - String debugString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/SyntheticAndFactory.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/SyntheticAndFactory.java index 1298d949ad..0ede92ce5f 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/util/SyntheticAndFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/util/SyntheticAndFactory.java @@ -24,8 +24,8 @@ */ package org.hibernate.hql.ast.util; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.ast.HqlSqlWalker; import org.hibernate.hql.ast.tree.FromElement; @@ -38,10 +38,6 @@ import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.JoinFragment; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; import antlr.collections.AST; /** @@ -91,7 +87,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { whereFragment = whereFragment.substring( 4 ); } - LOG.usingUnprocessedWhereFragment(whereFragment); + LOG.debug("Using unprocessed WHERE-fragment [" + whereFragment + "]"); SqlFragment fragment = ( SqlFragment ) create( SQL_TOKEN, whereFragment ); fragment.setJoinFragment( joinFragment ); @@ -122,7 +118,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { hqlSqlWalker ); - LOG.usingProcessedWhereFragment(fragment.getText()); + LOG.debug("Using processed WHERE-fragment [" + fragment.getText() + "]"); // Filter conditions need to be inserted before the HQL where condition and the // theta join node. This is because org.hibernate.loader.Loader binds the filter parameters first, @@ -204,19 +200,4 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { statement.getWhereClause().setFirstChild( and ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Using processed WHERE-fragment [%s]" ) - void usingProcessedWhereFragment( String whereFragment ); - - @LogMessage( level = DEBUG ) - @Message( value = "Using unprocessed WHERE-fragment [%s]" ) - void usingUnprocessedWhereFragment( String whereFragment ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java index e5c4db2fa4..976e2984c9 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java @@ -24,7 +24,6 @@ */ package org.hibernate.hql.classic; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.lang.reflect.Constructor; import java.sql.PreparedStatement; @@ -42,6 +41,7 @@ import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.ScrollableResults; @@ -71,10 +71,6 @@ import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An instance of QueryTranslator translates a Hibernate @@ -236,7 +232,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator */ private void compile() throws QueryException, MappingException { - LOG.compilingQuery(); + LOG.trace("Compiling query"); try { ParserHelper.parse( new PreprocessingParser( tokenReplacements ), queryString, @@ -252,7 +248,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator throw me; } catch ( Exception e ) { - LOG.debug(LOG.unexpectedQueryCompilationProblem(), e); + LOG.debug("Unexpected query compilation problem", e); e.printStackTrace(); QueryException qe = new QueryException( "Incorrect query syntax", e ); qe.setQueryString( queryString ); @@ -1235,18 +1231,4 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } }; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Compiling query" ) - void compilingQuery(); - - @Message( value = "Unexpected query compilation problem" ) - Object unexpectedQueryCompilationProblem(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java index ee00b81610..d00b133e2b 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java @@ -23,17 +23,13 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Generates string values using the SQL Server NEWID() function. @@ -84,20 +80,4 @@ public class GUIDGenerator implements IdentifierGenerator { ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "DEPRECATED : use {} instead with custom {} implementation" ) - void deprecatedUuidGenerator( String name, - String name2 ); - - @LogMessage( level = WARN ) - @Message( value = "GUID identifier generated: %s" ) - void guidGenerated( String result ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java b/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java index 8bac64c0e7..c0dd9c4621 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java @@ -24,7 +24,6 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; @@ -32,12 +31,9 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.type.CustomType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Factory and helper methods for {@link IdentifierGenerator} framework. @@ -89,7 +85,7 @@ public final class IdentifierGeneratorHelper { throw new HibernateException( "The database returned no natively generated identity value" ); } final Serializable id = IdentifierGeneratorHelper.get( rs, type ); - LOG.nativelyGeneratedIdentity(id); + LOG.debug("Natively generated identity: " + id); return id; } @@ -685,15 +681,4 @@ public final class IdentifierGeneratorHelper { */ private IdentifierGeneratorHelper() { } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Natively generated identity: %s" ) - void nativelyGeneratedIdentity( Serializable id ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java index ac0a4e4530..f3dbb9e650 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java @@ -23,13 +23,13 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.dialect.Dialect; @@ -37,10 +37,6 @@ import org.hibernate.engine.SessionImplementor; import org.hibernate.mapping.Table; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * increment
@@ -123,7 +119,7 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable { private void initializePreviousValueHolder(SessionImplementor session) { previousValueHolder = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass ); - LOG.fetchingInitialValue(sql); + LOG.debug("Fetching initial value: " + sql); try { PreparedStatement st = session.getJDBCContext().getConnectionManager().prepareSelectStatement( sql ); try { @@ -132,7 +128,7 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable { if (rs.next()) previousValueHolder.initialize(rs, 0L).increment(); else previousValueHolder.initialize(1L); sql = null; - LOG.firstFreeId(previousValueHolder.makeValue()); + LOG.debug("First free id: " + previousValueHolder.makeValue()); } finally { rs.close(); @@ -150,19 +146,4 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable { ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Fetching initial value: %s" ) - void fetchingInitialValue( String sql ); - - @LogMessage( level = DEBUG ) - @Message( value = "First free id: %s" ) - void firstFreeId( Number makeValue ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java index 8557aa1b30..8e1ca6e6ae 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java @@ -32,6 +32,7 @@ import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.dialect.Dialect; @@ -43,9 +44,6 @@ import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.mapping.Table; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @@ -285,17 +283,4 @@ public class MultipleHiLoPerTableGenerator hiloOptimizer = new OptimizerFactory.LegacyHiLoAlgorithmOptimizer( returnClass, maxLo ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Could not read or init a hi value" ) - Object unableToReadOrInitHiValue(); - - @Message( value = "Could not update hi value in: %s" ) - Object unableToUpdateHiValue( String tableName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java index 82a77da913..a2630f7422 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java @@ -23,25 +23,20 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; -import org.hibernate.exception.JDBCExceptionHelper; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.mapping.Table; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * sequence
@@ -118,7 +113,7 @@ public class SequenceGenerator implements PersistentIdentifierGenerator, Configu rs.next(); IntegralDataTypeHolder result = buildHolder(); result.initialize( rs, 1 ); - LOG.sequenceIdentifierGenerated(result); + LOG.debug("Sequence identifier generated: " + result); return result; } finally { @@ -162,15 +157,4 @@ public class SequenceGenerator implements PersistentIdentifierGenerator, Configu public String getSequenceName() { return sequenceName; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Sequence identifier generated: %s" ) - void sequenceIdentifierGenerated( IntegralDataTypeHolder result ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java index ec3597172a..ab0c1911d3 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java @@ -24,12 +24,12 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.INFO; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; @@ -38,10 +38,6 @@ import org.hibernate.id.insert.IdentifierGeneratingInsert; import org.hibernate.id.insert.InsertGeneratedIdentifierDelegate; import org.hibernate.sql.Insert; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A generator which combines sequence generation with immediate retrieval @@ -128,15 +124,4 @@ public class SequenceIdentityGenerator extends SequenceGenerator return this; } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Disallowing insert statement comment for select-identity due to Oracle driver bug" ) - void disallowingInsertStatementComment(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java index 7ca826fb78..790928bad5 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java @@ -33,6 +33,7 @@ import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; @@ -41,9 +42,6 @@ import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.mapping.Table; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An IdentifierGenerator that uses a database @@ -230,20 +228,4 @@ public class TableGenerator extends TransactionHelper protected IntegralDataTypeHolder buildHolder() { return IdentifierGeneratorHelper.getIntegralDataTypeHolder( identifierType.getReturnedClass() ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Could not read a hi value" ) - String unableToReadHiValue(); - - @Message( value = "Could not read a hi value - you need to populate the table: %s" ) - String unableToReadHiValue( String tableName ); - - @Message( value = "Could not update hi value in: %s" ) - Object unableToUpdateHiValue( String tableName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java index f29afa6ebd..7cdc2f9208 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java @@ -23,11 +23,11 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.Properties; import java.util.UUID; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; @@ -35,10 +35,6 @@ import org.hibernate.id.uuid.StandardRandomStrategy; import org.hibernate.type.Type; import org.hibernate.type.descriptor.java.UUIDTypeDescriptor; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An {@link IdentifierGenerator} which generates {@link UUID} values using a pluggable @@ -117,19 +113,4 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable { public Serializable generate(SessionImplementor session, Object object) throws HibernateException { return valueTransformer.transform( strategy.generateUUID( session ) ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Unable to instantiate UUID generation strategy class : %s" ) - void unableToInstantiateUuidGenerationStrategy( Exception ignore ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to locate requested UUID generation strategy class : %s" ) - void unableToLocateUuidGenerationStrategy( String strategyClassName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java index 0cd1059e47..98c434931a 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java @@ -23,17 +23,13 @@ */ package org.hibernate.id; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.Properties; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * uuid
@@ -96,16 +92,4 @@ public class UUIDHexGenerator extends AbstractUUIDGenerator implements Configura buf.replace( 4 - formatted.length(), 4, formatted ); return buf.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Using %s which does not generate IETF RFC 4122 compliant UUID values; consider using %s instead" ) - void usingUuidHexGenerator( String name, - String name2 ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java index 189662ecd6..6d5bf34214 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java @@ -23,18 +23,12 @@ */ package org.hibernate.id.enhanced; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.lang.reflect.Constructor; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.id.IntegralDataTypeHolder; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Factory for {@link Optimizer} instances. @@ -259,7 +253,8 @@ public class OptimizerFactory { public HiLoOptimizer(Class returnClass, int incrementSize) { super( returnClass, incrementSize ); if (incrementSize < 1) throw new HibernateException("increment size cannot be less than 1"); - LOG.creatingHiloOptimizer(incrementSize, returnClass.getName()); + LOG.trace("Creating hilo optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + + "]"); } /** @@ -335,7 +330,8 @@ public class OptimizerFactory { public LegacyHiLoAlgorithmOptimizer(Class returnClass, int incrementSize) { super( returnClass, incrementSize ); if (incrementSize < 1) throw new HibernateException("increment size cannot be less than 1"); - LOG.creatingLegacyHiloOptimizer(incrementSize, returnClass.getName()); + LOG.trace("Creating hilo optimizer (legacy) with [incrementSize=" + incrementSize + "; returnClass=" + + returnClass.getName() + "]"); maxLo = incrementSize; lo = maxLo+1; } @@ -400,7 +396,8 @@ public class OptimizerFactory { if ( incrementSize < 1 ) { throw new HibernateException( "increment size cannot be less than 1" ); } - LOG.creatingPooledOptimizer(incrementSize, returnClass.getName()); + LOG.trace("Creating pooled optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + + "]"); } /** @@ -470,7 +467,8 @@ public class OptimizerFactory { if ( incrementSize < 1 ) { throw new HibernateException( "increment size cannot be less than 1" ); } - LOG.creatingPooledLoOptimizer(incrementSize, returnClass.getName()); + LOG.trace("Creating pooled optimizer (lo) with [incrementSize=" + incrementSize + "; returnClass=" + + returnClass.getName() + "]"); } public Serializable generate(AccessCallback callback) { @@ -493,39 +491,4 @@ public class OptimizerFactory { return true; } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Creating hilo optimizer with [incrementSize=%d; returnClass=%s]" ) - void creatingHiloOptimizer( int incrementSize, - String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating hilo optimizer (legacy) with [incrementSize=%d; returnClass=%s]" ) - void creatingLegacyHiloOptimizer( int incrementSize, - String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating pooled optimizer (lo) with [incrementSize=%d; returnClass=%s]" ) - void creatingPooledLoOptimizer( int incrementSize, - String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating pooled optimizer with [incrementSize=%d; returnClass=%s]" ) - void creatingPooledOptimizer( int incrementSize, - String name ); - - @LogMessage( level = INFO ) - @Message( value = "Pooled optimizer source reported [%s] as the initial value; use of 1 or greater highly recommended" ) - void pooledOptimizerReportedInitialValue( IntegralDataTypeHolder value ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to instantiate specified optimizer [%s], falling back to noop" ) - void unableToInstantiateOptimizer( String type ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java index 4b43474d68..22d8c915ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java @@ -24,19 +24,15 @@ */ package org.hibernate.id.enhanced; -import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.IdentifierGeneratorHelper; import org.hibernate.id.IntegralDataTypeHolder; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Describes a sequence. @@ -112,7 +108,7 @@ public class SequenceStructure implements DatabaseStructure { rs.next(); IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( numberType ); value.initialize( rs, 1 ); - LOG.sequenceValueObtained(value.makeValue()); + LOG.debug("Sequence value obtained: " + value.makeValue()); return value; } finally { @@ -161,15 +157,4 @@ public class SequenceStructure implements DatabaseStructure { public String[] sqlDropStrings(Dialect dialect) throws HibernateException { return dialect.getDropSequenceStrings( sequenceName ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Sequence value obtained: %s" ) - void sequenceValueObtained( Number makeValue ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java index 7b7c8049fc..b2dce69a42 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java @@ -23,11 +23,10 @@ */ package org.hibernate.id.enhanced; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.Environment; import org.hibernate.cfg.ObjectNameNormalizer; @@ -38,10 +37,6 @@ import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.mapping.Table; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Generates identifier values based on an sequence-style database structure. @@ -371,21 +366,4 @@ public class SequenceStyleGenerator implements PersistentIdentifierGenerator, Co public String[] sqlDropStrings(Dialect dialect) throws HibernateException { return databaseStructure.sqlDropStrings( dialect ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Forcing table use for sequence-style generator due to pooled optimizer selection where db does not support pooled sequences" ) - void forcingTableUse(); - - @LogMessage( level = WARN ) - @Message( value = "Config specified explicit optimizer of [%s], but [%s=%d; honoring optimizer setting" ) - void honoringOptimizerSetting( String none, - String incrementParam, - int incrementSize ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java index 7014b891e0..9f2ebc815b 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java @@ -23,7 +23,6 @@ */ package org.hibernate.id.enhanced; -import static org.jboss.logging.Logger.Level.INFO; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; @@ -36,6 +35,7 @@ import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.Environment; import org.hibernate.cfg.ObjectNameNormalizer; @@ -51,10 +51,6 @@ import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.mapping.Table; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An enhanced version of table-based id generation. @@ -583,23 +579,4 @@ public class TableGenerator extends TransactionHelper implements PersistentIdent } return new String[] { sqlDropString.toString() }; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Could not read or init a hi value" ) - Object unableToReadOrInitHiValue(); - - @Message( value = "Could not updateQuery hi value in: %s" ) - Object unableToUpdateQueryHiValue( String tableName ); - - @LogMessage( level = INFO ) - @Message( value = "Explicit segment value for id generator [%s.%s] suggested; using default [%s]" ) - void usingDefaultIdGeneratorSegmentValue( String tableName, - String segmentColumnName, - String defaultToUse ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableStructure.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableStructure.java index 351e4d58ca..ec88575699 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableStructure.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/TableStructure.java @@ -32,6 +32,7 @@ import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.TransactionHelper; @@ -40,9 +41,6 @@ import org.hibernate.id.IdentifierGeneratorHelper; import org.hibernate.id.IntegralDataTypeHolder; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.jdbc.util.SQLStatementLogger; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Describes a table used to mimic sequence behavior @@ -209,20 +207,4 @@ public class TableStructure extends TransactionHelper implements DatabaseStructu return value; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Could not read a hi value" ) - String unableToReadHiValue(); - - @Message( value = "Could not read a hi value - you need to populate the table: %s" ) - String unableToReadHiValue( String tableName ); - - @Message( value = "Could not updateQuery hi value in: %s" ) - Object unableToUpdateQueryHiValue( String tableName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/id/factory/DefaultIdentifierGeneratorFactory.java b/hibernate-core/src/main/java/org/hibernate/id/factory/DefaultIdentifierGeneratorFactory.java index 916d216231..38de5704c4 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/factory/DefaultIdentifierGeneratorFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/id/factory/DefaultIdentifierGeneratorFactory.java @@ -23,10 +23,10 @@ */ package org.hibernate.id.factory; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; import org.hibernate.id.Assigned; @@ -47,10 +47,6 @@ import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableGenerator; import org.hibernate.type.Type; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic templated support for {@link IdentifierGeneratorFactory} implementations. @@ -90,14 +86,14 @@ public class DefaultIdentifierGeneratorFactory implements IdentifierGeneratorFac * {@inheritDoc} */ public void setDialect(Dialect dialect) { - LOG.settingDialect(dialect); + LOG.debug("Setting dialect [" + dialect + "]"); this.dialect = dialect; } public void register(String strategy, Class generatorClass) { Object old = generatorStrategyToClassNameMap.put( strategy, generatorClass ); - String msg = LOG.registeringIdentifierGeneratorStrategy(strategy, generatorClass); - if (old != null) msg += LOG.overriding(old); + String msg = "Registering IdentifierGenerator strategy [" + strategy + "] -> [" + generatorClass + "]"; + if (old != null) msg += ", overriding [" + old + "]"; LOG.debug(msg); } @@ -139,22 +135,4 @@ public class DefaultIdentifierGeneratorFactory implements IdentifierGeneratorFac } return generatorClass; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = ", overriding [%s]" ) - String overriding( Object old ); - - @Message( value = "Registering IdentifierGenerator strategy [%s] -> [%s]" ) - String registeringIdentifierGeneratorStrategy( String strategy, - Class generatorClass ); - - @LogMessage( level = DEBUG ) - @Message( value = "Setting dialect [%s]" ) - void settingDialect( Dialect dialect ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java b/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java index 878560c060..9a6cb40346 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java @@ -24,7 +24,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.TRACE; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; @@ -38,6 +37,7 @@ import java.util.Locale; import java.util.TimeZone; import org.hibernate.Hibernate; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.ScrollableResults; import org.hibernate.engine.QueryParameters; @@ -45,10 +45,6 @@ import org.hibernate.engine.SessionImplementor; import org.hibernate.hql.HolderInstantiator; import org.hibernate.loader.Loader; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Implementation of the ScrollableResults interface @@ -135,7 +131,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults { } catch( Throwable ignore ) { // ignore this error for now - LOG.unableToCleanupLoadContext(ignore.getMessage()); + LOG.trace("Exception trying to cleanup load context : " + ignore.getMessage()); } } } @@ -289,15 +285,4 @@ public abstract class AbstractScrollableResults implements ScrollableResults { protected void afterScrollOperation() { session.afterScrollOperation(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Exception trying to cleanup load context : %s" ) - void unableToCleanupLoadContext( String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java b/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java index d5df0a6fbc..c9710ff6a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java @@ -24,7 +24,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -36,10 +35,6 @@ import org.hibernate.event.EventSource; import org.hibernate.hql.HolderInstantiator; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An implementation of java.util.Iterator that is @@ -88,7 +83,7 @@ public final class IteratorImpl implements HibernateIterator { public void close() throws JDBCException { if (ps!=null) { try { - log.debug("closing iterator"); + LOG.debug("Closing iterator"); ps.close(); ps = null; rs = null; @@ -107,20 +102,19 @@ public final class IteratorImpl implements HibernateIterator { } catch( Throwable ignore ) { // ignore this error for now - LOG.unableToCleanupLoadContext(ignore.getMessage()); + LOG.debug("Exception trying to cleanup load context : " + ignore.getMessage()); } } } } private void postNext() throws SQLException { - LOG.retrievingNextResults(); + LOG.debug("Attempting to retrieve next results"); this.hasNext = rs.next(); if (!hasNext) { - LOG.exhaustedResults(); + LOG.debug("Exhausted results"); close(); - } - else LOG.retrievedNextResults(); + } else LOG.debug("Retrieved next results"); } public boolean hasNext() { @@ -134,7 +128,7 @@ public final class IteratorImpl implements HibernateIterator { try { boolean isHolder = holderInstantiator.isRequired(); - LOG.assemblingResults(); + LOG.debug("Assembling results"); if ( single && !isHolder ) { currentResult = types[0].nullSafeGet( rs, names[0], session, null ); } @@ -153,7 +147,7 @@ public final class IteratorImpl implements HibernateIterator { } postNext(); - LOG.returningCurrentResults(); + LOG.debug("Returning current results"); return currentResult; } catch (SQLException sqle) { @@ -185,42 +179,4 @@ public final class IteratorImpl implements HibernateIterator { null ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Assembling results" ) - void assemblingResults(); - - @LogMessage( level = DEBUG ) - @Message( value = "Closing iterator" ) - void closingIterator(); - - @LogMessage( level = DEBUG ) - @Message( value = "Exhausted results" ) - void exhaustedResults(); - - @LogMessage( level = DEBUG ) - @Message( value = "Retrieved next results" ) - void retrievedNextResults(); - - @LogMessage( level = DEBUG ) - @Message( value = "Attempting to retrieve next results" ) - void retrievingNextResults(); - - @LogMessage( level = DEBUG ) - @Message( value = "Returning current results" ) - void returningCurrentResults(); - - @LogMessage( level = DEBUG ) - @Message( value = "Exception trying to cleanup load context : %s" ) - void unableToCleanupLoadContext( String message ); - - @Message( value = "Unable to close iterator" ) - Object unableToCloseIterator(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java b/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java index ba6437be55..c56a60cb65 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java @@ -29,7 +29,6 @@ package org.hibernate.impl; * @author Gail Badner */ -import static org.jboss.logging.Logger.Level.TRACE; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -38,14 +37,11 @@ import java.util.HashMap; import java.util.Map; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; +import org.hibernate.Logger; import org.hibernate.engine.ActionQueue; import org.hibernate.engine.NonFlushedChanges; import org.hibernate.engine.StatefulPersistenceContext; import org.hibernate.event.EventSource; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; public final class NonFlushedChangesImpl implements NonFlushedChanges { @@ -71,7 +67,7 @@ public final class NonFlushedChangesImpl implements NonFlushedChanges { } private void writeObject(ObjectOutputStream oos) throws IOException { - LOG.serializingSessionNonFlushedChanges(); + LOG.trace("Serializing SessionNonFlushedChanges"); oos.defaultWriteObject(); oos.writeObject( entityMode.toString() ); persistenceContext.serialize( oos ); @@ -108,15 +104,4 @@ public final class NonFlushedChangesImpl implements NonFlushedChanges { public void clear() { nonFlushedChangesByEntityMode.clear(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Serializing SessionNonFlushedChanges" ) - void serializingSessionNonFlushedChanges(); - } } \ No newline at end of file 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 6e0cc6490a..96bafaf8b5 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java @@ -23,10 +23,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; @@ -54,6 +50,7 @@ import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; import org.hibernate.Interceptor; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.ObjectNotFoundException; import org.hibernate.QueryException; @@ -74,10 +71,6 @@ import org.hibernate.cache.impl.CacheDataDescriptionImpl; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; -import org.hibernate.exception.SQLExceptionConverter; -import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.context.CurrentSessionContext; import org.hibernate.context.JTASessionContext; import org.hibernate.context.ManagedSessionContext; @@ -90,12 +83,15 @@ import org.hibernate.engine.NamedQueryDefinition; import org.hibernate.engine.NamedSQLQueryDefinition; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; import org.hibernate.engine.profile.Association; import org.hibernate.engine.profile.Fetch; import org.hibernate.engine.profile.FetchProfile; import org.hibernate.engine.query.QueryPlanCache; import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; import org.hibernate.event.EventListeners; +import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.UUIDGenerator; import org.hibernate.id.factory.IdentifierGeneratorFactory; @@ -111,6 +107,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.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.stat.ConcurrentStatisticsImpl; import org.hibernate.stat.Statistics; @@ -126,10 +123,6 @@ import org.hibernate.type.TypeResolver; import org.hibernate.util.CollectionHelper; import org.hibernate.util.EmptyIterator; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -210,7 +203,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI this.statistics = new ConcurrentStatisticsImpl( this ); getStatistics().setStatisticsEnabled( settings.isStatisticsEnabled() ); - LOG.statisticsInitialized(settings.isStatisticsEnabled()); + LOG.debug("Statistics initialized [enabled=" + settings.isStatisticsEnabled() + "]}"); this.properties = new Properties(); this.properties.putAll( cfg.getProperties() ); @@ -232,8 +225,8 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI this.filters = new HashMap(); this.filters.putAll( cfg.getFilterDefinitions() ); - LOG.sessionFactoryConstructedWithFilterConfigurations(filters); - LOG.instantiatingSessionFactory(properties); + LOG.debug("Session factory constructed with filter configurations : " + filters); + LOG.debug("Instantiating session factory with properties: " + properties); // Caches settings.getRegionFactory().start( settings, properties ); @@ -277,7 +270,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI if ( accessStrategy == null && settings.isSecondLevelCacheEnabled() ) { final AccessType accessType = AccessType.parse( model.getCacheConcurrencyStrategy() ); if ( accessType != null ) { - LOG.buildingCacheForEntityData(model.getEntityName()); + LOG.trace("Building cache for entity data [" + model.getEntityName() + "]"); EntityRegion entityRegion = settings.getRegionFactory().buildEntityRegion( cacheRegionName, properties, CacheDataDescriptionImpl.decode( model ) ); accessStrategy = entityRegion.buildAccessStrategy( accessType ); entityAccessStrategies.put( cacheRegionName, accessStrategy ); @@ -299,7 +292,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI final AccessType accessType = AccessType.parse( model.getCacheConcurrencyStrategy() ); CollectionRegionAccessStrategy accessStrategy = null; if ( accessType != null && settings.isSecondLevelCacheEnabled() ) { - LOG.buildingCacheForCollectionData(model.getRole()); + LOG.trace("Building cache for collection data [" + model.getRole() + "]"); CollectionRegion collectionRegion = settings.getRegionFactory().buildCollectionRegion( cacheRegionName, properties, CacheDataDescriptionImpl.decode( model ) ); accessStrategy = collectionRegion.buildAccessStrategy( accessType ); entityAccessStrategies.put( cacheRegionName, accessStrategy ); @@ -367,7 +360,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } SessionFactoryObjectFactory.addInstance(uuid, name, this, properties); - LOG.instantiatedSessionFactory(); + LOG.debug("Instantiated session factory"); if ( settings.isAutoCreateSchema() ) { new SchemaExport( getJdbcServices(), cfg ).create( false, true ); @@ -383,7 +376,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } if ( settings.getTransactionManagerLookup()!=null ) { - LOG.obtainingJtaTransactionManager(); + LOG.debug("Obtaining JTA TransactionManager"); transactionManager = settings.getTransactionManagerLookup().getTransactionManager(properties); } else { @@ -535,7 +528,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI Map errors = new HashMap(); // Check named HQL queries - LOG.checkingNamedHqlQueries(namedQueries.size()); + LOG.debug("Checking " + namedQueries.size() + " named HQL queries"); Iterator itr = namedQueries.entrySet().iterator(); while ( itr.hasNext() ) { final Map.Entry entry = ( Map.Entry ) itr.next(); @@ -543,7 +536,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI final NamedQueryDefinition qd = ( NamedQueryDefinition ) entry.getValue(); // this will throw an error if there's something wrong. try { - LOG.checkingNamedQuery(queryName); + LOG.debug("Checking named query: " + queryName); //TODO: BUG! this currently fails for named queries for non-POJO entities queryPlanCache.getHQLQueryPlan( qd.getQueryString(), false, CollectionHelper.EMPTY_MAP ); } @@ -555,7 +548,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } } - LOG.checkingNamedSqlQueries(namedSqlQueries.size()); + LOG.debug("Checking " + namedSqlQueries.size() + " named SQL queries"); itr = namedSqlQueries.entrySet().iterator(); while ( itr.hasNext() ) { final Map.Entry entry = ( Map.Entry ) itr.next(); @@ -563,7 +556,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI final NamedSQLQueryDefinition qd = ( NamedSQLQueryDefinition ) entry.getValue(); // this will throw an error if there's something wrong. try { - LOG.checkingNamedSqlQuery(queryName); + LOG.debug("Checking named SQL query: " + queryName); // TODO : would be really nice to cache the spec on the query-def so as to not have to re-calc the hash; // currently not doable though because of the resultset-ref stuff... NativeSQLQuerySpecification spec; @@ -744,7 +737,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI // from javax.naming.Referenceable public Reference getReference() throws NamingException { - LOG.returningReferenceToSessionFactory(); + LOG.debug("Returning a Reference to the SessionFactory"); return new Reference( SessionFactoryImpl.class.getName(), new StringRefAddr("uuid", uuid), @@ -754,7 +747,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } private Object readResolve() throws ObjectStreamException { - LOG.resolvingSerializedSessionFactory(); + LOG.trace("Resolving serialized SessionFactory"); // look for the instance by uuid Object result = SessionFactoryObjectFactory.getInstance(uuid); if (result==null) { @@ -762,8 +755,8 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI // (alternatively we could do an actual JNDI lookup here....) result = SessionFactoryObjectFactory.getNamedInstance(name); if (result == null) throw new InvalidObjectException("Could not find a SessionFactory named: " + name); - LOG.resolvedSessionFactoryByName(); - } else LOG.resolvedSessionFactoryByUid(); + LOG.debug("Resolved SessionFactory by name"); + } else LOG.debug("Resolved SessionFactory by UID"); return result; } @@ -787,15 +780,15 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - LOG.deserializing(); + LOG.trace("Deserializing"); in.defaultReadObject(); - LOG.deserialized(uuid); + LOG.debug("Deserialized: " + uuid); } private void writeObject(ObjectOutputStream out) throws IOException { - LOG.serializing(uuid); + LOG.debug("Serializing: " + uuid); out.defaultWriteObject(); - LOG.serialized(); + LOG.trace("Serialized"); } public Type[] getReturnTypes(String queryString) throws HibernateException { @@ -923,7 +916,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void close() throws HibernateException { if ( isClosed ) { - LOG.alreadyClosed(); + LOG.trace("Already closed"); return; } @@ -988,9 +981,8 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictEntity(String entityName, Serializable identifier) { EntityPersister p = getEntityPersister( entityName ); if ( p.hasCache() ) { - if (LOG.isDebugEnabled()) LOG.evictingSecondLevelCache(MessageHelper.infoString(p, - identifier, - SessionFactoryImpl.this)); + if (LOG.isDebugEnabled()) LOG.debug("Evicting second-level cache: " + + MessageHelper.infoString(p, identifier, SessionFactoryImpl.this)); p.getCacheAccessStrategy().evict( buildCacheKey( identifier, p ) ); } } @@ -1012,7 +1004,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictEntityRegion(String entityName) { EntityPersister p = getEntityPersister( entityName ); if ( p.hasCache() ) { - LOG.evictingSecondLevelCache(p.getEntityName()); + LOG.debug("Evicting second-level cache: " + p.getEntityName()); p.getCacheAccessStrategy().evictAll(); } } @@ -1033,9 +1025,10 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictCollection(String role, Serializable ownerIdentifier) { CollectionPersister p = getCollectionPersister( role ); if ( p.hasCache() ) { - if (LOG.isDebugEnabled()) LOG.evictingSecondLevelCache(MessageHelper.collectionInfoString(p, - ownerIdentifier, - SessionFactoryImpl.this)); + if (LOG.isDebugEnabled()) LOG.debug("Evicting second-level cache: " + + MessageHelper.collectionInfoString(p, + ownerIdentifier, + SessionFactoryImpl.this)); CacheKey cacheKey = buildCacheKey( ownerIdentifier, p ); p.getCacheAccessStrategy().evict( cacheKey ); } @@ -1054,7 +1047,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictCollectionRegion(String role) { CollectionPersister p = getCollectionPersister( role ); if ( p.hasCache() ) { - LOG.evictingSecondLevelCache(p.getRole()); + LOG.debug("Evicting second-level cache: " + p.getRole()); p.getCacheAccessStrategy().evictAll(); } } @@ -1296,7 +1289,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } Object result = SessionFactoryObjectFactory.getInstance( uuid ); if ( result == null ) { - LOG.unableToLocateSessionFactoryByUuid(uuid); + LOG.trace("Could not locate session factory by uuid [" + uuid + "] during session deserialization; trying name"); if ( isNamed ) { result = SessionFactoryObjectFactory.getNamedInstance( name ); } @@ -1306,117 +1299,4 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } return ( SessionFactoryImpl ) result; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Already closed" ) - void alreadyClosed(); - - @LogMessage( level = WARN ) - @Message( value = "JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()" ) - void autoFlushWillNotWork(); - - @LogMessage( level = TRACE ) - @Message( value = "Building cache for collection data [%s]" ) - void buildingCacheForCollectionData( String role ); - - @LogMessage( level = TRACE ) - @Message( value = "Building cache for entity data [%s]" ) - void buildingCacheForEntityData( String entityName ); - - @LogMessage( level = INFO ) - @Message( value = "Building session factory" ) - void buildingSessionFactory(); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking %d named HQL queries" ) - void checkingNamedHqlQueries( int size ); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking named query: %s" ) - void checkingNamedQuery( String queryName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking %d named SQL queries" ) - void checkingNamedSqlQueries( int size ); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking named SQL query: %s" ) - void checkingNamedSqlQuery( String queryName ); - - @LogMessage( level = INFO ) - @Message( value = "Closing" ) - void closing(); - - @LogMessage( level = DEBUG ) - @Message( value = "Deserialized: %s" ) - void deserialized( String uuid ); - - @LogMessage( level = TRACE ) - @Message( value = "Deserializing" ) - void deserializing(); - - @LogMessage( level = DEBUG ) - @Message( value = "Evicting second-level cache: %s" ) - void evictingSecondLevelCache( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Instantiated session factory" ) - void instantiatedSessionFactory(); - - @LogMessage( level = DEBUG ) - @Message( value = "Instantiating session factory with properties: %s" ) - void instantiatingSessionFactory( Properties properties ); - - @Message( value = "Error in named query: %s" ) - Object namedQueryError( String queryName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Obtaining JTA TransactionManager" ) - void obtainingJtaTransactionManager(); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolved SessionFactory by name" ) - void resolvedSessionFactoryByName(); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolved SessionFactory by UID" ) - void resolvedSessionFactoryByUid(); - - @LogMessage( level = TRACE ) - @Message( value = "Resolving serialized SessionFactory" ) - void resolvingSerializedSessionFactory(); - - @LogMessage( level = DEBUG ) - @Message( value = "Returning a Reference to the SessionFactory" ) - void returningReferenceToSessionFactory(); - - @LogMessage( level = DEBUG ) - @Message( value = "Serializing: %s" ) - void serializing( String uuid ); - - @LogMessage( level = TRACE ) - @Message( value = "Serialized" ) - void serialized(); - - @LogMessage( level = DEBUG ) - @Message( value = "Session factory constructed with filter configurations : %s" ) - void sessionFactoryConstructedWithFilterConfigurations( Map filters ); - - @LogMessage( level = DEBUG ) - @Message( value = "Statistics initialized [enabled=%s]}" ) - void statisticsInitialized( boolean statisticsEnabled ); - - @Message( value = "Unable to construct current session context [%s]" ) - Object unableToConstructCurrentSessionContext( String impl ); - - @LogMessage( level = TRACE ) - @Message( value = "Could not locate session factory by uuid [%s] during session deserialization; trying name" ) - void unableToLocateSessionFactoryByUuid( String uuid ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java index 9f86c17539..31b9cebc1a 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java @@ -23,9 +23,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; @@ -41,12 +38,9 @@ import javax.naming.event.NamingEvent; import javax.naming.event.NamingExceptionEvent; import javax.naming.event.NamingListener; import javax.naming.spi.ObjectFactory; +import org.hibernate.Logger; import org.hibernate.SessionFactory; import org.hibernate.internal.util.jndi.JndiHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Resolves {@link SessionFactory} instances during JNDI look-ups as well as during deserialization @@ -61,7 +55,7 @@ public class SessionFactoryObjectFactory implements ObjectFactory { static { INSTANCE = new SessionFactoryObjectFactory(); - LOG.initializingSessionFactoryObjectFactory(); + LOG.debug("Initializing class SessionFactoryObjectFactory"); } private static final ConcurrentHashMap INSTANCES = new ConcurrentHashMap(); @@ -69,7 +63,7 @@ public class SessionFactoryObjectFactory implements ObjectFactory { private static final NamingListener LISTENER = new NamespaceChangeListener() { public void objectAdded(NamingEvent evt) { - LOG.factoryBoundToName(evt.getNewBinding().getName()); + LOG.debug("A factory was successfully bound to name: " + evt.getNewBinding().getName()); } public void objectRemoved(NamingEvent evt) { String name = evt.getOldBinding().getName(); @@ -92,21 +86,19 @@ public class SessionFactoryObjectFactory implements ObjectFactory { }; public Object getObjectInstance(Object reference, Name name, Context ctx, Hashtable env) throws Exception { - LOG.jndiLookup(name); + LOG.debug("JNDI lookup: " + name); String uid = (String) ( (Reference) reference ).get(0).getContent(); return getInstance(uid); } public static void addInstance(String uid, String name, SessionFactory instance, Properties properties) { - - LOG.registered(uid, name == null ? LOG.unnamed() : name); + LOG.debug("Registered: " + uid + " (" + (name == null ? "" : name) + ")"); INSTANCES.put(uid, instance); if (name!=null) NAMED_INSTANCES.put(name, instance); //must add to JNDI _after_ adding to HashMaps, because some JNDI servers use serialization if (name == null) LOG.notBindingFactoryToJndi(); else { - LOG.factoryName(name); try { @@ -124,9 +116,7 @@ public class SessionFactoryObjectFactory implements ObjectFactory { catch(ClassCastException cce) { LOG.initialContextDidNotImplementEventContext(); } - } - } public static void removeInstance(String uid, String name, Properties properties) { @@ -156,113 +146,22 @@ public class SessionFactoryObjectFactory implements ObjectFactory { } public static Object getNamedInstance(String name) { - LOG.lookupName(name); + LOG.debug("Lookup: name=" + name); Object result = NAMED_INSTANCES.get(name); if (result==null) { - LOG.notFound(name); + LOG.debug("Not found: " + name); LOG.debug(NAMED_INSTANCES.toString()); } return result; } public static Object getInstance(String uid) { - LOG.lookupUid(uid); + LOG.debug("Lookup: uid=" + uid); Object result = INSTANCES.get(uid); if (result==null) { - LOG.notFound(uid); + LOG.debug("Not found: " + uid); LOG.debug(INSTANCES.toString()); } return result; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Bound factory to JNDI name: %s" ) - void factoryBoundToJndiName( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "A factory was successfully bound to name: %s" ) - void factoryBoundToName( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Factory name: %s" ) - void factoryName( String name ); - - @LogMessage( level = INFO ) - @Message( value = "A factory was renamed from name: %s" ) - void factoryRenamedFromName( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Unbound factory from JNDI name: %s" ) - void factoryUnboundFromJndiName( String name ); - - @LogMessage( level = INFO ) - @Message( value = "A factory was unbound from name: %s" ) - void factoryUnboundFromName( String name ); - - @LogMessage( level = WARN ) - @Message( value = "InitialContext did not implement EventContext" ) - void initialContextDidNotImplementEventContext(); - - @LogMessage( level = DEBUG ) - @Message( value = "Initializing class SessionFactoryObjectFactory" ) - void initializingSessionFactoryObjectFactory(); - - @Message( value = "Invalid JNDI name: %s" ) - Object invalidJndiName( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "JNDI lookup: %s" ) - void jndiLookup( Name name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Lookup: name=%s" ) - void lookupName( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Lookup: uid=%s" ) - void lookupUid( String uid ); - - @LogMessage( level = WARN ) - @Message( value = "Naming exception occurred accessing factory: %s" ) - void namingExceptionAccessingFactory( NamingException exception ); - - @LogMessage( level = INFO ) - @Message( value = "Not binding factory to JNDI, no JNDI name configured" ) - void notBindingFactoryToJndi(); - - @LogMessage( level = DEBUG ) - @Message( value = "Not found: %s" ) - void notFound( String name ); - - @LogMessage( level = DEBUG ) - @Message( value = "Registered: %s (%s)" ) - void registered( String uid, - String string ); - - @Message( value = "Could not bind factory to JNDI" ) - Object unableToBindFactoryToJndi(); - - @Message( value = "Could not unbind factory from JNDI" ) - Object unableToUnbindFactoryFromJndi(); - - @LogMessage( level = INFO ) - @Message( value = "Unbinding factory from JNDI name: %s" ) - void unbindingFactoryFromJndiName( String name ); - - @Message( value = "" ) - String unnamed(); - } -} - - - - - - - +} \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java b/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java index ec41fb2db7..e31c5de74e 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java @@ -24,9 +24,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -59,6 +56,7 @@ import org.hibernate.Interceptor; import org.hibernate.LobHelper; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.ObjectDeletedException; import org.hibernate.Query; @@ -140,10 +138,6 @@ import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.CollectionHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -215,7 +209,7 @@ public final class SessionImpl extends AbstractSessionImpl if (factory.getStatistics().isStatisticsEnabled()) factory.getStatisticsImplementor().openSession(); - LOG.openedSession(entityMode); + LOG.debug("Opened session [" + entityMode + "]"); } /** @@ -259,7 +253,7 @@ public final class SessionImpl extends AbstractSessionImpl if (factory.getStatistics().isStatisticsEnabled()) factory.getStatisticsImplementor().openSession(); - LOG.openedSessionAt(timestamp); + LOG.debug("Opened session at timestamp: " + timestamp); } public Session getSession(EntityMode entityMode) { @@ -303,7 +297,7 @@ public final class SessionImpl extends AbstractSessionImpl } public Connection close() throws HibernateException { - LOG.closingSession(); + LOG.trace("Closing session"); if ( isClosed() ) { throw new SessionException( "Session was already closed" ); } @@ -364,10 +358,10 @@ public final class SessionImpl extends AbstractSessionImpl public void managedFlush() { if ( isClosed() ) { - LOG.skippingAutoFlush(); + LOG.trace("Skipping auto-flush due to session closed"); return; } - LOG.automaticallyFlushingSession(); + LOG.trace("Automatically flushing session"); flush(); if ( childSessionsByEntityMode != null ) { @@ -515,7 +509,7 @@ public final class SessionImpl extends AbstractSessionImpl } public void managedClose() { - LOG.automaticallyClosingSession(); + LOG.trace("Automatically closing session"); close(); } @@ -536,26 +530,26 @@ public final class SessionImpl extends AbstractSessionImpl public Connection disconnect() throws HibernateException { errorIfClosed(); - LOG.disconnectingSession(); + LOG.debug("Disconnecting session"); return jdbcContext.getConnectionManager().manualDisconnect(); } public void reconnect() throws HibernateException { errorIfClosed(); - LOG.reconnectingSession(); + LOG.debug("Reconnecting session"); checkTransactionSynchStatus(); jdbcContext.getConnectionManager().manualReconnect(); } public void reconnect(Connection conn) throws HibernateException { errorIfClosed(); - LOG.reconnectingSession(); + LOG.debug("Reconnecting session"); checkTransactionSynchStatus(); jdbcContext.getConnectionManager().manualReconnect( conn ); } public void beforeTransactionCompletion(Transaction tx) { - LOG.beforeTransactionCompletion(); + LOG.trace("Before transaction completion"); actionQueue.beforeTransactionCompletion(); if ( rootSession == null ) { try { @@ -585,7 +579,7 @@ public final class SessionImpl extends AbstractSessionImpl } public void afterTransactionCompletion(boolean success, Transaction tx) { - LOG.afterTransactionCompletion(); + LOG.trace("After transaction completion"); persistenceContext.afterTransactionCompletion(); actionQueue.afterTransactionCompletion(success); if ( rootSession == null && tx != null ) { @@ -1007,7 +1001,7 @@ public final class SessionImpl extends AbstractSessionImpl public Object immediateLoad(String entityName, Serializable id) throws HibernateException { if (LOG.isDebugEnabled()) { EntityPersister persister = getFactory().getEntityPersister(entityName); - LOG.initializingProxy(MessageHelper.infoString(persister, id, getFactory())); + LOG.debug("Initializing proxy: " + MessageHelper.infoString(persister, id, getFactory())); } LoadEvent event = new LoadEvent(id, entityName, true, this); @@ -1178,19 +1172,17 @@ public final class SessionImpl extends AbstractSessionImpl public boolean isDirty() throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); - LOG.checkingSessionDirtiness(); + LOG.debug("Checking session dirtiness"); if ( actionQueue.areInsertionsOrDeletionsQueued() ) { - LOG.sessionDirty(); + LOG.debug("Session dirty (scheduled updates and insertions)"); return true; } - else { - DirtyCheckEvent event = new DirtyCheckEvent(this); - DirtyCheckEventListener[] dirtyCheckEventListener = listeners.getDirtyCheckEventListeners(); - for ( int i = 0; i < dirtyCheckEventListener.length; i++ ) { - dirtyCheckEventListener[i].onDirtyCheck(event); - } - return event.isDirty(); + DirtyCheckEvent event = new DirtyCheckEvent(this); + DirtyCheckEventListener[] dirtyCheckEventListener = listeners.getDirtyCheckEventListeners(); + for (int i = 0; i < dirtyCheckEventListener.length; i++) { + dirtyCheckEventListener[i].onDirtyCheck(event); } + return event.isDirty(); } public void flush() throws HibernateException { @@ -1207,9 +1199,10 @@ public final class SessionImpl extends AbstractSessionImpl public void forceFlush(EntityEntry entityEntry) throws HibernateException { errorIfClosed(); - if (LOG.isDebugEnabled()) LOG.flushingToForceDeletion(MessageHelper.infoString(entityEntry.getPersister(), - entityEntry.getId(), - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Flushing to force deletion of re-saved object: " + + MessageHelper.infoString(entityEntry.getPersister(), + entityEntry.getId(), + getFactory())); if ( persistenceContext.getCascadeLevel() > 0 ) { throw new ObjectDeletedException( @@ -1358,8 +1351,8 @@ public final class SessionImpl extends AbstractSessionImpl } if (LOG.isTraceEnabled()) { - LOG.delete(query); - if (values.length != 0) LOG.parameters(StringHelper.toString(values)); + LOG.trace("delete: " + query); + if (values.length != 0) LOG.trace("Parameters: " + StringHelper.toString(values)); } List list = find( query, values, types ); @@ -1415,7 +1408,7 @@ public final class SessionImpl extends AbstractSessionImpl public void setFlushMode(FlushMode flushMode) { errorIfClosed(); checkTransactionSynchStatus(); - LOG.settingFlushMode(flushMode); + LOG.trace("Setting flush mode to: " + flushMode); this.flushMode = flushMode; } @@ -1432,7 +1425,7 @@ public final class SessionImpl extends AbstractSessionImpl public void setCacheMode(CacheMode cacheMode) { errorIfClosed(); checkTransactionSynchStatus(); - LOG.settingCacheMode(cacheMode); + LOG.trace("Setting cache mode to: " + cacheMode); this.cacheMode= cacheMode; } @@ -1783,7 +1776,7 @@ public final class SessionImpl extends AbstractSessionImpl errorIfClosed(); checkTransactionSynchStatus(); - LOG.scrollSqlQuery(customQuery.getSQL()); + LOG.trace("Scroll SQL query: " + customQuery.getSQL()); CustomLoader loader = new CustomLoader( customQuery, getFactory() ); @@ -1804,7 +1797,7 @@ public final class SessionImpl extends AbstractSessionImpl errorIfClosed(); checkTransactionSynchStatus(); - LOG.sqlQuery(customQuery.getSQL()); + LOG.trace("SQL query: " + customQuery.getSQL()); CustomLoader loader = new CustomLoader( customQuery, getFactory() ); @@ -2095,7 +2088,7 @@ public final class SessionImpl extends AbstractSessionImpl * @throws ClassNotFoundException Indicates a class resolution issue */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { - LOG.deserializingSession(); + LOG.trace("Deserializing session"); ois.defaultReadObject(); @@ -2156,7 +2149,7 @@ public final class SessionImpl extends AbstractSessionImpl throw new IllegalStateException( "Cannot serialize a session while connected" ); } - LOG.serializingSession(); + LOG.trace("Serializing session"); oos.defaultWriteObject(); @@ -2342,109 +2335,4 @@ public final class SessionImpl extends AbstractSessionImpl fireLock( object, lockOptions ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "After transaction completion" ) - void afterTransactionCompletion(); - - @LogMessage( level = TRACE ) - @Message( value = "Automatically closing session" ) - void automaticallyClosingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Automatically flushing session" ) - void automaticallyFlushingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Before transaction completion" ) - void beforeTransactionCompletion(); - - @LogMessage( level = DEBUG ) - @Message( value = "Checking session dirtiness" ) - void checkingSessionDirtiness(); - - @LogMessage( level = TRACE ) - @Message( value = "Closing session" ) - void closingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "delete: %s" ) - void delete( String query ); - - @LogMessage( level = TRACE ) - @Message( value = "Deserializing session" ) - void deserializingSession(); - - @LogMessage( level = DEBUG ) - @Message( value = "Disconnecting session" ) - void disconnectingSession(); - - @Message( value = "Exception in interceptor afterTransactionCompletion()" ) - Object exceptionInAfterTransactionCompletionInterceptor(); - - @Message( value = "Exception in interceptor beforeTransactionCompletion()" ) - Object exceptionInBeforeTransactionCompletionInterceptor(); - - @LogMessage( level = DEBUG ) - @Message( value = "Flushing to force deletion of re-saved object: %s" ) - void flushingToForceDeletion( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Initializing proxy: %s" ) - void initializingProxy( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Opened session [%s]" ) - void openedSession( EntityMode entityMode ); - - @LogMessage( level = DEBUG ) - @Message( value = "Opened session at timestamp: %ld" ) - void openedSessionAt( long timestamp ); - - @LogMessage( level = TRACE ) - @Message( value = "Parameters: %s" ) - void parameters( String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Reconnecting session" ) - void reconnectingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Scroll SQL query: %s" ) - void scrollSqlQuery( String sql ); - - @LogMessage( level = TRACE ) - @Message( value = "Serializing session" ) - void serializingSession(); - - @LogMessage( level = DEBUG ) - @Message( value = "Session dirty (scheduled updates and insertions)" ) - void sessionDirty(); - - @LogMessage( level = TRACE ) - @Message( value = "Setting cache mode to: %s" ) - void settingCacheMode( CacheMode cacheMode ); - - @LogMessage( level = TRACE ) - @Message( value = "Setting flush mode to: %s" ) - void settingFlushMode( FlushMode flushMode ); - - @LogMessage( level = TRACE ) - @Message( value = "Skipping auto-flush due to session closed" ) - void skippingAutoFlush(); - - @LogMessage( level = TRACE ) - @Message( value = "SQL query: %s" ) - void sqlQuery( String sql ); - - @LogMessage( level = WARN ) - @Message( value = "Transaction started on non-root session" ) - void transactionStartedOnNonRootSession(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java b/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java index cb70a1c202..88689a18b4 100755 --- a/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java @@ -21,7 +21,6 @@ */ package org.hibernate.impl; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.sql.Connection; import java.util.Collections; @@ -38,6 +37,7 @@ import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; @@ -70,10 +70,6 @@ import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.type.Type; import org.hibernate.util.CollectionHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @author Gavin King @@ -203,7 +199,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl public void refresh(String entityName, Object entity, LockMode lockMode) { final EntityPersister persister = this.getEntityPersister( entityName, entity ); final Serializable id = persister.getIdentifier( entity, this ); - if (LOG.isTraceEnabled()) LOG.refreshingTransient(MessageHelper.infoString(persister, id, this.getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Refreshing transient " + MessageHelper.infoString(persister, id, this.getFactory())); // TODO : can this ever happen??? // EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); // if ( source.getPersistenceContext().getEntry( key ) != null ) { @@ -689,15 +685,4 @@ public class StatelessSessionImpl extends AbstractSessionImpl temporaryPersistenceContext.clear(); return result; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Refreshing transient %s" ) - void refreshingTransient( String infoString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/jdbc/TypeInfoExtracter.java b/hibernate-core/src/main/java/org/hibernate/internal/util/jdbc/TypeInfoExtracter.java index 87b906e618..f983562baa 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/jdbc/TypeInfoExtracter.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/jdbc/TypeInfoExtracter.java @@ -23,16 +23,12 @@ */ package org.hibernate.internal.util.jdbc; -import static org.jboss.logging.Logger.Level.WARN; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedHashSet; +import org.hibernate.Logger; import org.hibernate.util.ArrayHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Helper to extract type innformation from {@link DatabaseMetaData JDBC metadata} @@ -104,23 +100,4 @@ public class TypeInfoExtracter { } return value.split( "," ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Error accessing type info result set : %s" ) - void unableToAccessTypeInfoResultSet( String string ); - - @LogMessage( level = WARN ) - @Message( value = "Unable to release type info result set" ) - void unableToReleaseTypeInfoResultSet(); - - @LogMessage( level = WARN ) - @Message( value = "Unable to retrieve type info result set : %s" ) - void unableToRetrieveTypeInfoResultSet( String string ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/jndi/JndiHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/jndi/JndiHelper.java index 6e53655400..2d299e844c 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/jndi/JndiHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/jndi/JndiHelper.java @@ -23,9 +23,6 @@ */ package org.hibernate.internal.util.jndi; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.Hashtable; import java.util.Map; import java.util.Properties; @@ -35,11 +32,8 @@ import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NamingException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; public final class JndiHelper { @@ -118,7 +112,7 @@ public final class JndiHelper { */ public static void bind(String jndiName, Object value, Context context) { try { - LOG.binding(jndiName); + LOG.trace("Binding : " + jndiName); context.rebind( jndiName, value ); } catch ( Exception initialException ) { @@ -131,7 +125,7 @@ public final class JndiHelper { Context intermediateContext = null; try { - LOG.intermediateLookup(intermediateContextName); + LOG.trace("Intermediate lookup: " + intermediateContextName); intermediateContext = (Context) intermediateContextBase.lookup( intermediateContextName ); } catch ( NameNotFoundException handledBelow ) { @@ -141,9 +135,9 @@ public final class JndiHelper { throw new JndiException( "Unaniticipated error doing intermediate lookup", e ); } - if (intermediateContext != null) LOG.foundIntermediateContext(intermediateContextName); + if (intermediateContext != null) LOG.trace("Found intermediate context: " + intermediateContextName); else { - LOG.creatingSubcontextTrace(intermediateContextName); + LOG.trace("Creating subcontext: " + intermediateContextName); try { intermediateContext = intermediateContextBase.createSubcontext( intermediateContextName ); } @@ -154,7 +148,7 @@ public final class JndiHelper { intermediateContextBase = intermediateContext; n = n.getSuffix( 1 ); } - LOG.binding(n); + LOG.trace("Binding : " + n); try { intermediateContextBase.rebind( n, value ); } @@ -162,7 +156,7 @@ public final class JndiHelper { throw new JndiException( "Error performing intermediate bind [" + n + "]", e ); } } - LOG.boundName(jndiName); + LOG.debug("Bound name: " + jndiName); } private static Name tokenizeName(String jndiName, Context context) { @@ -210,7 +204,7 @@ public final class JndiHelper { */ public static void bind(Context ctx, String name, Object val) throws NamingException { try { - LOG.binding(name); + LOG.trace("Binding : " + name); ctx.rebind(name, val); } catch (Exception e) { @@ -220,13 +214,13 @@ public final class JndiHelper { Context subctx=null; try { - LOG.lookup(ctxName); + LOG.trace("Lookup: " + ctxName); subctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException nfe) {} if (subctx!=null) { - LOG.foundSubcontext(ctxName); + LOG.debug("Found subcontext: " + ctxName); ctx = subctx; } else { @@ -235,56 +229,10 @@ public final class JndiHelper { } n = n.getSuffix(1); } - LOG.binding(n); + LOG.trace("Binding : " + n); ctx.rebind(n, val); } - LOG.boundName(name); + LOG.debug("Bound name: " + name); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Binding : %s" ) - void binding( Object jndiName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Bound name: %s" ) - void boundName( String jndiName ); - - @LogMessage( level = INFO ) - @Message( value = "Creating subcontext: %s" ) - void creatingSubcontextInfo( String intermediateContextName ); - - @LogMessage( level = TRACE ) - @Message( value = "Creating subcontext: %s" ) - void creatingSubcontextTrace( String intermediateContextName ); - - @LogMessage( level = TRACE ) - @Message( value = "Found intermediate context: %s" ) - void foundIntermediateContext( String intermediateContextName ); - - @LogMessage( level = DEBUG ) - @Message( value = "Found subcontext: %s" ) - void foundSubcontext( String ctxName ); - - @LogMessage( level = TRACE ) - @Message( value = "Intermediate lookup: %s" ) - void intermediateLookup( String intermediateContextName ); - - @LogMessage( level = INFO ) - @Message( value = "JNDI InitialContext properties:%s" ) - void jndiInitialContextProperties( Hashtable hash ); - - @LogMessage( level = TRACE ) - @Message( value = "Lookup: %s" ) - void lookup( String ctxName ); - - @Message( value = "Could not obtain initial context" ) - Object unableToObtainInitialContext(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/jdbc/AbstractBatcher.java b/hibernate-core/src/main/java/org/hibernate/jdbc/AbstractBatcher.java deleted file mode 100644 index e3c2d3808a..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/jdbc/AbstractBatcher.java +++ /dev/null @@ -1,714 +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.jdbc; - -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ConcurrentModificationException; -import java.util.HashSet; -import java.util.Iterator; -import org.hibernate.AssertionFailure; -import org.hibernate.HibernateException; -import org.hibernate.Interceptor; -import org.hibernate.ScrollMode; -import org.hibernate.TransactionException; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.exception.JDBCExceptionHelper; -import org.hibernate.jdbc.util.FormatStyle; -import org.hibernate.util.JDBCExceptionReporter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Manages prepared statements and batching. - * - * @author Gavin King - */ -public abstract class AbstractBatcher implements Batcher { - - private static int globalOpenPreparedStatementCount; - private static int globalOpenResultSetCount; - - private int openPreparedStatementCount; - private int openResultSetCount; - - static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, - AbstractBatcher.class.getPackage().getName()); - - private final ConnectionManager connectionManager; - private final SessionFactoryImplementor factory; - - private PreparedStatement batchUpdate; - private String batchUpdateSQL; - - private HashSet statementsToClose = new HashSet(); - private HashSet resultSetsToClose = new HashSet(); - private PreparedStatement lastQuery; - - private boolean releasing = false; - private final Interceptor interceptor; - - private long transactionTimeout = -1; - boolean isTransactionTimeoutSet; - - public AbstractBatcher(ConnectionManager connectionManager, Interceptor interceptor) { - this.connectionManager = connectionManager; - this.interceptor = interceptor; - this.factory = connectionManager.getFactory(); - } - - public void setTransactionTimeout(int seconds) { - isTransactionTimeoutSet = true; - transactionTimeout = System.currentTimeMillis() / 1000 + seconds; - } - - public void unsetTransactionTimeout() { - isTransactionTimeoutSet = false; - } - - protected PreparedStatement getStatement() { - return batchUpdate; - } - - public CallableStatement prepareCallableStatement(String sql) - throws SQLException, HibernateException { - executeBatch(); - logOpenPreparedStatement(); - return getCallableStatement( connectionManager.getConnection(), sql, false); - } - - public PreparedStatement prepareStatement(String sql) - throws SQLException, HibernateException { - return prepareStatement( sql, false ); - } - - public PreparedStatement prepareStatement(String sql, boolean getGeneratedKeys) - throws SQLException, HibernateException { - executeBatch(); - logOpenPreparedStatement(); - return getPreparedStatement( - connectionManager.getConnection(), - sql, - false, - getGeneratedKeys, - null, - null, - false - ); - } - - public PreparedStatement prepareStatement(String sql, String[] columnNames) - throws SQLException, HibernateException { - executeBatch(); - logOpenPreparedStatement(); - return getPreparedStatement( - connectionManager.getConnection(), - sql, - false, - false, - columnNames, - null, - false - ); - } - - public PreparedStatement prepareSelectStatement(String sql) - throws SQLException, HibernateException { - logOpenPreparedStatement(); - return getPreparedStatement( - connectionManager.getConnection(), - sql, - false, - false, - null, - null, - false - ); - } - - public PreparedStatement prepareQueryStatement( - String sql, - boolean scrollable, - ScrollMode scrollMode) throws SQLException, HibernateException { - logOpenPreparedStatement(); - PreparedStatement ps = getPreparedStatement( - connectionManager.getConnection(), - sql, - scrollable, - scrollMode - ); - setStatementFetchSize( ps ); - statementsToClose.add( ps ); - lastQuery = ps; - return ps; - } - - public CallableStatement prepareCallableQueryStatement( - String sql, - boolean scrollable, - ScrollMode scrollMode) throws SQLException, HibernateException { - logOpenPreparedStatement(); - CallableStatement ps = ( CallableStatement ) getPreparedStatement( - connectionManager.getConnection(), - sql, - scrollable, - false, - null, - scrollMode, - true - ); - setStatementFetchSize( ps ); - statementsToClose.add( ps ); - lastQuery = ps; - return ps; - } - - public void abortBatch(SQLException sqle) { - try { - if (batchUpdate!=null) closeStatement(batchUpdate); - } - catch (SQLException e) { - //noncritical, swallow and let the other propagate! - JDBCExceptionReporter.logExceptions(e); - } - finally { - batchUpdate=null; - batchUpdateSQL=null; - } - } - - public ResultSet getResultSet(PreparedStatement ps) throws SQLException { - ResultSet rs = ps.executeQuery(); - resultSetsToClose.add(rs); - logOpenResults(); - return rs; - } - - public ResultSet getResultSet(CallableStatement ps, Dialect dialect) throws SQLException { - ResultSet rs = dialect.getResultSet(ps); - resultSetsToClose.add(rs); - logOpenResults(); - return rs; - - } - - public void closeQueryStatement(PreparedStatement ps, ResultSet rs) throws SQLException { - boolean psStillThere = statementsToClose.remove( ps ); - try { - if ( rs != null ) { - if ( resultSetsToClose.remove( rs ) ) { - logCloseResults(); - rs.close(); - } - } - } - finally { - if ( psStillThere ) { - closeQueryStatement( ps ); - } - } - } - - public PreparedStatement prepareBatchStatement(String sql) - throws SQLException, HibernateException { - sql = getSQL( sql ); - - if ( !sql.equals(batchUpdateSQL) ) { - batchUpdate=prepareStatement(sql); // calls executeBatch() - batchUpdateSQL=sql; - } - else { - LOG.reusingPreparedStatement(); - log(sql); - } - return batchUpdate; - } - - public CallableStatement prepareBatchCallableStatement(String sql) - throws SQLException, HibernateException { - if ( !sql.equals(batchUpdateSQL) ) { // TODO: what if batchUpdate is a callablestatement ? - batchUpdate=prepareCallableStatement(sql); // calls executeBatch() - batchUpdateSQL=sql; - } - return (CallableStatement)batchUpdate; - } - - - public void executeBatch() throws HibernateException { - if (batchUpdate!=null) { - try { - try { - doExecuteBatch(batchUpdate); - } - finally { - closeStatement(batchUpdate); - } - } - catch (SQLException sqle) { - throw JDBCExceptionHelper.convert( - factory.getSQLExceptionConverter(), - sqle, - "Could not execute JDBC batch update", - batchUpdateSQL - ); - } - finally { - batchUpdate=null; - batchUpdateSQL=null; - } - } - } - - public void closeStatement(PreparedStatement ps) throws SQLException { - logClosePreparedStatement(); - closePreparedStatement(ps); - } - - private void closeQueryStatement(PreparedStatement ps) throws SQLException { - - try { - //work around a bug in all known connection pools.... - if ( ps.getMaxRows()!=0 ) ps.setMaxRows(0); - if ( ps.getQueryTimeout()!=0 ) ps.setQueryTimeout(0); - } - catch (Exception e) { - LOG.warn(LOG.unableToClearMaxRowsAndQueryTimeout(), e); -// ps.close(); //just close it; do NOT try to return it to the pool! - return; //NOTE: early exit! - } - finally { - closeStatement(ps); - } - - if ( lastQuery==ps ) lastQuery = null; - - } - - /** - * Actually releases the batcher, allowing it to cleanup internally held - * resources. - */ - public void closeStatements() { - try { - releasing = true; - - try { - if ( batchUpdate != null ) { - batchUpdate.close(); - } - } - catch ( SQLException sqle ) { - //no big deal - LOG.warn(LOG.unableToCloseJdbcPreparedStatement(), sqle); - } - batchUpdate = null; - batchUpdateSQL = null; - - Iterator iter = resultSetsToClose.iterator(); - while ( iter.hasNext() ) { - try { - logCloseResults(); - ( ( ResultSet ) iter.next() ).close(); - } - catch ( SQLException e ) { - // no big deal - LOG.warn(LOG.unableToCloseJdbcResultSet(), e); - } - catch ( ConcurrentModificationException e ) { - // this has been shown to happen occasionally in rare cases - // when using a transaction manager + transaction-timeout - // where the timeout calls back through Hibernate's - // registered transaction synchronization on a separate - // "reaping" thread. In cases where that reaping thread - // executes through this block at the same time the main - // application thread does we can get into situations where - // these CMEs occur. And though it is not "allowed" per-se, - // the end result without handling it specifically is infinite - // looping. So here, we simply break the loop - LOG.unableToReleaseBatcher(); - break; - } - catch ( Throwable e ) { - // sybase driver (jConnect) throwing NPE here in certain - // cases, but we'll just handle the general "unexpected" case - LOG.warn(LOG.unableToCloseJdbcResultSet(), e); - } - } - resultSetsToClose.clear(); - - iter = statementsToClose.iterator(); - while ( iter.hasNext() ) { - try { - closeQueryStatement( ( PreparedStatement ) iter.next() ); - } - catch ( ConcurrentModificationException e ) { - // see explanation above... - LOG.unableToReleaseBatcher(); - break; - } - catch ( SQLException e ) { - // no big deal - LOG.warn(LOG.unableToCloseJdbcStatement(), e); - } - } - statementsToClose.clear(); - } - finally { - releasing = false; - } - } - - protected abstract void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException; - - private String preparedStatementCountsToString() { - return - " (open PreparedStatements: " + - openPreparedStatementCount + - ", globally: " + - globalOpenPreparedStatementCount + - ")"; - } - - private String resultSetCountsToString() { - return - " (open ResultSets: " + - openResultSetCount + - ", globally: " + - globalOpenResultSetCount + - ")"; - } - - private void logOpenPreparedStatement() { - if (LOG.isDebugEnabled()) { - LOG.aboutToOpenPreparedStatement(preparedStatementCountsToString()); - openPreparedStatementCount++; - globalOpenPreparedStatementCount++; - } - } - - private void logClosePreparedStatement() { - if (LOG.isDebugEnabled()) { - LOG.aboutToClosePreparedStatement(preparedStatementCountsToString()); - openPreparedStatementCount--; - globalOpenPreparedStatementCount--; - } - } - - private void logOpenResults() { - if (LOG.isDebugEnabled()) { - LOG.aboutToOpenResultSet(resultSetCountsToString()); - openResultSetCount++; - globalOpenResultSetCount++; - } - } - - private void logCloseResults() { - if (LOG.isDebugEnabled()) { - LOG.aboutToCloseResultSet(resultSetCountsToString()); - openResultSetCount--; - globalOpenResultSetCount--; - } - } - - protected SessionFactoryImplementor getFactory() { - return factory; - } - - private void log(String sql) { - factory.getSettings().getSqlStatementLogger().logStatement( sql, FormatStyle.BASIC ); - } - - private PreparedStatement getPreparedStatement( - final Connection conn, - final String sql, - final boolean scrollable, - final ScrollMode scrollMode) throws SQLException { - return getPreparedStatement( - conn, - sql, - scrollable, - false, - null, - scrollMode, - false - ); - } - - private CallableStatement getCallableStatement( - final Connection conn, - String sql, - boolean scrollable) throws SQLException { - if (scrollable && !factory.getSettings().isScrollableResultSetsEnabled()) throw new AssertionFailure( - "scrollable result sets are not enabled"); - - sql = getSQL( sql ); - log( sql ); - - LOG.preparingCallableStatement(); - if (scrollable) return conn.prepareCall(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - return conn.prepareCall(sql); - } - - private String getSQL(String sql) { - sql = interceptor.onPrepareStatement( sql ); - if ( sql==null || sql.length() == 0 ) { - throw new AssertionFailure( "Interceptor.onPrepareStatement() returned null or empty string." ); - } - return sql; - } - - private PreparedStatement getPreparedStatement( - final Connection conn, - String sql, - boolean scrollable, - final boolean useGetGeneratedKeys, - final String[] namedGeneratedKeys, - final ScrollMode scrollMode, - final boolean callable) throws SQLException { - if ( scrollable && !factory.getSettings().isScrollableResultSetsEnabled() ) { - throw new AssertionFailure("scrollable result sets are not enabled"); - } - if ( useGetGeneratedKeys && !factory.getSettings().isGetGeneratedKeysEnabled() ) { - throw new AssertionFailure("getGeneratedKeys() support is not enabled"); - } - - sql = getSQL( sql ); - log( sql ); - - LOG.preparingStatement(); - PreparedStatement result; - if ( scrollable ) { - if ( callable ) { - result = conn.prepareCall( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY ); - } - else { - result = conn.prepareStatement( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY ); - } - } - else if ( useGetGeneratedKeys ) { - result = conn.prepareStatement( sql, Statement.RETURN_GENERATED_KEYS ); - } - else if ( namedGeneratedKeys != null ) { - result = conn.prepareStatement( sql, namedGeneratedKeys ); - } - else { - if ( callable ) { - result = conn.prepareCall( sql ); - } - else { - result = conn.prepareStatement( sql ); - } - } - - setTimeout( result ); - - if ( factory.getStatistics().isStatisticsEnabled() ) { - factory.getStatisticsImplementor().prepareStatement(); - } - - return result; - - } - - private void setTimeout(PreparedStatement result) throws SQLException { - if ( isTransactionTimeoutSet ) { - int timeout = (int) ( transactionTimeout - ( System.currentTimeMillis() / 1000 ) ); - if (timeout <= 0) throw new TransactionException("transaction timeout expired"); - result.setQueryTimeout(timeout); - } - } - - private void closePreparedStatement(PreparedStatement ps) throws SQLException { - try { - LOG.closingStatement(); - ps.close(); - if ( factory.getStatistics().isStatisticsEnabled() ) { - factory.getStatisticsImplementor().closeStatement(); - } - } - finally { - if ( !releasing ) { - // If we are in the process of releasing, no sense - // checking for aggressive-release possibility. - connectionManager.afterStatement(); - } - } - } - - private void setStatementFetchSize(PreparedStatement statement) throws SQLException { - Integer statementFetchSize = factory.getSettings().getJdbcFetchSize(); - if ( statementFetchSize!=null ) { - statement.setFetchSize( statementFetchSize.intValue() ); - } - } - - public Connection openConnection() throws HibernateException { - LOG.openingJdbcConnection(); - try { - return factory.getConnectionProvider().getConnection(); - } - catch (SQLException sqle) { - throw JDBCExceptionHelper.convert( - factory.getSQLExceptionConverter(), - sqle, - "Cannot open connection" - ); - } - } - - public void closeConnection(Connection conn) throws HibernateException { - if ( conn == null ) { - LOG.foundNullConnection(); - // EARLY EXIT!!!! - return; - } - - if (LOG.isDebugEnabled()) LOG.closingJdbcConnection(preparedStatementCountsToString() + resultSetCountsToString()); - - try { - if ( !conn.isClosed() ) { - JDBCExceptionReporter.logAndClearWarnings( conn ); - } - factory.getConnectionProvider().closeConnection( conn ); - } - catch ( SQLException sqle ) { - throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot close connection" ); - } - } - - public void cancelLastQuery() throws HibernateException { - try { - if (lastQuery!=null) lastQuery.cancel(); - } - catch (SQLException sqle) { - throw JDBCExceptionHelper.convert( - factory.getSQLExceptionConverter(), - sqle, - "Cannot cancel query" - ); - } - } - - public boolean hasOpenResources() { - return resultSetsToClose.size() > 0 || statementsToClose.size() > 0; - } - - public String openResourceStatsAsString() { - return preparedStatementCountsToString() + resultSetCountsToString(); - } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "About to close PreparedStatement%s" ) - void aboutToClosePreparedStatement( String preparedStatementCountsToString ); - - @LogMessage( level = DEBUG ) - @Message( value = "About to close ResultSet%s" ) - void aboutToCloseResultSet( String preparedStatementCountsToString ); - - @LogMessage( level = DEBUG ) - @Message( value = "About to open PreparedStatement%s" ) - void aboutToOpenPreparedStatement( String preparedStatementCountsToString ); - - @LogMessage( level = DEBUG ) - @Message( value = "About to open ResultSet%s" ) - void aboutToOpenResultSet( String preparedStatementCountsToString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Closing JDBC connection%s" ) - void closingJdbcConnection( String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Closing statement" ) - void closingStatement(); - - @LogMessage( level = DEBUG ) - @Message( value = "Executing batch size: %d" ) - void executingBatchSize( int batchSize ); - - @LogMessage( level = DEBUG ) - @Message( value = "Found null connection on AbstractBatcher#closeConnection" ) - void foundNullConnection(); - - @LogMessage( level = WARN ) - @Message( value = "JDBC driver did not return the expected number of row counts" ) - void jdbcDriverDidNotReturnExpectedNumberOfRowCounts(); - - @LogMessage( level = DEBUG ) - @Message( value = "No batched statements to execute" ) - void noBatchedStatementsToExecute(); - - @LogMessage( level = DEBUG ) - @Message( value = "Opening JDBC connection" ) - void openingJdbcConnection(); - - @LogMessage( level = TRACE ) - @Message( value = "Preparing callable statement" ) - void preparingCallableStatement(); - - @LogMessage( level = TRACE ) - @Message( value = "Preparing statement" ) - void preparingStatement(); - - @LogMessage( level = DEBUG ) - @Message( value = "Reusing prepared statement" ) - void reusingPreparedStatement(); - - @Message( value = "Exception clearing maxRows/queryTimeout" ) - Object unableToClearMaxRowsAndQueryTimeout(); - - @Message( value = "Could not close a JDBC prepared statement" ) - Object unableToCloseJdbcPreparedStatement(); - - @Message( value = "Could not close a JDBC result set" ) - Object unableToCloseJdbcResultSet(); - - @Message( value = "Could not close a JDBC statement" ) - Object unableToCloseJdbcStatement(); - - @Message( value = "Exception executing batch: " ) - Object unableToExecuteBatch(); - - @LogMessage( level = INFO ) - @Message( value = "Encountered CME attempting to release batcher; assuming cause is tx-timeout scenario and ignoring" ) - void unableToReleaseBatcher(); - } -} \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/jdbc/BatchingBatcher.java b/hibernate-core/src/main/java/org/hibernate/jdbc/BatchingBatcher.java deleted file mode 100644 index 91edc08952..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/jdbc/BatchingBatcher.java +++ /dev/null @@ -1,87 +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.jdbc; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import org.hibernate.HibernateException; -import org.hibernate.Interceptor; - -/** - * An implementation of the Batcher interface that - * actually uses batching - * @author Gavin King - */ -public class BatchingBatcher extends AbstractBatcher { - - private int batchSize; - private Expectation[] expectations; - - public BatchingBatcher(ConnectionManager connectionManager, Interceptor interceptor) { - super( connectionManager, interceptor ); - expectations = new Expectation[ getFactory().getSettings().getJdbcBatchSize() ]; - } - - public void addToBatch(Expectation expectation) throws SQLException, HibernateException { - if (!expectation.canBeBatched()) throw new HibernateException("attempting to batch an operation which cannot be batched"); - PreparedStatement batchUpdate = getStatement(); - batchUpdate.addBatch(); - expectations[ batchSize++ ] = expectation; - if (batchSize == getFactory().getSettings().getJdbcBatchSize()) doExecuteBatch(batchUpdate); - } - - @Override - protected void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException { - if (batchSize == 0) LOG.noBatchedStatementsToExecute(); - else { - LOG.executingBatchSize(batchSize); - - try { - checkRowCounts( ps.executeBatch(), ps ); - } - catch (RuntimeException re) { - LOG.error(LOG.unableToExecuteBatch(), re); - throw re; - } - finally { - batchSize = 0; - } - } - } - - private void checkRowCounts(int[] rowCounts, PreparedStatement ps) throws SQLException, HibernateException { - int numberOfRowCounts = rowCounts.length; - if (numberOfRowCounts != batchSize) LOG.jdbcDriverDidNotReturnExpectedNumberOfRowCounts(); - for (int i = 0; i < numberOfRowCounts; i++) { - expectations[i].verifyOutcome(rowCounts[i], ps, i); - } - } -} - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java b/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java index 7029285cbe..fc3b6a3979 100644 --- a/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java @@ -24,20 +24,16 @@ */ package org.hibernate.jdbc; -import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.StaleStateException; import org.hibernate.engine.ExecuteUpdateResultCheckStyle; import org.hibernate.exception.GenericJDBCException; import org.hibernate.util.JDBCExceptionReporter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Holds various often used {@link Expectation} definitions. @@ -76,7 +72,7 @@ public class Expectations { } private void checkBatched(int rowCount, int batchPosition) { - if (rowCount == -2) LOG.successOfBatchUpdateUnknown(batchPosition); + if (rowCount == -2) LOG.debug("Success of batch update unknown: " + batchPosition); else if (rowCount == -3) throw new BatchFailedException("Batch update failed: " + batchPosition); else { if (expectedRowCount > rowCount) throw new StaleStateException( @@ -193,15 +189,4 @@ public class Expectations { private Expectations() { } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Success of batch update unknown: %s" ) - void successOfBatchUpdateUnknown( int batchPosition ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/jdbc/util/SQLStatementLogger.java b/hibernate-core/src/main/java/org/hibernate/jdbc/util/SQLStatementLogger.java index 506abc33a7..7641755bac 100644 --- a/hibernate-core/src/main/java/org/hibernate/jdbc/util/SQLStatementLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/util/SQLStatementLogger.java @@ -24,8 +24,7 @@ */ package org.hibernate.jdbc.util; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * Centralize logging handling for SQL statements. @@ -117,11 +116,4 @@ public class SQLStatementLogger { private FormatStyle determineActualStyle(FormatStyle style) { return formatSql ? style : FormatStyle.NONE; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - } } 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 5026fbfc3c..cb5022318b 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java @@ -1,7 +1,6 @@ //$Id: HibernateService.java 6100 2005-03-17 10:48:03Z turin42 $ package org.hibernate.jmx; -import static org.jboss.logging.Logger.Level.INFO; import java.util.Map; import java.util.Properties; import javax.naming.InitialContext; @@ -12,10 +11,6 @@ import org.hibernate.cfg.internal.ServicesRegistryBootstrap; import org.hibernate.internal.util.jndi.JndiHelper; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.util.ExternalSessionFactoryConfig; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -42,7 +37,7 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi } catch (HibernateException he) { LOG.unableToBuildSessionFactoryUsingMBeanClasspath(he.getMessage()); - LOG.debug(LOG.errorWas(), he); + LOG.debug("Error was", he); new SessionFactoryStub(this); } } @@ -169,33 +164,4 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi public Properties getProperties() { return buildProperties(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Error was" ) - Object errorWas(); - - @LogMessage( level = INFO ) - @Message( value = "Service properties: %s" ) - void serviceProperties( Properties properties ); - - @LogMessage( level = INFO ) - @Message( value = "Starting service at JNDI name: %s" ) - void startingServiceAtJndiName( String boundName ); - - @LogMessage( level = INFO ) - @Message( value = "Stopping service" ) - void stoppingService(); - - @LogMessage( level = INFO ) - @Message( value = "Could not build SessionFactory using the MBean classpath - will try again using client classpath: %s" ) - void unableToBuildSessionFactoryUsingMBeanClasspath( String message ); - - @Message( value = "Exception while stopping service" ) - Object unableToStopService(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java b/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java index b1c6c1b85c..87a00754e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java @@ -23,7 +23,6 @@ */ package org.hibernate.jmx; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; @@ -37,6 +36,7 @@ import org.hibernate.AssertionFailure; import org.hibernate.Cache; import org.hibernate.HibernateException; import org.hibernate.Interceptor; +import org.hibernate.Logger; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; import org.hibernate.TypeHelper; @@ -47,10 +47,6 @@ import org.hibernate.impl.SessionFactoryObjectFactory; import org.hibernate.metadata.ClassMetadata; import org.hibernate.metadata.CollectionMetadata; import org.hibernate.stat.Statistics; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A flyweight for SessionFactory. If the MBean itself does not @@ -117,8 +113,8 @@ public class SessionFactoryStub implements SessionFactory { // (alternatively we could do an actual JNDI lookup here....) result = SessionFactoryObjectFactory.getNamedInstance(name); if (result == null) throw new InvalidObjectException("Could not find a stub SessionFactory named: " + name); - LOG.resolvedStubSessionFactoryByName(); - } else LOG.resolvedStubSessionFactoryByUid(); + LOG.debug("Resolved stub SessionFactory by name"); + } else LOG.debug("Resolved stub SessionFactory by uid"); return result; } @@ -228,19 +224,4 @@ public class SessionFactoryStub implements SessionFactory { public TypeHelper getTypeHelper() { return getImpl().getTypeHelper(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Resolved stub SessionFactory by name" ) - void resolvedStubSessionFactoryByName(); - - @LogMessage( level = DEBUG ) - @Message( value = "Resolved stub SessionFactory by uid" ) - void resolvedStubSessionFactoryByUid(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java b/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java index f100273916..31544a8617 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java @@ -5,6 +5,7 @@ import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.naming.Reference; +import org.hibernate.Logger; import org.hibernate.SessionFactory; import org.hibernate.impl.SessionFactoryObjectFactory; import org.hibernate.stat.CollectionStatistics; @@ -13,9 +14,6 @@ import org.hibernate.stat.QueryStatistics; import org.hibernate.stat.SecondLevelCacheStatistics; import org.hibernate.stat.Statistics; import org.hibernate.stat.StatisticsImpl; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * JMX service for Hibernate statistics
@@ -315,20 +313,4 @@ public class StatisticsService implements StatisticsServiceMBean { public String getQueryExecutionMaxTimeQueryString() { return stats.getQueryExecutionMaxTimeQueryString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "JNDI name %s does not handle a session factory reference" ) - Object jndiNameDoesNotHandleSessionFactoryReference( String sfJNDIName ); - - @Message( value = "No session factory with JNDI name %s" ) - Object noSessionFactoryWithJndiName( String sfJNDIName ); - - @Message( value = "Error while accessing session factory with JNDI name %s" ) - Object unableToAccessSessionFactory( String sfJNDIName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java index 32c504eee1..5874187bfe 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java @@ -23,8 +23,6 @@ */ package org.hibernate.loader; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.sql.CallableStatement; import java.sql.PreparedStatement; @@ -42,6 +40,7 @@ import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.QueryException; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; @@ -52,7 +51,6 @@ import org.hibernate.cache.QueryCache; import org.hibernate.cache.QueryKey; import org.hibernate.collection.PersistentCollection; import org.hibernate.dialect.Dialect; -import org.hibernate.engine.CascadingAction; import org.hibernate.engine.EntityKey; import org.hibernate.engine.EntityUniqueKey; import org.hibernate.engine.PersistenceContext; @@ -83,10 +81,6 @@ import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.type.VersionType; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Abstract superclass of object loading (and querying) strategies. This class implements @@ -861,12 +855,12 @@ public abstract class Loader { EntityKey[] keys = new EntityKey[entitySpan]; //we can reuse it for each row - LOG.processingResultSet(); + LOG.trace("Processing result set"); int count; for ( count = 0; count < maxRows && rs.next(); count++ ) { - LOG.resultSetRow(count); + LOG.debug("Result set row: " + count); Object result = getRowFromResultSet( rs, @@ -888,7 +882,7 @@ public abstract class Loader { } - LOG.processingResultSetDone(count); + LOG.trace("Done processing result set (" + count + " rows)"); } finally { @@ -1016,7 +1010,7 @@ public abstract class Loader { if ( hydratedObjects!=null ) { int hydratedObjectsSize = hydratedObjects.size(); - LOG.totalObjectsHydrated(hydratedObjectsSize); + LOG.trace("Total objects hydrated: " + hydratedObjectsSize); for ( int i = 0; i < hydratedObjectsSize; i++ ) { TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre, post ); } @@ -1186,9 +1180,8 @@ public abstract class Loader { if ( collectionRowKey != null ) { // we found a collection element in the result set - if (LOG.isDebugEnabled()) LOG.foundCollectionRow(MessageHelper.collectionInfoString(persister, - collectionRowKey, - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Found row of collection: " + + MessageHelper.collectionInfoString(persister, collectionRowKey, getFactory())); Object owner = optionalOwner; if ( owner == null ) { @@ -1216,9 +1209,8 @@ public abstract class Loader { // ensure that a collection is created with the owner's identifier, // since what we have is an empty collection - if (LOG.isDebugEnabled()) LOG.resultSetContainsCollection(MessageHelper.collectionInfoString(persister, - optionalKey, - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Result set contains (possibly empty) collection: " + + MessageHelper.collectionInfoString(persister, optionalKey, getFactory())); persistenceContext.getLoadContexts() .getCollectionLoadContext( rs ) @@ -1250,9 +1242,10 @@ public abstract class Loader { for ( int i = 0; i < keys.length; i++ ) { //handle empty collections - if (LOG.isDebugEnabled()) LOG.resultSetContainsCollection(MessageHelper.collectionInfoString(collectionPersisters[j], - keys[i], - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Result set contains (possibly empty) collection: " + + MessageHelper.collectionInfoString(collectionPersisters[j], + keys[i], + getFactory())); session.getPersistenceContext() .getLoadContexts() @@ -1366,7 +1359,7 @@ public abstract class Loader { final int cols = persisters.length; final EntityAliases[] descriptors = getEntityAliases(); - if (LOG.isDebugEnabled()) LOG.resultRow(StringHelper.toString(keys)); + if (LOG.isDebugEnabled()) LOG.debug("Result row: " + StringHelper.toString(keys)); final Object[] rowResults = new Object[cols]; @@ -1541,7 +1534,8 @@ public abstract class Loader { // Get the persister for the _subclass_ final Loadable persister = (Loadable) getFactory().getEntityPersister( instanceEntityName ); - if (LOG.isTraceEnabled()) LOG.initializingObjectFromResultSet(MessageHelper.infoString(persister, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Initializing object from ResultSet: " + + MessageHelper.infoString(persister, id, getFactory())); boolean eagerPropertyFetch = isEagerPropertyFetchEnabled(i); @@ -1730,7 +1724,7 @@ public abstract class Loader { PreparedStatement st = null; - st = session.getJDBCContext().getConnectionManager().prepareQueryStatement( + st = session.getJDBCContext().getConnectionManager().prepareQueryStatement( sql, scroll || useScrollableResultSetToSkip, scrollMode, @@ -1771,12 +1765,14 @@ public abstract class Loader { LockOptions lockOptions = queryParameters.getLockOptions(); if ( lockOptions != null ) { if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) { - if (!dialect.supportsLockTimeouts()) LOG.unsupportedLockTimeoutRequested(lockOptions.getTimeOut()); + if (!dialect.supportsLockTimeouts()) LOG.debug("Lock timeout [" + + lockOptions.getTimeOut() + + "] requested but dialect reported to not support lock timeouts"); else if (dialect.isLockTimeoutParameterized()) st.setInt(col++, lockOptions.getTimeOut()); } } - LOG.boundParametersTotal(col); + LOG.trace("Bound [" + col + "] parameters total"); } catch ( SQLException sqle ) { st.close(); @@ -1937,7 +1933,7 @@ public abstract class Loader { TypedValue typedval = ( TypedValue ) e.getValue(); int[] locs = getNamedParameterLocs( name ); for ( int i = 0; i < locs.length; i++ ) { - LOG.bindNamedParameters(typedval.getValue(), name, locs[i] + startIndex); + LOG.debug("bindNamedParameters() " + typedval.getValue() + " -> " + name + " [" + (locs[i] + startIndex) + "]"); typedval.getType().nullSafeSet( statement, typedval.getValue(), locs[i] + startIndex, session ); } result += locs.length; @@ -1996,7 +1992,7 @@ public abstract class Loader { // potential deadlock issues due to nature of code. if ( session.getFactory().getSettings().isWrapResultSetsEnabled() ) { try { - LOG.wrappingResultSet(rs); + LOG.debug("Wrapping result set [" + rs + "]"); return session.getFactory() .getSettings() .getJdbcSupport().wrap( rs, retreiveColumnNameToIndexCache( rs ) ); @@ -2013,7 +2009,7 @@ public abstract class Loader { private ColumnNameCache retreiveColumnNameToIndexCache(ResultSet rs) throws SQLException { if ( columnNameCache == null ) { - LOG.buildingColumnIndexByNameCache(); + LOG.trace("Building columnName->columnIndex cache"); columnNameCache = new ColumnNameCache( rs.getMetaData().getColumnCount() ); } @@ -2035,7 +2031,8 @@ public abstract class Loader { final EntityPersister persister, LockOptions lockOptions) throws HibernateException { - if (LOG.isDebugEnabled()) LOG.loadingEntity(MessageHelper.infoString(persister, id, identifierType, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Loading entity: " + + MessageHelper.infoString(persister, id, identifierType, getFactory())); List result; try { @@ -2058,7 +2055,7 @@ public abstract class Loader { ); } - LOG.loadingEntityDone(); + LOG.debug("Done entity load"); return result; @@ -2076,7 +2073,7 @@ public abstract class Loader { final Type indexType, final EntityPersister persister) throws HibernateException { - LOG.loadingCollectionElementByIndex(); + LOG.debug("Loading collection element by index"); List result; try { @@ -2097,7 +2094,7 @@ public abstract class Loader { ); } - LOG.loadingEntityDone(); + LOG.debug("Done entity load"); return result; @@ -2118,7 +2115,7 @@ public abstract class Loader { final EntityPersister persister, LockOptions lockOptions) throws HibernateException { - if (LOG.isDebugEnabled()) LOG.batchLoadingEntity(MessageHelper.infoString(persister, ids, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Batch loading entity: " + MessageHelper.infoString(persister, ids, getFactory())); Type[] types = new Type[ids.length]; Arrays.fill( types, idType ); @@ -2142,7 +2139,7 @@ public abstract class Loader { ); } - LOG.batchLoadingEntityDone(); + LOG.debug("Done entity batch load"); return result; @@ -2156,9 +2153,8 @@ public abstract class Loader { final Serializable id, final Type type) throws HibernateException { - if (LOG.isDebugEnabled()) LOG.loadingCollection(MessageHelper.collectionInfoString(getCollectionPersisters()[0], - id, - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Loading collection: " + + MessageHelper.collectionInfoString(getCollectionPersisters()[0], id, getFactory())); Serializable[] ids = new Serializable[]{id}; try { @@ -2177,7 +2173,7 @@ public abstract class Loader { ); } - LOG.loadingCollectionDone(); + LOG.debug("Done loading collection"); } @@ -2189,9 +2185,8 @@ public abstract class Loader { final Serializable[] ids, final Type type) throws HibernateException { - if (LOG.isDebugEnabled()) LOG.batchLoadingCollection(MessageHelper.collectionInfoString(getCollectionPersisters()[0], - ids, - getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Batch loading collection: " + + MessageHelper.collectionInfoString(getCollectionPersisters()[0], ids, getFactory())); Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); @@ -2211,7 +2206,7 @@ public abstract class Loader { ); } - LOG.batchLoadingCollectionDone(); + LOG.debug("Done batch load"); } @@ -2279,8 +2274,9 @@ public abstract class Loader { QueryKey key = generateQueryKey( session, queryParameters ); - if (querySpaces == null || querySpaces.size() == 0) LOG.unexpectedQuerySpaces(querySpaces == null ? querySpaces : LOG.empty()); - else LOG.querySpaces(querySpaces.toString()); + if (querySpaces == null || querySpaces.size() == 0) LOG.trace("Unexpected querySpaces is " + + (querySpaces == null ? querySpaces : "empty")); + else LOG.trace("querySpaces is " + querySpaces.toString()); List result = getResultFromQueryCache( session, @@ -2586,134 +2582,4 @@ public abstract class Loader { public String toString() { return getClass().getName() + '(' + getSQLString() + ')'; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - protected interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Batch loading collection: %s" ) - void batchLoadingCollection( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done batch load" ) - void batchLoadingCollectionDone(); - - @LogMessage( level = DEBUG ) - @Message( value = "Batch loading entity: %s" ) - void batchLoadingEntity( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done entity batch load" ) - void batchLoadingEntityDone(); - - @LogMessage( level = DEBUG ) - @Message( value = "bindNamedParameters() %s -> %s [%d]" ) - void bindNamedParameters( Object value, - String name, - int index ); - - @LogMessage( level = TRACE ) - @Message( value = "Bound [%d] parameters total" ) - void boundParametersTotal( int col ); - - @LogMessage( level = TRACE ) - @Message( value = "Building columnName->columnIndex cache" ) - void buildingColumnIndexByNameCache(); - - @Message( value = "empty" ) - Object empty(); - - @LogMessage( level = DEBUG ) - @Message( value = "Found row of collection: %s" ) - void foundCollectionRow( String collectionInfoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Initializing object from ResultSet: %s" ) - void initializingObjectFromResultSet( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Loading collection: %s" ) - void loadingCollection( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done loading collection" ) - void loadingCollectionDone(); - - @LogMessage( level = DEBUG ) - @Message( value = "Loading collection element by index" ) - void loadingCollectionElementByIndex(); - - @LogMessage( level = DEBUG ) - @Message( value = "Loading entity: %s" ) - void loadingEntity( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done entity load" ) - void loadingEntityDone(); - - @LogMessage( level = TRACE ) - @Message( value = "Processing result set" ) - void processingResultSet(); - - @LogMessage( level = TRACE ) - @Message( value = "Done processing result set (%d rows)" ) - void processingResultSetDone( int count ); - - @LogMessage( level = TRACE ) - @Message( value = "querySpaces is %s" ) - void querySpaces( String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Result row: %s" ) - void resultRow( String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Result set contains (possibly empty) collection: %s" ) - void resultSetContainsCollection( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Result set row: %d" ) - void resultSetRow( int count ); - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for action %s on entity %s: %s" ) - void staticSelectForAction( CascadingAction action, - String entityName, - String sqlString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for entity %s [%s]: %s" ) - void staticSelectForEntity( String entityName, - LockMode lockMode, - String sqlString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for entity %s [%s:%d]: %s" ) - void staticSelectForEntity( String entityName, - LockMode lockMode, - int timeOut, - String sqlString ); - - @LogMessage( level = TRACE ) - @Message( value = "Total objects hydrated: %d" ) - void totalObjectsHydrated( int hydratedObjectsSize ); - - @Message( value = "Error wrapping result set" ) - Object unableToWrapResultSet(); - - @LogMessage( level = TRACE ) - @Message( value = "Unexpected querySpaces is %s" ) - void unexpectedQuerySpaces( Object string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Lock timeout [%d] requested but dialect reported to not support lock timeouts" ) - void unsupportedLockTimeoutRequested( int timeOut ); - - @LogMessage( level = DEBUG ) - @Message( value = "Wrapping result set [%s]" ) - void wrappingResultSet( ResultSet rs ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/collection/BasicCollectionLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/collection/BasicCollectionLoader.java index d65744a7d4..f04dfe442e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/collection/BasicCollectionLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/collection/BasicCollectionLoader.java @@ -24,16 +24,12 @@ */ package org.hibernate.loader.collection; -import static org.jboss.logging.Logger.Level.DEBUG; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.loader.JoinWalker; import org.hibernate.persister.collection.QueryableCollection; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Loads a collection of values or a many-to-many association. @@ -83,18 +79,6 @@ public class BasicCollectionLoader extends CollectionLoader { postInstantiate(); - LOG.staticSelectForCollection(collectionPersister.getRole(), getSQLString()); + LOG.debug("Static select for collection " + collectionPersister.getRole() + ": " + getSQLString()); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for collection %s: %s" ) - void staticSelectForCollection( String role, - String sqlString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/collection/OneToManyLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/collection/OneToManyLoader.java index 6640d94859..7849a657d7 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/collection/OneToManyLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/collection/OneToManyLoader.java @@ -24,16 +24,12 @@ */ package org.hibernate.loader.collection; -import static org.jboss.logging.Logger.Level.DEBUG; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.loader.JoinWalker; import org.hibernate.persister.collection.QueryableCollection; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Loads one-to-many associations
@@ -82,18 +78,6 @@ public class OneToManyLoader extends CollectionLoader { initFromWalker( walker ); postInstantiate(); - LOG.staticSelectForOneToMany(oneToManyPersister.getRole(), getSQLString()); + LOG.debug("Static select for one-to-many " + oneToManyPersister.getRole() + ": " + getSQLString()); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for one-to-many %s: %s" ) - void staticSelectForOneToMany( String role, - String sqlString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java index 0ca4ce2440..eebc6cbc2e 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java @@ -24,7 +24,6 @@ */ package org.hibernate.loader.custom.sql; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -33,15 +32,12 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.query.sql.NativeSQLQueryReturn; import org.hibernate.loader.custom.CustomQuery; import org.hibernate.persister.collection.SQLLoadableCollection; import org.hibernate.persister.entity.SQLLoadable; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Implements Hibernate's built-in support for native SQL queries. @@ -85,7 +81,7 @@ public class SQLCustomQuery implements CustomQuery { final Collection additionalQuerySpaces, final SessionFactoryImplementor factory) throws HibernateException { - LOG.processingSqlQery(sqlQuery); + LOG.trace("Starting processing of sql query [" + sqlQuery + "]"); SQLQueryReturnProcessor processor = new SQLQueryReturnProcessor(queryReturns, factory); SQLQueryReturnProcessor.ResultAliasContext aliasContext = processor.process(); @@ -255,15 +251,4 @@ public class SQLCustomQuery implements CustomQuery { return aliasContext.getPropertyResultsMap( alias ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Starting processing of sql query [%s]" ) - void processingSqlQery( String sqlQuery ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java index fe0bc3dfd9..6485b5206a 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java @@ -24,13 +24,13 @@ */ package org.hibernate.loader.custom.sql; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.query.sql.NativeSQLQueryCollectionReturn; @@ -59,10 +59,6 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.SQLLoadable; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Responsible for processing the series of {@link org.hibernate.engine.query.sql.NativeSQLQueryReturn returns} @@ -387,7 +383,7 @@ public class SQLQueryReturnProcessor { private void addPersister(String alias, Map propertyResult, SQLLoadable persister) { alias2Persister.put( alias, persister ); String suffix = generateEntitySuffix(); - LOG.mappingAliasToEntitySuffix(alias, suffix); + LOG.trace("Mapping alias [" + alias + "] to entity-suffix [" + suffix + "]"); alias2Suffix.put( alias, suffix ); entityPropertyResultMaps.put( alias, propertyResult ); } @@ -396,7 +392,7 @@ public class SQLQueryReturnProcessor { SQLLoadableCollection collectionPersister = ( SQLLoadableCollection ) factory.getCollectionPersister( role ); alias2CollectionPersister.put( alias, collectionPersister ); String suffix = generateCollectionSuffix(); - LOG.mappingAliasToCollectionSuffix(alias, suffix); + LOG.trace("Mapping alias [" + alias + "] to collection-suffix [" + suffix + "]"); alias2CollectionSuffix.put( alias, suffix ); collectionPropertyResultMaps.put( alias, propertyResults ); @@ -524,21 +520,4 @@ public class SQLQueryReturnProcessor { // public Map getAlias2Return() { // return alias2Return; // } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Mapping alias [%s] to collection-suffix [%s]" ) - void mappingAliasToCollectionSuffix( String alias, - String suffix ); - - @LogMessage( level = TRACE ) - @Message( value = "Mapping alias [%s] to entity-suffix [%s]" ) - void mappingAliasToEntitySuffix( String alias, - String suffix ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/entity/CascadeEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/entity/CascadeEntityLoader.java index 9f4d54e526..7fe5a778ec 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/entity/CascadeEntityLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/entity/CascadeEntityLoader.java @@ -53,7 +53,7 @@ public class CascadeEntityLoader extends AbstractEntityLoader { postInstantiate(); - LOG.staticSelectForAction(action, entityName, getSQLString()); + LOG.debug("Static select for action " + action + " on entity " + entityName + ": " + getSQLString()); } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/entity/CollectionElementLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/entity/CollectionElementLoader.java index 991c33d93e..513ab1f1b9 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/entity/CollectionElementLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/entity/CollectionElementLoader.java @@ -24,12 +24,12 @@ */ package org.hibernate.loader.entity; -import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.SessionFactoryImplementor; @@ -41,10 +41,6 @@ import org.hibernate.persister.entity.OuterJoinLoadable; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * @@ -87,7 +83,7 @@ public class CollectionElementLoader extends OuterJoinLoader { postInstantiate(); - LOG.staticSelectForEntity(entityName, getSQLString()); + LOG.debug("Static select for entity " + entityName + ": " + getSQLString()); } @@ -133,16 +129,4 @@ public class CollectionElementLoader extends OuterJoinLoader { protected boolean isSingleRowLoader() { return true; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Static select for entity %s: %s" ) - void staticSelectForEntity( String entityName, - String sqlString ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/loader/entity/EntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/entity/EntityLoader.java index b8d7409ac5..41cc752b36 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/entity/EntityLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/entity/EntityLoader.java @@ -120,7 +120,7 @@ public class EntityLoader extends AbstractEntityLoader { batchLoader = batchSize > 1; - LOG.staticSelectForEntity(entityName, lockMode, getSQLString()); + LOG.debug("Static select for entity " + entityName + " [" + lockMode + "]: " + getSQLString()); } public EntityLoader( @@ -147,7 +147,8 @@ public class EntityLoader extends AbstractEntityLoader { batchLoader = batchSize > 1; - LOG.staticSelectForEntity(entityName, lockOptions.getLockMode(), lockOptions.getTimeOut(), getSQLString()); + LOG.debug("Static select for entity " + entityName + " [" + lockOptions.getLockMode() + ":" + lockOptions.getTimeOut() + + "]: " + getSQLString()); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/AbstractSimpleValue.java b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/AbstractSimpleValue.java index f3405edfb0..77ef5d1cac 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/AbstractSimpleValue.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/AbstractSimpleValue.java @@ -23,8 +23,7 @@ */ package org.hibernate.metamodel.relational; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.Logger; /** * Basic support for {@link SimpleValue} implementations. @@ -32,7 +31,8 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public abstract class AbstractSimpleValue implements SimpleValue { - private static final Logger log = LoggerFactory.getLogger( AbstractSimpleValue.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private final ValueContainer container; private Datatype datatype; @@ -59,10 +59,8 @@ public abstract class AbstractSimpleValue implements SimpleValue { * {@inheritDoc} */ public void setDatatype(Datatype datatype) { - log.debug( "setting datatype for column {} : {}", toLoggableString(), datatype ); - if ( this.datatype != null && ! this.datatype.equals( datatype ) ) { - log.debug( "overriding previous datatype : {}", this.datatype ); - } + LOG.debug("Setting datatype for column " + toLoggableString() + " : " + datatype); + if (this.datatype != null && !this.datatype.equals(datatype)) LOG.debug("Overriding previous datatype : " + this.datatype); this.datatype = datatype; } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/ForeignKey.java b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/ForeignKey.java index a7a05b349f..d7785c4169 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/ForeignKey.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/ForeignKey.java @@ -25,9 +25,7 @@ package org.hibernate.metamodel.relational; import java.util.ArrayList; import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.Logger; /** * Models the notion of a foreign key. @@ -39,7 +37,8 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class ForeignKey extends AbstractConstraint implements Constraint, Exportable { - private static final Logger log = LoggerFactory.getLogger( ForeignKey.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private final TableSpecification targetTable; private List targetColumns; @@ -78,25 +77,13 @@ public class ForeignKey extends AbstractConstraint implements Constraint, Export public void addColumnMapping(Column sourceColumn, Column targetColumn) { if ( targetColumn == null ) { - if ( targetColumns != null ) { - if ( log.isWarnEnabled() ) { - log.warn( - "Attempt to map column [" + sourceColumn.toLoggableString() - + "] to no target column after explicit target column(s) named for FK [name=" - + getName() + "]" - ); - } - } + if (targetColumns != null) LOG.attemptToMapColumnToNoTargetColumn(sourceColumn.toLoggableString(), getName()); } else { if ( targetColumns == null ) { - if ( !internalColumnAccess().isEmpty() ) { - log.warn( - "Value mapping mismatch as part of FK [table=" + getTable().toLoggableString() - + ", name=" + getName() + "] while adding source column [" - + sourceColumn.toLoggableString() + "]" - ); - } + if (!internalColumnAccess().isEmpty()) LOG.valueMappingMismatch(getTable().toLoggableString(), + getName(), + sourceColumn.toLoggableString()); targetColumns = new ArrayList(); } targetColumns.add( targetColumn ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java index 5c6a0a8f0e..6261ae11db 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java @@ -23,7 +23,6 @@ */ package org.hibernate.persister.collection; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -35,6 +34,7 @@ import java.util.Map; import org.hibernate.AssertionFailure; import org.hibernate.FetchMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.TransientObjectException; @@ -84,10 +84,6 @@ import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.FilterHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -610,11 +606,11 @@ public abstract class AbstractCollectionPersister protected void logStaticSQL() { if (LOG.isDebugEnabled()) { - LOG.staticSqlForCollection(getRole()); - if (getSQLInsertRowString() != null) LOG.rowInsert(getSQLInsertRowString()); - if (getSQLUpdateRowString() != null) LOG.rowUpdate(getSQLUpdateRowString()); - if (getSQLDeleteRowString() != null) LOG.rowDelete(getSQLDeleteRowString()); - if (getSQLDeleteString() != null) LOG.oneShotDelete(getSQLDeleteString()); + LOG.debug("Static SQL for collection: " + getRole()); + if (getSQLInsertRowString() != null) LOG.debug(" Row insert: " + getSQLInsertRowString()); + if (getSQLUpdateRowString() != null) LOG.debug(" Row update: " + getSQLUpdateRowString()); + if (getSQLDeleteRowString() != null) LOG.debug(" Row delete: " + getSQLDeleteRowString()); + if (getSQLDeleteString() != null) LOG.debug(" One-shot delete: " + getSQLDeleteString()); } } @@ -1061,7 +1057,8 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowDeleteEnabled() ) { - if (LOG.isDebugEnabled()) LOG.deletingCollection(MessageHelper.collectionInfoString(this, id, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Deleting collection: " + + MessageHelper.collectionInfoString(this, id, getFactory())); // Remove all the old entries @@ -1103,7 +1100,7 @@ public abstract class AbstractCollectionPersister } } - LOG.deletingCollectionDone(); + LOG.debug("Done deleting collection"); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( @@ -1123,7 +1120,8 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowInsertEnabled() ) { - if (LOG.isDebugEnabled()) LOG.insertingCollection(MessageHelper.collectionInfoString(this, id, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Inserting collection: " + + MessageHelper.collectionInfoString(this, id, getFactory())); try { //create all the new entries @@ -1192,9 +1190,9 @@ public abstract class AbstractCollectionPersister i++; } - LOG.insertingCollectionDone(count); + LOG.debug("Done inserting collection: " + count + " rows inserted"); - } else LOG.collectionWasEmpty(); + } else LOG.debug("Collection was empty"); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( @@ -1216,7 +1214,8 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowDeleteEnabled() ) { - if (LOG.isDebugEnabled()) LOG.deletingCollectionRows(MessageHelper.collectionInfoString(this, id, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Deleting rows of collection: " + + MessageHelper.collectionInfoString(this, id, getFactory())); boolean deleteByIndex = !isOneToMany() && hasIndex && !indexContainsFormula; @@ -1280,9 +1279,9 @@ public abstract class AbstractCollectionPersister } } - LOG.deletingCollectionRowsDone(count); + LOG.debug("Done deleting collection rows: " + count + " deleted"); } - } else LOG.noRowsToDelete(); + } else LOG.debug("No rows to delete"); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( @@ -1304,7 +1303,8 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowInsertEnabled() ) { - if (LOG.isDebugEnabled()) LOG.insertingCollectionRows(MessageHelper.collectionInfoString(this, id, getFactory())); + if (LOG.isDebugEnabled()) LOG.debug("Inserting rows of collection: " + + MessageHelper.collectionInfoString(this, id, getFactory())); try { //insert all the new entries @@ -1368,7 +1368,7 @@ public abstract class AbstractCollectionPersister } i++; } - LOG.insertingCollectionRowsDone(count); + LOG.debug("Done inserting rows: " + count + " inserted"); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( @@ -1496,12 +1496,12 @@ public abstract class AbstractCollectionPersister if ( !isInverse && collection.isRowUpdatePossible() ) { - LOG.updatingCollectionRows(role, id); + LOG.debug("Updating rows of collection: " + role + "#" + id); //update all the modified entries int count = doUpdateRows( id, collection, session ); - LOG.updatingCollectionRowsDone(count); + LOG.debug("Done updating rows: " + count + " updated"); } } @@ -1776,80 +1776,4 @@ public abstract class AbstractCollectionPersister public CollectionInitializer getInitializer() { return initializer; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Collection was empty" ) - void collectionWasEmpty(); - - @LogMessage( level = DEBUG ) - @Message( value = "Deleting collection: %s" ) - void deletingCollection( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done deleting collection" ) - void deletingCollectionDone(); - - @LogMessage( level = DEBUG ) - @Message( value = "Deleting rows of collection: %s" ) - void deletingCollectionRows( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done deleting collection rows: %d deleted" ) - void deletingCollectionRowsDone( int count ); - - @LogMessage( level = DEBUG ) - @Message( value = "Inserting collection: %s" ) - void insertingCollection( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done inserting collection: %d rows inserted" ) - void insertingCollectionDone( int count ); - - @LogMessage( level = DEBUG ) - @Message( value = "Inserting rows of collection: %s" ) - void insertingCollectionRows( String collectionInfoString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done inserting rows: %d inserted" ) - void insertingCollectionRowsDone( int count ); - - @LogMessage( level = DEBUG ) - @Message( value = "No rows to delete" ) - void noRowsToDelete(); - - @LogMessage( level = DEBUG ) - @Message( value = " One-shot delete: %s" ) - void oneShotDelete( String sqlDeleteString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Row delete: %s" ) - void rowDelete( String sqlDeleteRowString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Row insert: %s" ) - void rowInsert( String sqlInsertRowString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Row update: %s" ) - void rowUpdate( String sqlUpdateRowString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Static SQL for collection: %s" ) - void staticSqlForCollection( String role ); - - @LogMessage( level = DEBUG ) - @Message( value = "Updating rows of collection: %s#%s" ) - void updatingCollectionRows( String role, - Serializable id ); - - @LogMessage( level = DEBUG ) - @Message( value = "Done updating rows: %d updated" ) - void updatingCollectionRowsDone( int count ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java index 476fe5e14b..8069689d91 100755 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/NamedQueryCollectionInitializer.java @@ -24,17 +24,13 @@ */ package org.hibernate.persister.collection; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import org.hibernate.FlushMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionImplementor; import org.hibernate.impl.AbstractQueryImpl; import org.hibernate.loader.collection.CollectionInitializer; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A wrapper around a named query. @@ -57,7 +53,7 @@ public final class NamedQueryCollectionInitializer implements CollectionInitiali public void initialize(Serializable key, SessionImplementor session) throws HibernateException { - LOG.initializingCollection(persister.getRole(), queryName); + LOG.debug("Initializing collection: " + persister.getRole() + " using named query: " + queryName); //TODO: is there a more elegant way than downcasting? AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedSQLQuery(queryName); @@ -76,16 +72,4 @@ public final class NamedQueryCollectionInitializer implements CollectionInitiali .list(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Initializing collection: %s using named query: %s" ) - void initializingCollection( String role, - String queryName ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index 422e9bdb05..bd6f5d26cc 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -23,8 +23,6 @@ */ package org.hibernate.persister.entity; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -43,6 +41,7 @@ import org.hibernate.FetchMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.StaleObjectStateException; @@ -109,10 +108,6 @@ import org.hibernate.type.VersionType; import org.hibernate.util.ArrayHelper; import org.hibernate.util.FilterHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic functionality for persisting an entity via JDBC @@ -796,7 +791,8 @@ public abstract class AbstractEntityPersister throw new HibernateException( "entity is not associated with the session: " + id ); } - if (LOG.isTraceEnabled()) LOG.initializingLazyProperties(MessageHelper.infoString(this, id, getFactory()), fieldName); + if (LOG.isTraceEnabled()) LOG.trace("Initializing lazy properties of: " + MessageHelper.infoString(this, id, getFactory()) + + ", field access: " + fieldName); if ( hasCache() ) { CacheKey cacheKey = new CacheKey(id, getIdentifierType(), getEntityName(), session.getEntityMode(), getFactory() ); @@ -823,7 +819,7 @@ public abstract class AbstractEntityPersister if (!hasLazyProperties()) throw new AssertionFailure("no lazy properties"); - LOG.initializingLazyPropertiesFromDataStore(); + LOG.trace("Initializing lazy properties from datastore"); try { @@ -862,7 +858,7 @@ public abstract class AbstractEntityPersister } } - LOG.initializingLazyPropertiesDone(); + LOG.trace("Done initializing lazy properties"); return result; @@ -885,7 +881,7 @@ public abstract class AbstractEntityPersister final CacheEntry cacheEntry ) { - LOG.initializingLazyPropertiesFromSecondLevelCache(); + LOG.trace("Initializing lazy properties from second-level cache"); Object result = null; Serializable[] disassembledValues = cacheEntry.getDisassembledState(); @@ -901,7 +897,7 @@ public abstract class AbstractEntityPersister } } - LOG.initializingLazyPropertiesDone(); + LOG.trace("Done initializing lazy properties"); return result; } @@ -1079,7 +1075,8 @@ public abstract class AbstractEntityPersister public Object[] getDatabaseSnapshot(Serializable id, SessionImplementor session) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.gettingCurrentPersistentState(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Getting current persistent state for: " + + MessageHelper.infoString(this, id, getFactory())); try { PreparedStatement ps = session.getJDBCContext().getConnectionManager().prepareSelectStatement( getSQLSnapshotSelectString() ); @@ -1280,7 +1277,9 @@ public abstract class AbstractEntityPersister } Object nextVersion = getVersionType().next( currentVersion, session ); - if (LOG.isTraceEnabled()) LOG.forcingVersionIncrement(MessageHelper.infoString( this, id, getFactory() ), getVersionType().toLoggableString( currentVersion, getFactory() ), getVersionType().toLoggableString( nextVersion, getFactory() )); + if (LOG.isTraceEnabled()) LOG.trace("Forcing version increment [" + MessageHelper.infoString(this, id, getFactory()) + "; " + + getVersionType().toLoggableString(currentVersion, getFactory()) + " -> " + + getVersionType().toLoggableString(nextVersion, getFactory()) + "]"); // todo : cache this sql... String versionIncrementString = generateVersionIncrementUpdateString(); @@ -1329,7 +1328,7 @@ public abstract class AbstractEntityPersister */ public Object getCurrentVersion(Serializable id, SessionImplementor session) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.gettingVersion(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Getting version: " + MessageHelper.infoString(this, id, getFactory())); try { @@ -2137,7 +2136,7 @@ public abstract class AbstractEntityPersister final SessionImplementor session, int index) throws SQLException, HibernateException { - if (LOG.isTraceEnabled()) LOG.dehydratingEntity(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Dehydrating entity: " + MessageHelper.infoString(this, id, getFactory())); for ( int i = 0; i < entityMetamodel.getPropertySpan(); i++ ) { if ( includeProperty[i] && isPropertyOfTable( i, j ) ) { @@ -2174,7 +2173,7 @@ public abstract class AbstractEntityPersister final boolean allProperties, final SessionImplementor session) throws SQLException, HibernateException { - if (LOG.isTraceEnabled()) LOG.hydratingEntity(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Hydrating entity: " + MessageHelper.infoString(this, id, getFactory())); final AbstractEntityPersister rootPersister = (AbstractEntityPersister) rootLoadable; @@ -2286,8 +2285,8 @@ public abstract class AbstractEntityPersister final SessionImplementor session) throws HibernateException { if (LOG.isTraceEnabled()) { - LOG.insertingEntityWithNativeId(getEntityName()); - if (isVersioned()) LOG.version(Versioning.getVersion(fields, this)); + LOG.trace("Inserting entity: " + getEntityName() + " (native id)"); + if (isVersioned()) LOG.trace("Version: " + Versioning.getVersion(fields, this)); } Binder binder = new Binder() { @@ -2344,8 +2343,8 @@ public abstract class AbstractEntityPersister } if (LOG.isTraceEnabled()) { - LOG.insertingEntity(MessageHelper.infoString(this, id, getFactory())); - if (j == 0 && isVersioned()) LOG.version(Versioning.getVersion(fields, this)); + LOG.trace("Inserting entity: " + MessageHelper.infoString(this, id, getFactory())); + if (j == 0 && isVersioned()) LOG.trace("Version: " + Versioning.getVersion(fields, this)); } Expectation expectation = Expectations.appropriateExpectation( insertResultCheckStyles[j] ); @@ -2466,8 +2465,8 @@ public abstract class AbstractEntityPersister final boolean useBatch = j == 0 && expectation.canBeBatched() && isBatchable(); //note: updates to joined tables can't be batched... if (LOG.isTraceEnabled()) { - LOG.updatingEntity(MessageHelper.infoString(this, id, getFactory())); - if (useVersion) LOG.updateVersion(oldVersion, fields[getVersionProperty()]); + LOG.trace("Updating entity: " + MessageHelper.infoString(this, id, getFactory())); + if (useVersion) LOG.trace("Existing version: " + oldVersion + " -> New version:" + fields[getVersionProperty()]); } try { @@ -2570,12 +2569,12 @@ public abstract class AbstractEntityPersister final boolean useBatch = j == 0 && isBatchable() && expectation.canBeBatched(); if (LOG.isTraceEnabled()) { - LOG.deletingEntity(MessageHelper.infoString(this, id, getFactory())); - if (useVersion) LOG.version(version); + LOG.trace("Deleting entity: " + MessageHelper.infoString(this, id, getFactory())); + if (useVersion) LOG.trace("Version: " + version); } if ( isTableCascadeDeleteEnabled( j ) ) { - LOG.deleteHandledByForeignKeyConstraint(getTableName(j)); + LOG.trace("Delete handled by foreign key constraint: " + getTableName(j)); return; //EARLY EXIT! } @@ -2864,20 +2863,22 @@ public abstract class AbstractEntityPersister protected void logStaticSQL() { if (LOG.isDebugEnabled()) { - LOG.staticSqlForEntity(getEntityName()); - if (sqlLazySelectString != null) LOG.lazySelect(sqlLazySelectString); - if (sqlVersionSelectString != null) LOG.versionSelect(sqlVersionSelectString); - if (sqlSnapshotSelectString != null) LOG.snapshotSelect(sqlSnapshotSelectString); + LOG.debug("Static SQL for entity: " + getEntityName()); + if (sqlLazySelectString != null) LOG.debug(" Lazy select: " + sqlLazySelectString); + if (sqlVersionSelectString != null) LOG.debug(" Version select: " + sqlVersionSelectString); + if (sqlSnapshotSelectString != null) LOG.debug(" Snapshot select: " + sqlSnapshotSelectString); for ( int j = 0; j < getTableSpan(); j++ ) { - LOG.insert(j, getSQLInsertStrings()[j]); - LOG.update(j, getSQLUpdateStrings()[j]); - LOG.delete(j, getSQLDeleteStrings()[j]); + LOG.debug(" Insert " + j + ": " + getSQLInsertStrings()[j]); + LOG.debug(" Update " + j + ": " + getSQLUpdateStrings()[j]); + LOG.debug(" Delete " + j + ": " + getSQLDeleteStrings()[j]); } - if (sqlIdentityInsertString != null) LOG.identityInsert(sqlIdentityInsertString); - if (sqlUpdateByRowIdString != null) LOG.updateAllFieldsByRowId(sqlUpdateByRowIdString); - if (sqlLazyUpdateByRowIdString != null) LOG.updateNonLazyFieldsByRowId(sqlLazyUpdateByRowIdString); - if (sqlInsertGeneratedValuesSelectString != null) LOG.insertGeneratedPropertySelect(sqlInsertGeneratedValuesSelectString); - if (sqlUpdateGeneratedValuesSelectString != null) LOG.updateGeneratedPropertySelect(sqlUpdateGeneratedValuesSelectString); + if (sqlIdentityInsertString != null) LOG.debug(" Identity insert: " + sqlIdentityInsertString); + if (sqlUpdateByRowIdString != null) LOG.debug(" Update by row id (all fields): " + sqlUpdateByRowIdString); + if (sqlLazyUpdateByRowIdString != null) LOG.debug(" Update by row id (non-lazy fields): " + sqlLazyUpdateByRowIdString); + if (sqlInsertGeneratedValuesSelectString != null) LOG.debug("Insert-generated property select: " + + sqlInsertGeneratedValuesSelectString); + if (sqlUpdateGeneratedValuesSelectString != null) LOG.debug("Update-generated property select: " + + sqlUpdateGeneratedValuesSelectString); } } @@ -3173,7 +3174,7 @@ public abstract class AbstractEntityPersister public Object load(Serializable id, Object optionalObject, LockOptions lockOptions, SessionImplementor session) throws HibernateException { - if (LOG.isTraceEnabled()) LOG.fetchingEntity(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Fetching entity: " + MessageHelper.infoString(this, id, getFactory())); final UniqueEntityLoader loader = getAppropriateLoader(lockOptions, session ); return loader.load( id, optionalObject, session, lockOptions ); @@ -3346,7 +3347,7 @@ public abstract class AbstractEntityPersister if (LOG.isTraceEnabled()) { for ( int i = 0; i < props.length; i++ ) { String propertyName = entityMetamodel.getProperties()[ props[i] ].getName(); - LOG.propertyIsDirty(StringHelper.qualify(getEntityName(), propertyName)); + LOG.trace(StringHelper.qualify(getEntityName(), propertyName) + " is dirty"); } } } @@ -3945,7 +3946,8 @@ public abstract class AbstractEntityPersister if ( !hasNaturalIdentifier() ) { throw new MappingException( "persistent class did not define a natural-id : " + MessageHelper.infoString( this ) ); } - if (LOG.isTraceEnabled()) LOG.gettingNaturalIdSnapshotState(MessageHelper.infoString(this, id, getFactory())); + if (LOG.isTraceEnabled()) LOG.trace("Getting current natural-id snapshot state for: " + + MessageHelper.infoString(this, id, getFactory())); int[] naturalIdPropertyIndexes = getNaturalIdentifierProperties(); int naturalIdPropertyCount = naturalIdPropertyIndexes.length; @@ -4034,142 +4036,4 @@ public abstract class AbstractEntityPersister throws HibernateException { getTuplizer( entityMode ).setPropertyValue( object, propertyName, value ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Dehydrating entity: %s" ) - void dehydratingEntity( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Delete %d: %s" ) - void delete( int j, - String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Delete handled by foreign key constraint: %s" ) - void deleteHandledByForeignKeyConstraint( String tableName ); - - @LogMessage( level = TRACE ) - @Message( value = "Deleting entity: %s" ) - void deletingEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Fetching entity: %s" ) - void fetchingEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Forcing version increment [%s; %s -> %s]" ) - void forcingVersionIncrement( String infoString, - String loggableString, - String loggableString2 ); - - @LogMessage( level = TRACE ) - @Message( value = "Getting current persistent state for: %s" ) - void gettingCurrentPersistentState( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Getting current natural-id snapshot state for: %s" ) - void gettingNaturalIdSnapshotState( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Getting version: %s" ) - void gettingVersion( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Hydrating entity: %s" ) - void hydratingEntity( String infoString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Identity insert: %s" ) - void identityInsert( String sqlIdentityInsertString ); - - @LogMessage( level = TRACE ) - @Message( value = "Initializing lazy properties of: %s, field access: %s" ) - void initializingLazyProperties( String infoString, - String fieldName ); - - @LogMessage( level = TRACE ) - @Message( value = "Done initializing lazy properties" ) - void initializingLazyPropertiesDone(); - - @LogMessage( level = TRACE ) - @Message( value = "Initializing lazy properties from datastore" ) - void initializingLazyPropertiesFromDataStore(); - - @LogMessage( level = TRACE ) - @Message( value = "Initializing lazy properties from second-level cache" ) - void initializingLazyPropertiesFromSecondLevelCache(); - - @LogMessage( level = DEBUG ) - @Message( value = " Insert %d: %s" ) - void insert( int j, - String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Insert-generated property select: %s" ) - void insertGeneratedPropertySelect( String sqlInsertGeneratedValuesSelectString ); - - @LogMessage( level = TRACE ) - @Message( value = "Inserting entity: %s" ) - void insertingEntity( String entityName ); - - @LogMessage( level = TRACE ) - @Message( value = "Inserting entity: %s (native id)" ) - void insertingEntityWithNativeId( String entityName ); - - @LogMessage( level = DEBUG ) - @Message( value = " Lazy select: %s" ) - void lazySelect( String sqlLazySelectString ); - - @LogMessage( level = TRACE ) - @Message( value = "%s is dirty" ) - void propertyIsDirty( String qualify ); - - @LogMessage( level = DEBUG ) - @Message( value = " Snapshot select: %s" ) - void snapshotSelect( String sqlSnapshotSelectString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Static SQL for entity: %s" ) - void staticSqlForEntity( String entityName ); - - @LogMessage( level = DEBUG ) - @Message( value = " Update %d: %s" ) - void update( int j, - String string ); - - @LogMessage( level = DEBUG ) - @Message( value = " Update by row id (all fields): %s" ) - void updateAllFieldsByRowId( String sqlUpdateByRowIdString ); - - @LogMessage( level = DEBUG ) - @Message( value = "Update-generated property select: %s" ) - void updateGeneratedPropertySelect( String sqlUpdateGeneratedValuesSelectString ); - - @LogMessage( level = DEBUG ) - @Message( value = " Update by row id (non-lazy fields): %s" ) - void updateNonLazyFieldsByRowId( String sqlLazyUpdateByRowIdString ); - - @LogMessage( level = TRACE ) - @Message( value = "Existing version: %s -> New version: %s" ) - void updateVersion( Object oldVersion, - Object object ); - - @LogMessage( level = TRACE ) - @Message( value = "Updating entity: %s" ) - void updatingEntity( String infoString ); - - @LogMessage( level = TRACE ) - @Message( value = "Version: %s" ) - void version( Object version ); - - @LogMessage( level = DEBUG ) - @Message( value = " Version select: %s" ) - void versionSelect( String sqlVersionSelectString ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractPropertyMapping.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractPropertyMapping.java index d7369e38d7..404e8733e9 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractPropertyMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractPropertyMapping.java @@ -24,9 +24,9 @@ */ package org.hibernate.persister.entity; -import static org.jboss.logging.Logger.Level.TRACE; import java.util.HashMap; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.engine.Mapping; @@ -37,10 +37,6 @@ import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic implementation of the {@link PropertyMapping} contract. @@ -140,7 +136,8 @@ public abstract class AbstractPropertyMapping implements PropertyMapping { String[] formulaTemplates) { // TODO : not quite sure yet of the difference, but this is only needed from annotations for @Id @ManyToOne support if ( typesByPropertyPath.containsKey( path ) ) { - LOG.skippingDuplicatePathRegistration(path, typesByPropertyPath.get(path), type); + LOG.trace("Skipping duplicate registration of path [" + path + "], existing type = [" + typesByPropertyPath.get(path) + + "], incoming type = [" + type + "]"); return; } typesByPropertyPath.put(path, type); @@ -298,17 +295,4 @@ public abstract class AbstractPropertyMapping implements PropertyMapping { return StringHelper.qualify(path, property); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Skipping duplicate registration of path [%s], existing type = [%s], incoming type = [%s]" ) - void skippingDuplicatePathRegistration( String path, - Object object, - Type type ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/NamedQueryLoader.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/NamedQueryLoader.java index 233fd1c061..da37b57ca9 100755 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/NamedQueryLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/NamedQueryLoader.java @@ -24,18 +24,14 @@ */ package org.hibernate.persister.entity; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import org.hibernate.FlushMode; import org.hibernate.LockOptions; +import org.hibernate.Logger; import org.hibernate.engine.EntityKey; import org.hibernate.engine.SessionImplementor; import org.hibernate.impl.AbstractQueryImpl; import org.hibernate.loader.entity.UniqueEntityLoader; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Not really a Loader, just a wrapper around a @@ -58,12 +54,12 @@ public final class NamedQueryLoader implements UniqueEntityLoader { } public Object load(Serializable id, Object optionalObject, SessionImplementor session, LockOptions lockOptions) { - if (lockOptions != null) LOG.ignoringLockOptions(); + if (lockOptions != null) LOG.debug("Ignoring lock-options passed to named query loader"); return load( id, optionalObject, session ); } public Object load(Serializable id, Object optionalObject, SessionImplementor session) { - LOG.loadingEntity(persister.getEntityName(), queryName); + LOG.debug("Loading entity: " + persister.getEntityName() + " using named query: " + queryName); AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedQuery(queryName); if ( query.hasNamedParameters() ) { @@ -89,20 +85,4 @@ public final class NamedQueryLoader implements UniqueEntityLoader { .getEntity( new EntityKey( id, persister, session.getEntityMode() ) ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Ignoring lock-options passed to named query loader" ) - void ignoringLockOptions(); - - @LogMessage( level = DEBUG ) - @Message( value = "Loading entity: %s using named query: %s" ) - void loadingEntity( String entityName, - String queryName ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java b/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java index 04cd29a0ad..b6acae3455 100644 --- a/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java +++ b/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java @@ -24,7 +24,6 @@ */ package org.hibernate.pretty; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -32,15 +31,12 @@ import java.util.List; import java.util.Map; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.TypedValue; import org.hibernate.intercept.LazyPropertyInitializer; import org.hibernate.metadata.ClassMetadata; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Renders entities to a nicely readable string. @@ -106,11 +102,11 @@ public final class Printer { public void toString(Iterator iter, EntityMode entityMode) throws HibernateException { if (!LOG.isDebugEnabled() || !iter.hasNext()) return; - LOG.listingEntities(); + LOG.debug("Listing entities:"); int i=0; while ( iter.hasNext() ) { if (i++>20) { - LOG.more(); + LOG.debug("More......"); break; } LOG.debug(toString(iter.next(), entityMode)); @@ -120,19 +116,4 @@ public final class Printer { public Printer(SessionFactoryImplementor factory) { this.factory = factory; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Listing entities:" ) - void listingEntities(); - - @LogMessage( level = DEBUG ) - @Message( value = "More......" ) - void more(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java b/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java index a6e89a6c19..45420b4508 100644 --- a/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java +++ b/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java @@ -23,22 +23,18 @@ */ package org.hibernate.property; -import static org.jboss.logging.Logger.Level.ERROR; import java.beans.Introspector; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.PropertyAccessException; import org.hibernate.PropertyNotFoundException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Accesses property values via a get/set pair, which may be nonpublic. @@ -386,26 +382,4 @@ public class BasicPropertyAccessor implements PropertyAccessor { return null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = ERROR ) - @Message( value = "Expected type: %s, actual value: %s" ) - void expectedType( String name, - String string ); - - @LogMessage( level = ERROR ) - @Message( value = "IllegalArgumentException in class: %s, getter method of property: %s" ) - void illegalPropertyGetterArgument( String name, - String propertyName ); - - @LogMessage( level = ERROR ) - @Message( value = "IllegalArgumentException in class: %s, setter method of property: %s" ) - void illegalPropertySetterArgument( String name, - String propertyName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java b/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java index cd9c0fbdd6..99af34b956 100755 --- a/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java @@ -24,17 +24,13 @@ */ package org.hibernate.secure; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.StringTokenizer; import javax.security.jacc.EJBMethodPermission; import javax.security.jacc.PolicyConfiguration; import javax.security.jacc.PolicyConfigurationFactory; import javax.security.jacc.PolicyContextException; import org.hibernate.HibernateException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * Adds Hibernate permissions to roles via JACC @@ -79,7 +75,7 @@ public class JACCConfiguration { null // arguments ); - LOG.addingPermissionToRole(role, permission); + LOG.debug("Adding permission to role " + role + ": " + permission); try { policyConfiguration.addToRole( role, permission ); } @@ -88,16 +84,4 @@ public class JACCConfiguration { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Adding permission to role %s: %s" ) - void addingPermissionToRole( String role, - EJBMethodPermission permission ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesInitializer.java b/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesInitializer.java index 4a3e873e1d..61c0f81faa 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesInitializer.java @@ -23,11 +23,11 @@ */ package org.hibernate.service.internal; -import static org.jboss.logging.Logger.Level.TRACE; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.service.jmx.spi.JmxService; import org.hibernate.service.spi.Configurable; import org.hibernate.service.spi.InjectService; @@ -38,10 +38,6 @@ import org.hibernate.service.spi.ServiceInitiator; import org.hibernate.service.spi.ServicesRegistryAwareService; import org.hibernate.service.spi.Startable; import org.hibernate.service.spi.UnknownServiceException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Delegate responsible for initializing services @@ -92,7 +88,7 @@ public class ServicesInitializer { * @return The intiialized instance of the service */ public T initializeService(Class serviceRole) { - LOG.initializingService(serviceRole.getName()); + LOG.trace("Initializing service [role=" + serviceRole.getName() + "]"); // PHASE 1 : create service T service = createService( serviceRole ); @@ -191,15 +187,4 @@ public class ServicesInitializer { servicesRegistry.getService( JmxService.class ).registerService( (Manageable) service, serviceRole ); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Initializing service [role=%s]" ) - void initializingService( String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesRegistryImpl.java index c1c866c2ce..4d4fcb4da0 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/ServicesRegistryImpl.java @@ -23,23 +23,19 @@ */ package org.hibernate.service.internal; -import static org.jboss.logging.Logger.Level.INFO; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.spi.Service; import org.hibernate.service.spi.ServiceInitiator; import org.hibernate.service.spi.ServicesRegistry; import org.hibernate.service.spi.Stoppable; import org.hibernate.service.spi.UnknownServiceException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Basic Hibernate implementation of the service registry. @@ -113,16 +109,4 @@ public class ServicesRegistryImpl implements ServicesRegistry { serviceList.add( service ); serviceMap.put( serviceRole, service ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Error stopping service [%s] : %s" ) - void unableToStopService( Class class1, - String string ); - } } 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 67a6be3b09..24ea8d6d31 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 @@ -23,8 +23,6 @@ */ package org.hibernate.service.jdbc.connections.internal; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.beans.BeanInfo; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; @@ -40,10 +38,6 @@ import org.hibernate.service.classloading.spi.ClassLoaderService; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.ServiceInitiator; import org.hibernate.service.spi.ServicesRegistry; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Instantiates and configures an appropriate {@link ConnectionProvider}. @@ -110,7 +104,7 @@ public class ConnectionProviderInitiator implements ServiceInitiatororder-by
mapping. @@ -69,7 +67,7 @@ public class OrderByFragmentTranslator { if (LOG.isTraceEnabled()) { ASTPrinter printer = new ASTPrinter( OrderByTemplateTokenTypes.class ); - LOG.trace(printer.showAsString(parser.getAST(), LOG.orderByFragmentHeader())); + LOG.trace(printer.showAsString(parser.getAST(), "--- {order-by fragment} ---")); } OrderByFragmentRenderer renderer = new OrderByFragmentRenderer(); @@ -85,14 +83,4 @@ public class OrderByFragmentTranslator { return renderer.getRenderedFragment(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "--- {order-by fragment} ---" ) - String orderByFragmentHeader(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java b/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java index b669d2a95a..7ebb7ccb8d 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java @@ -26,6 +26,7 @@ package org.hibernate.stat; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; +import org.hibernate.Logger; import org.hibernate.cache.Region; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.ArrayHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/stat/Logger.java b/hibernate-core/src/main/java/org/hibernate/stat/Logger.java deleted file mode 100644 index 7c84c0b20b..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/stat/Logger.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.stat; - -import static org.jboss.logging.Logger.Level.INFO; -import java.util.concurrent.atomic.AtomicLong; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Collections fetched (minimize this): %ld" ) - void collectionsFetched( long collectionFetchCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections fetched (minimize this): %s" ) - void collectionsFetched( AtomicLong collectionFetchCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections loaded: %ld" ) - void collectionsLoaded( long collectionLoadCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections loaded: %s" ) - void collectionsLoaded( AtomicLong collectionLoadCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections recreated: %ld" ) - void collectionsRecreated( long collectionRecreateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections recreated: %s" ) - void collectionsRecreated( AtomicLong collectionRecreateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections removed: %ld" ) - void collectionsRemoved( long collectionRemoveCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections removed: %s" ) - void collectionsRemoved( AtomicLong collectionRemoveCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections updated: %ld" ) - void collectionsUpdated( long collectionUpdateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Collections updated: %s" ) - void collectionsUpdated( AtomicLong collectionUpdateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Connections obtained: %ld" ) - void connectionsObtained( long connectCount ); - - @LogMessage( level = INFO ) - @Message( value = "Connections obtained: %s" ) - void connectionsObtained( AtomicLong connectCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities deleted: %ld" ) - void entitiesDeleted( long entityDeleteCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities deleted: %s" ) - void entitiesDeleted( AtomicLong entityDeleteCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities fetched (minimize this): %ld" ) - void entitiesFetched( long entityFetchCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities fetched (minimize this): %s" ) - void entitiesFetched( AtomicLong entityFetchCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities inserted: %ld" ) - void entitiesInserted( long entityInsertCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities inserted: %s" ) - void entitiesInserted( AtomicLong entityInsertCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities loaded: %ld" ) - void entitiesLoaded( long entityLoadCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities loaded: %s" ) - void entitiesLoaded( AtomicLong entityLoadCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities updated: %ld" ) - void entitiesUpdated( long entityUpdateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Entities updated: %s" ) - void entitiesUpdated( AtomicLong entityUpdateCount ); - - @LogMessage( level = INFO ) - @Message( value = "Flushes: %ld" ) - void flushes( long flushCount ); - - @LogMessage( level = INFO ) - @Message( value = "Flushes: %s" ) - void flushes( AtomicLong flushCount ); - - @LogMessage( level = INFO ) - @Message( value = "HQL: %s, time: %sms, rows: %s" ) - void hql( String hql, - Long valueOf, - Long valueOf2 ); - - @LogMessage( level = INFO ) - @Message( value = "Logging statistics...." ) - void loggingStatistics(); - - @LogMessage( level = INFO ) - @Message( value = "Max query time: %ldms" ) - void maxQueryTime( long queryExecutionMaxTime ); - - @LogMessage( level = INFO ) - @Message( value = "Max query time: %sms" ) - void maxQueryTime( AtomicLong queryExecutionMaxTime ); - - @LogMessage( level = INFO ) - @Message( value = "Optimistic lock failures: %ld" ) - void optimisticLockFailures( long optimisticFailureCount ); - - @LogMessage( level = INFO ) - @Message( value = "Optimistic lock failures: %s" ) - void optimisticLockFailures( AtomicLong optimisticFailureCount ); - - @LogMessage( level = INFO ) - @Message( value = "Queries executed to database: %ld" ) - void queriesExecuted( long queryExecutionCount ); - - @LogMessage( level = INFO ) - @Message( value = "Queries executed to database: %s" ) - void queriesExecuted( AtomicLong queryExecutionCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache hits: %ld" ) - void queryCacheHits( long queryCacheHitCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache hits: %s" ) - void queryCacheHits( AtomicLong queryCacheHitCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache misses: %ld" ) - void queryCacheMisses( long queryCacheMissCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache misses: %s" ) - void queryCacheMisses( AtomicLong queryCacheMissCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache puts: %ld" ) - void queryCachePuts( long queryCachePutCount ); - - @LogMessage( level = INFO ) - @Message( value = "Query cache puts: %s" ) - void queryCachePuts( AtomicLong queryCachePutCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache hits: %ld" ) - void secondLevelCacheHits( long secondLevelCacheHitCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache hits: %s" ) - void secondLevelCacheHits( AtomicLong secondLevelCacheHitCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache misses: %ld" ) - void secondLevelCacheMisses( long secondLevelCacheMissCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache misses: %s" ) - void secondLevelCacheMisses( AtomicLong secondLevelCacheMissCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache puts: %ld" ) - void secondLevelCachePuts( long secondLevelCachePutCount ); - - @LogMessage( level = INFO ) - @Message( value = "Second level cache puts: %s" ) - void secondLevelCachePuts( AtomicLong secondLevelCachePutCount ); - - @LogMessage( level = INFO ) - @Message( value = "Sessions closed: %ld" ) - void sessionsClosed( long sessionCloseCount ); - - @LogMessage( level = INFO ) - @Message( value = "Sessions closed: %s" ) - void sessionsClosed( AtomicLong sessionCloseCount ); - - @LogMessage( level = INFO ) - @Message( value = "Sessions opened: %ld" ) - void sessionsOpened( long sessionOpenCount ); - - @LogMessage( level = INFO ) - @Message( value = "Sessions opened: %s" ) - void sessionsOpened( AtomicLong sessionOpenCount ); - - @LogMessage( level = INFO ) - @Message( value = "Start time: %s" ) - void startTime( long startTime ); - - @LogMessage( level = INFO ) - @Message( value = "Statements closed: %ld" ) - void statementsClosed( long closeStatementCount ); - - @LogMessage( level = INFO ) - @Message( value = "Statements closed: %s" ) - void statementsClosed( AtomicLong closeStatementCount ); - - @LogMessage( level = INFO ) - @Message( value = "Statements prepared: %ld" ) - void statementsPrepared( long prepareStatementCount ); - - @LogMessage( level = INFO ) - @Message( value = "Statements prepared: %s" ) - void statementsPrepared( AtomicLong prepareStatementCount ); - - @LogMessage( level = INFO ) - @Message( value = "Successful transactions: %ld" ) - void successfulTransactions( long committedTransactionCount ); - - @LogMessage( level = INFO ) - @Message( value = "Successful transactions: %s" ) - void successfulTransactions( AtomicLong committedTransactionCount ); - - @LogMessage( level = INFO ) - @Message( value = "Transactions: %ld" ) - void transactions( long transactionCount ); - - @LogMessage( level = INFO ) - @Message( value = "Transactions: %s" ) - void transactions( AtomicLong transactionCount ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java b/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java index d4485c8eb7..8e4ee3c715 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java @@ -26,6 +26,7 @@ package org.hibernate.stat; import java.util.HashMap; import java.util.Map; +import org.hibernate.Logger; import org.hibernate.cache.Region; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.ArrayHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java index bbdfcdc138..dd4bad59f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java @@ -24,7 +24,6 @@ */ package org.hibernate.tool.hbm2ddl; -import static org.jboss.logging.Logger.Level.INFO; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -35,15 +34,12 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.exception.JDBCExceptionHelper; import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.mapping.Table; import org.hibernate.util.StringHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * JDBC database metadata @@ -200,15 +196,4 @@ public class DatabaseMetadata { public String toString() { return "DatabaseMetadata" + tables.keySet().toString() + sequences.toString(); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Table not found: %s" ) - void tableNotFound( String name ); - } } 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 3baff52b56..05c2815deb 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 @@ -24,10 +24,6 @@ */ package org.hibernate.tool.hbm2ddl; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -46,6 +42,7 @@ import java.util.List; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.JDBCException; +import org.hibernate.Logger; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; @@ -58,10 +55,6 @@ import org.hibernate.jdbc.util.Formatter; import org.hibernate.util.ConfigHelper; import org.hibernate.util.JDBCExceptionReporter; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Commandline tool to export table schema to the database. This class may also be called from inside an application. @@ -259,7 +252,7 @@ public class SchemaExport { importFileReaders.add( new NamedReader( resourceName, stream ) ); } catch ( HibernateException e ) { - LOG.importFileNotFound(currentFile); + LOG.debug("Import file not found: " + currentFile); } } @@ -403,7 +396,7 @@ public class SchemaExport { } catch ( SQLException e ) { exceptions.add( e ); - LOG.unsuccessfulDrop(dropSQL[i]); + LOG.debug("Unsuccessful: " + dropSQL[i]); LOG.debug(e.getMessage()); } } @@ -542,62 +535,4 @@ public class SchemaExport { public List getExceptions() { return exceptions; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Executing import script: %s" ) - void executingImportScript( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Exporting generated schema to database" ) - void exportingGeneratedSchemaToDatabase(); - - @LogMessage( level = DEBUG ) - @Message( value = "Import file not found: %s" ) - void importFileNotFound( String currentFile ); - - @LogMessage( level = INFO ) - @Message( value = "Running hbm2ddl schema export" ) - void runningHbm2ddlSchemaExport(); - - @LogMessage( level = INFO ) - @Message( value = "Schema export complete" ) - void schemaExportComplete(); - - @Message( value = "Schema export unsuccessful" ) - Object schemaExportUnsuccessful(); - - @Message( value = "Could not close connection" ) - Object unableToCloseConnection(); - - @Message( value = "Error closing imput files: %s" ) - Object unableToCloseInputFiles( String name ); - - @Message( value = "Error closing output file: %s" ) - Object unableToCloseOutputFile( String outputFile ); - - @Message( value = "Error creating schema " ) - Object unableToCreateSchema(); - - @LogMessage( level = WARN ) - @Message( value = "Unable to log SQLWarnings : %s" ) - void unableToLogSqlWarnings( SQLException sqle ); - - @LogMessage( level = ERROR ) - @Message( value = "Unsuccessful: %s" ) - void unsuccessfulCreate( String string ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unsuccessful: %s" ) - void unsuccessfulDrop( String string ); - - @LogMessage( level = INFO ) - @Message( value = "Writing generated schema to file: %s" ) - void writingGeneratedSchemaToFile( String outputFile ); - } } 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 d6b303408d..2420c70dab 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 @@ -24,8 +24,6 @@ */ package org.hibernate.tool.hbm2ddl; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.INFO; import java.io.FileInputStream; import java.io.FileWriter; import java.io.Writer; @@ -37,6 +35,7 @@ import java.util.List; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.JDBCException; +import org.hibernate.Logger; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; @@ -47,10 +46,6 @@ import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.jdbc.util.Formatter; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A commandline tool to update a database schema. May also be called from @@ -273,47 +268,4 @@ public class SchemaUpdate { public void setDelimiter(String delimiter) { this.delimiter = delimiter; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Fetching database metadata" ) - void fetchingDatabaseMetadata(); - - @LogMessage( level = INFO ) - @Message( value = "Running hbm2ddl schema update" ) - void runningHbm2ddlSchemaUpdate(); - - @LogMessage( level = INFO ) - @Message( value = "Schema update complete" ) - void schemaUpdateComplete(); - - @Message( value = "Error closing connection" ) - Object unableToCloseConnection(); - - @Message( value = "Could not complete schema update" ) - Object unableToCompleteSchemaUpdate(); - - @Message( value = "Could not get database metadata" ) - Object unableToGetDatabaseMetadata(); - - @Message( value = "Error running schema update" ) - Object unableToRunSchemaUpdate(); - - @LogMessage( level = ERROR ) - @Message( value = "Unsuccessful: %s" ) - void unsuccessful( String sql ); - - @LogMessage( level = INFO ) - @Message( value = "Updating schema" ) - void updatingSchema(); - - @LogMessage( level = INFO ) - @Message( value = "Writing generated schema to file: %s" ) - void writingGeneratedSchemaToFile( String outputFile ); - } } 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 d5b29794d1..c30811ea9c 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 @@ -24,22 +24,17 @@ */ package org.hibernate.tool.hbm2ddl; -import static org.jboss.logging.Logger.Level.INFO; import java.io.FileInputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; 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; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A commandline tool to update a database schema. May also be called from @@ -158,31 +153,4 @@ public class SchemaValidator { } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Fetching database metadata" ) - void fetchingDatabaseMetadata(); - - @LogMessage( level = INFO ) - @Message( value = "Running schema validator" ) - void runningSchemaValidator(); - - @Message( value = "Error closing connection" ) - Object unableToCloseConnection(); - - @Message( value = "Could not complete schema validation" ) - Object unableToCompleteSchemaValidation(); - - @Message( value = "Could not get database metadata" ) - Object unableToGetDatabaseMetadata(); - - @Message( value = "Error running schema update" ) - Object unableToRunSchemaUpdate(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/TableMetadata.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/TableMetadata.java index 14ac66fda7..dc373a6d24 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/TableMetadata.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/TableMetadata.java @@ -23,19 +23,14 @@ */ package org.hibernate.tool.hbm2ddl; -import static org.jboss.logging.Logger.Level.INFO; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.Set; +import org.hibernate.Logger; import org.hibernate.mapping.ForeignKey; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * JDBC table metadata @@ -210,27 +205,4 @@ public class TableMetadata { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "Columns: %s" ) - void columns( Set keySet ); - - @LogMessage( level = INFO ) - @Message( value = "Foreign keys: %s" ) - void foreignKeys( Set keySet ); - - @LogMessage( level = INFO ) - @Message( value = "Indexes: %s" ) - void indexes( Set keySet ); - - @LogMessage( level = INFO ) - @Message( value = "Table found: %s" ) - void tableFound( String string ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java b/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java index b4455ee720..d3ed0fd9c4 100755 --- a/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java @@ -28,6 +28,7 @@ import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.Transaction; import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; @@ -66,7 +67,7 @@ public class CMTTransaction implements Transaction { return; } - LOG.begin(); + LOG.debug("Begin"); boolean synchronization = jdbcContext.registerSynchronizationIfPossible(); @@ -87,7 +88,7 @@ public class CMTTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - LOG.commit(); + LOG.debug("Commit"); boolean flush = !transactionContext.isFlushModeNever() && !transactionContext.isFlushBeforeCompletionEnabled(); @@ -108,7 +109,7 @@ public class CMTTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - LOG.rollback(); + LOG.debug("Rollback"); try { getTransaction().setRollbackOnly(); diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java b/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java index 3c19c20ac4..785165b01f 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java @@ -28,6 +28,7 @@ import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; +import org.hibernate.Logger; import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.util.JTAHelper; @@ -49,9 +50,9 @@ public final class CacheSynchronization implements Synchronization { private final org.hibernate.Transaction hibernateTransaction; public CacheSynchronization( - TransactionFactory.Context ctx, + TransactionFactory.Context ctx, JDBCContext jdbcContext, - Transaction transaction, + Transaction transaction, org.hibernate.Transaction tx) { this.ctx = ctx; this.jdbcContext = jdbcContext; @@ -63,7 +64,7 @@ public final class CacheSynchronization implements Synchronization { * {@inheritDoc} */ public void beforeCompletion() { - LOG.transactionBeforeCompletionCallback(); + LOG.trace("Transaction before completion callback"); boolean flush; try { @@ -81,7 +82,7 @@ public final class CacheSynchronization implements Synchronization { try { if (flush) { - LOG.automaticallyFlushingSession(); + LOG.trace("Automatically flushing session"); ctx.managedFlush(); } } @@ -107,13 +108,13 @@ public final class CacheSynchronization implements Synchronization { * {@inheritDoc} */ public void afterCompletion(int status) { - LOG.transactionAfterCompletionCallback(status); + LOG.trace("Transaction after completion callback, status: " + status); try { jdbcContext.afterTransactionCompletion(status==Status.STATUS_COMMITTED, hibernateTransaction); } finally { if ( ctx.shouldAutoClose() && !ctx.isClosed() ) { - LOG.automaticallyClosingSession(); + LOG.trace("Automatically closing session"); ctx.managedClose(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java b/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java index c719e13966..03548be6f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java @@ -27,6 +27,7 @@ import java.sql.SQLException; import javax.transaction.Status; import javax.transaction.Synchronization; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.Transaction; import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; @@ -73,13 +74,13 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("cannot re-start transaction after failed commit"); } - LOG.begin(); + LOG.debug("Begin"); try { toggleAutoCommit = jdbcContext.connection().getAutoCommit(); - LOG.currentAutoCommitStatus(toggleAutoCommit); + LOG.debug("current autocommit status: " + toggleAutoCommit); if (toggleAutoCommit) { - LOG.disablingAutoCommit(); + LOG.debug("Disabling autocommit"); jdbcContext.connection().setAutoCommit(false); } } @@ -122,7 +123,7 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - LOG.commit(); + LOG.debug("Commit"); if ( !transactionContext.isFlushModeNever() && callback ) { transactionContext.managedFlush(); //if an exception occurs during flush, user must call rollback() @@ -135,7 +136,7 @@ public class JDBCTransaction implements Transaction { try { commitAndResetAutoCommit(); - LOG.commitedJdbcConnection(); + LOG.debug("Committed JDBC Connection"); committed = true; if ( callback ) { jdbcContext.afterTransactionCompletion( true, this ); @@ -174,7 +175,7 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - LOG.rollback(); + LOG.debug("Rollback"); if (!commitFailed) { @@ -185,7 +186,7 @@ public class JDBCTransaction implements Transaction { try { rollbackAndResetAutoCommit(); - LOG.rolledBackJdbcConnection(); + LOG.debug("Rolled back JDBC Connection"); rolledBack = true; notifySynchronizationsAfterTransactionCompletion(Status.STATUS_ROLLEDBACK); } @@ -215,7 +216,7 @@ public class JDBCTransaction implements Transaction { private void toggleAutoCommit() { try { if (toggleAutoCommit) { - LOG.reenablingAutoCommit(); + LOG.debug("Re-enabling autocommit"); jdbcContext.connection().setAutoCommit( true ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java index 5bc034075c..88d98e45c2 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java @@ -30,6 +30,7 @@ import javax.transaction.SystemException; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.Transaction; import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; @@ -80,13 +81,13 @@ public class JTATransaction implements Transaction { throw new TransactionException( "cannot re-start transaction after failed commit" ); } - LOG.begin(); + LOG.debug("Begin"); try { newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION; if ( newTransaction ) { userTransaction.begin(); - LOG.beganNewJtaTransaction(); + LOG.debug("Began a new JTA transaction"); } } catch ( Exception e ) { @@ -129,7 +130,7 @@ public class JTATransaction implements Transaction { throw new TransactionException( "Transaction not successfully started" ); } - LOG.commit(); + LOG.debug("Commit"); boolean flush = !transactionContext.isFlushModeNever() && ( callback || !transactionContext.isFlushBeforeCompletionEnabled() ); @@ -148,7 +149,7 @@ public class JTATransaction implements Transaction { try { userTransaction.commit(); commitSucceeded = true; - LOG.commitedJtaUserTransaction(); + LOG.debug("Committed JTA UserTransaction"); } catch ( Exception e ) { commitFailed = true; // so the transaction is already rolled back, by JTA spec @@ -177,7 +178,7 @@ public class JTATransaction implements Transaction { throw new TransactionException( "Transaction not successfully started" ); } - LOG.rollback(); + LOG.debug("Rollback"); try { closeIfRequired(); @@ -191,12 +192,12 @@ public class JTATransaction implements Transaction { if ( newTransaction ) { if ( !commitFailed ) { userTransaction.rollback(); - LOG.rolledBackJtaUserTransaction(); + LOG.debug("Rolled back JTA UserTransaction"); } } else { userTransaction.setRollbackOnly(); - LOG.jtaUserTransactionSetToRollbackOnly(); + LOG.debug("Set JTA UserTransaction to rollback only"); } } catch ( Exception e ) { diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java index 65f1c6a149..6b1b9ce631 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java @@ -31,6 +31,7 @@ import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.Transaction; import org.hibernate.TransactionException; import org.hibernate.cfg.Environment; @@ -89,7 +90,7 @@ public class JTATransactionFactory implements TransactionFactory { public void configure(Properties props) throws HibernateException { this.initialContext = resolveInitialContext( props ); this.userTransactionName = resolveUserTransactionName( props ); - LOG.configuredJtaTransactionFactoryForUserTransactionJndiNamespace(userTransactionName); + LOG.trace("Configured JTATransactionFactory to use [" + userTransactionName + "] for UserTransaction JDNI namespace"); } /** @@ -154,7 +155,7 @@ public class JTATransactionFactory implements TransactionFactory { */ protected UserTransaction getUserTransaction() { final String utName = getUserTransactionName(); - LOG.attemptingToLocateUserTransactionViaJndi(utName); + LOG.trace("Attempting to locate UserTransaction via JNDI [" + utName + "]"); try { UserTransaction ut = ( UserTransaction ) getInitialContext().lookup( utName ); @@ -162,7 +163,7 @@ public class JTATransactionFactory implements TransactionFactory { throw new TransactionException( "Naming service lookup for UserTransaction returned null [" + utName +"]" ); } - LOG.obtainedUserTransaction(); + LOG.trace("Obtained UserTransaction"); return ut; } diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/Logger.java b/hibernate-core/src/main/java/org/hibernate/transaction/Logger.java deleted file mode 100644 index 65fc7c6de1..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/transaction/Logger.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.transaction; - -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to locate UserTransaction via JNDI [%s]" ) - void attemptingToLocateUserTransactionViaJndi( String utName ); - - @LogMessage( level = TRACE ) - @Message( value = "Automatically closing session" ) - void automaticallyClosingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Automatically flushing session" ) - void automaticallyFlushingSession(); - - @LogMessage( level = DEBUG ) - @Message( value = "Began a new JTA transaction" ) - void beganNewJtaTransaction(); - - @LogMessage( level = DEBUG ) - @Message( value = "Begin" ) - void begin(); - - @LogMessage( level = DEBUG ) - @Message( value = "Commit" ) - void commit(); - - @LogMessage( level = DEBUG ) - @Message( value = "Committed JDBC Connection" ) - void commitedJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Committed JTA UserTransaction" ) - void commitedJtaUserTransaction(); - - @LogMessage( level = TRACE ) - @Message( value = "Configured JTATransactionFactory to use [%s] for UserTransaction JDNI namespace" ) - void configuredJtaTransactionFactoryForUserTransactionJndiNamespace( String userTransactionName ); - - @LogMessage( level = DEBUG ) - @Message( value = "current autocommit status: %s" ) - void currentAutoCommitStatus( boolean toggleAutoCommit ); - - @LogMessage( level = DEBUG ) - @Message( value = "Disabling autocommit" ) - void disablingAutoCommit(); - - @LogMessage( level = INFO ) - @Message( value = "Instantiated TransactionManagerLookup" ) - void instantiatedTransactionManagerLookup(); - - @LogMessage( level = INFO ) - @Message( value = "Instantiating TransactionManagerLookup: %s" ) - void instantiatingTransactionManagerLookup( String tmLookupClass ); - - @Message( value = "JDBC begin failed" ) - String jdbcBeginFailed(); - - @Message( value = "JDBC rollback failed" ) - String jdbcRollbackFailed(); - - @LogMessage( level = DEBUG ) - @Message( value = "Set JTA UserTransaction to rollback only" ) - void jtaUserTransactionSetToRollbackOnly(); - - @LogMessage( level = WARN ) - @Message( value = "You should set hibernate.transaction.manager_lookup_class if cache is enabled" ) - void managerLookupClassShouldBeSet(); - - @LogMessage( level = TRACE ) - @Message( value = "Obtained UserTransaction" ) - void obtainedUserTransaction(); - - @LogMessage( level = INFO ) - @Message( value = "Obtaining TransactionManager" ) - void obtainingTransactionManager(); - - @LogMessage( level = DEBUG ) - @Message( value = "Re-enabling autocommit" ) - void reenablingAutoCommit(); - - @LogMessage( level = DEBUG ) - @Message( value = "Rollback" ) - void rollback(); - - @LogMessage( level = DEBUG ) - @Message( value = "Rolled back JDBC Connection" ) - void rolledBackJdbcConnection(); - - @LogMessage( level = DEBUG ) - @Message( value = "Rolled back JTA UserTransaction" ) - void rolledBackJtaUserTransaction(); - - @LogMessage( level = TRACE ) - @Message( value = "Transaction after completion callback, status: %d" ) - void transactionAfterCompletionCallback( int status ); - - @LogMessage( level = TRACE ) - @Message( value = "Transaction before completion callback" ) - void transactionBeforeCompletionCallback(); - - @Message( value = "TransactionFactory class not found" ) - String transactionFactoryClassNotFound(); - - @Message( value = "TransactionFactory class not found: %s" ) - String transactionFactoryClassNotFound( String strategyClassName ); - - @LogMessage( level = INFO ) - @Message( value = "No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)" ) - void transactionManagerLookupNotConfigured(); - - @LogMessage( level = INFO ) - @Message( value = "Transaction strategy: %s" ) - void transactionStrategy( String strategyClassName ); - - @Message( value = "JTA transaction begin failed" ) - String unableToBeginJtaTransaction(); - - @Message( value = "Could not close session" ) - String unableToCloseSession(); - - @Message( value = "Could not close session during rollback" ) - String unableToCloseSessionDuringRollback(); - - @Message( value = "JTA commit failed" ) - String unableToCommitJta(); - - @Message( value = "Could not determine transaction status" ) - String unableToDetermineTransactionStatus(); - - @Message( value = "Could not determine transaction status after commit" ) - String unableToDetermineTransactionStatusAfterCommit(); - - @Message( value = "Failed to instantiate TransactionFactory" ) - String unableToInstantiateTransactionFactory(); - - @Message( value = "Failed to instantiate TransactionFactory: %s" ) - String unableToInstantiateTransactionFactory( Exception error ); - - @Message( value = "Failed to instantiate TransactionManagerLookup" ) - String unableToInstantiateTransactionManagerLookup(); - - @Message( value = "Failed to instantiate TransactionManagerLookup '%s'" ) - String unableToInstantiateTransactionManagerLookup( String tmLookupClass ); - - @Message( value = "JDBC commit failed" ) - String unableToPerformJdbcCommit(); - - @Message( value = "JTA rollback failed" ) - String unableToRollbackJta(); - - @Message( value = "Could not set transaction to rollback only" ) - String unableToSetTransactionToRollbackOnly(); - - @Message( value = "Could not toggle autocommit" ) - Object unableToToggleAutoCommit(); - - @LogMessage( level = INFO ) - @Message( value = "Using default transaction strategy (direct JDBC transactions)" ) - void usingDefaultTransactionStrategy(); -} diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java index b18f71a312..b27b9d36d1 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java @@ -26,6 +26,7 @@ package org.hibernate.transaction; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.util.ReflectHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java index 5a8c58fe4f..7f01b60f83 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java @@ -27,6 +27,7 @@ package org.hibernate.transaction; import java.util.Properties; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; import org.hibernate.util.ReflectHelper; diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java b/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java index 917f8c64a8..057e74c10a 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java @@ -28,6 +28,7 @@ import java.util.Properties; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; +import org.hibernate.Logger; /** * {@link TransactionManagerLookup} strategy for WebSphere (versions 4, 5.0 and 5.1) diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/CallbackCoordinator.java b/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/CallbackCoordinator.java index 73ec4df3b7..2f07858129 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/CallbackCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/CallbackCoordinator.java @@ -23,19 +23,14 @@ */ package org.hibernate.transaction.synchronization; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.TRACE; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; +import org.hibernate.Logger; import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.transaction.TransactionFactory; import org.hibernate.util.JTAHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Manages callbacks from the {@link javax.transaction.Synchronization} registered by Hibernate. @@ -102,7 +97,7 @@ public class CallbackCoordinator { // sync callbacks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public void beforeCompletion() { - LOG.transactionBeforeCompletionCallback(); + LOG.trace("Transaction before completion callback"); boolean flush; try { @@ -115,7 +110,7 @@ public class CallbackCoordinator { try { if ( flush ) { - LOG.automaticallyFlushingSession(); + LOG.trace("Automatically flushing session"); ctx.managedFlush(); } } @@ -139,7 +134,7 @@ public class CallbackCoordinator { } public void afterCompletion(int status) { - LOG.transactionAfterCompletionCallback(status); + LOG.trace("Transaction after completion callback [status=" + status + "]"); try { afterCompletionAction.doAction( ctx, status ); @@ -151,7 +146,7 @@ public class CallbackCoordinator { reset(); jdbcContext.cleanUpJtaSynchronizationCallbackCoordinator(); if ( ctx.shouldAutoClose() && !ctx.isClosed() ) { - LOG.automaticallyClosingSession(); + LOG.trace("Automatically closing session"); ctx.managedClose(); } } @@ -186,38 +181,4 @@ public class CallbackCoordinator { // nothing to do by default. } }; - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Automatically closing session" ) - void automaticallyClosingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Automatically flushing session" ) - void automaticallyFlushingSession(); - - @LogMessage( level = TRACE ) - @Message( value = "Transaction after completion callback [status=%d]" ) - void transactionAfterCompletionCallback( int status ); - - @LogMessage( level = TRACE ) - @Message( value = "Transaction before completion callback" ) - void transactionBeforeCompletionCallback(); - - @LogMessage( level = ERROR ) - @Message( value = "Could not determine transaction status [%s]" ) - void unableToDetermineTransactionStatus( String message ); - - @LogMessage( level = ERROR ) - @Message( value = "Error during managed flush [%s]" ) - void unableToPerformManagedFlush( String message ); - - @Message( value = "Could not set transaction to rollback only" ) - Object unableToSetTransactionToRollbackOnly(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/HibernateSynchronizationImpl.java b/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/HibernateSynchronizationImpl.java index bd63475bdf..db5a820d11 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/HibernateSynchronizationImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/synchronization/HibernateSynchronizationImpl.java @@ -23,12 +23,8 @@ */ package org.hibernate.transaction.synchronization; -import static org.jboss.logging.Logger.Level.TRACE; import javax.transaction.Synchronization; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * The {@link Synchronization} implementation Hibernate registers with the JTA {@link javax.transaction.Transaction} @@ -51,7 +47,7 @@ public class HibernateSynchronizationImpl implements Synchronization { * {@inheritDoc} */ public void beforeCompletion() { - LOG.jtaSyncBeforeCompletion(); + LOG.trace("JTA sync : beforeCompletion()"); coordinator.beforeCompletion(); } @@ -59,22 +55,7 @@ public class HibernateSynchronizationImpl implements Synchronization { * {@inheritDoc} */ public void afterCompletion(int status) { - LOG.jtaSyncAfterCompletion(status); + LOG.trace("JTA sync : afterCompletion(" + status + ")"); coordinator.afterCompletion( status ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "JTA sync : afterCompletion(%d)" ) - void jtaSyncAfterCompletion( int status ); - - @LogMessage( level = TRACE ) - @Message( value = "JTA sync : beforeCompletion()" ) - void jtaSyncBeforeCompletion(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java b/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java index 4a3cdd1a13..bef65712f5 100644 --- a/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java @@ -24,15 +24,11 @@ */ package org.hibernate.transform; -import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * Distinctions the result tuples in the final result based on the defined @@ -97,7 +93,7 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { result.add( entity ); } } - LOG.transformed(list.size(), result.size()); + LOG.debug("Transformed: " + list.size() + " rows to: " + result.size() + " distinct results"); return result; } @@ -109,16 +105,4 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { private Object readResolve() { return INSTANCE; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Transformed: %d rows to: %d distinct results" ) - void transformed( int size, - int size2 ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java b/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java index 43fc4b32f4..4d4796f0a3 100755 --- a/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java @@ -24,20 +24,16 @@ */ package org.hibernate.tuple; -import static org.jboss.logging.Logger.Level.INFO; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Constructor; import org.hibernate.InstantiationException; +import org.hibernate.Logger; import org.hibernate.PropertyNotFoundException; import org.hibernate.bytecode.ReflectionOptimizer; import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Defines a POJO-based instantiator for use from the tuplizers. @@ -122,15 +118,4 @@ public class PojoInstantiator implements Instantiator, Serializable { return mappedClass.isInstance(object) || ( proxyInterface!=null && proxyInterface.isInstance(object) ); //this one needed only for guessEntityMode() } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "No default (no-argument) constructor for class: %s (class must be instantiated by Interceptor)" ) - void noDefaultConstructor( String name ); - } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java index 4c9e62aab2..9d59b7238f 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java @@ -23,13 +23,13 @@ */ package org.hibernate.tuple.entity; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityKey; @@ -53,10 +53,6 @@ import org.hibernate.type.ComponentType; import org.hibernate.type.CompositeType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** @@ -371,7 +367,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { subId = pcEntry.getId(); } else { - LOG.performingImplicitDerivedIdentityCascade(); + LOG.debug("Performing implicit derived identity cascade"); final PersistEvent event = new PersistEvent( null, propertyValues[i], (EventSource) session ); for ( int x = 0; x < session.getListeners().getPersistEventListeners().length; x++ ) { session.getListeners().getPersistEventListeners()[x].onPersist( event ); @@ -676,15 +672,4 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { public Getter getGetter(int i) { return getters[i]; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Performing implicit derived identity cascade" ) - void performingImplicitDerivedIdentityCascade(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/Dom4jEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/Dom4jEntityTuplizer.java index b7edffae2b..bc9ca0ba28 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/Dom4jEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/Dom4jEntityTuplizer.java @@ -32,6 +32,7 @@ import org.dom4j.Element; import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.mapping.PersistentClass; @@ -46,9 +47,6 @@ import org.hibernate.proxy.dom4j.Dom4jProxyFactory; import org.hibernate.tuple.Dom4jInstantiator; import org.hibernate.tuple.Instantiator; import org.hibernate.type.CompositeType; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An {@link EntityTuplizer} specific to the dom4j entity mode. @@ -239,14 +237,4 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { return rootEntityName.hashCode(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "could not create proxy factory for:%s" ) - Object unableToCreateProxyFactory( String entityName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java index 174e53afbe..2c35c5c198 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/DynamicMapEntityTuplizer.java @@ -27,6 +27,7 @@ import java.util.Map; import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; @@ -38,9 +39,6 @@ import org.hibernate.proxy.ProxyFactory; import org.hibernate.proxy.map.MapProxyFactory; import org.hibernate.tuple.DynamicMapInstantiator; import org.hibernate.tuple.Instantiator; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An {@link EntityTuplizer} specific to the dynamic-map entity mode. @@ -191,14 +189,4 @@ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer { return getClass().hashCode(); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Could not create proxy factory for:%s" ) - Object unableToCreateProxyFactory( String entityName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java index 46cda4abfb..e07aaac65d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java @@ -23,8 +23,6 @@ */ package org.hibernate.tuple.entity; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; @@ -35,6 +33,7 @@ import java.util.Map; import java.util.Set; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.engine.CascadeStyle; import org.hibernate.engine.SessionFactoryImplementor; @@ -55,10 +54,6 @@ import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Centralizes metamodel information about an entity. @@ -640,19 +635,4 @@ public class EntityMetamodel implements Serializable { public boolean hasUpdateGeneratedValues() { return hasUpdateGeneratedValues; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = WARN ) - @Message( value = "Entity [%s] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names" ) - void entityMappedAsNonAbstract( String name ); - - @LogMessage( level = INFO ) - @Message( value = "Lazy property fetching available for: %s" ) - void lazyPropertyFetchingAvailable( String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java index 6287d51de9..b0c69ca5a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/PojoEntityTuplizer.java @@ -23,7 +23,6 @@ */ package org.hibernate.tuple.entity; -import static org.jboss.logging.Logger.Level.ERROR; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; @@ -33,6 +32,7 @@ import java.util.Set; import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.bytecode.ReflectionOptimizer; import org.hibernate.cfg.Environment; @@ -53,10 +53,6 @@ import org.hibernate.tuple.Instantiator; import org.hibernate.tuple.PojoInstantiator; import org.hibernate.type.CompositeType; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * An {@link EntityTuplizer} specific to the pojo entity mode. @@ -380,24 +376,4 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { public EntityNameResolver[] getEntityNameResolvers() { return null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = ERROR ) - @Message( value = "Getters of lazy classes cannot be final: %s.%s" ) - void gettersOfLazyClassesCannotBeFinal( String entityName, - String name ); - - @LogMessage( level = ERROR ) - @Message( value = "Setters of lazy classes cannot be final: %s.%s" ) - void settersOfLazyClassesCannotBeFinal( String entityName, - String name ); - - @Message( value = "Could not create proxy factory for:%s" ) - Object unableToCreateProxyFactory( String entityName ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java index 8dc9225f9f..e33c35f7b0 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java @@ -23,19 +23,13 @@ */ package org.hibernate.type; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.UserType; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A registry of {@link BasicType} instances @@ -142,7 +136,7 @@ public class BasicTypeRegistry implements Serializable { for ( String key : type.getRegistrationKeys() ) { // be safe... if (key == null) continue; - LOG.addingTypeRegistration(key, type); + LOG.debug("Adding type registration " + key + " -> " + type); final Type old = registry.put( key, type ); if (old != null && old != type) LOG.typeRegistrationOverridesPrevious(key, old); } @@ -163,25 +157,4 @@ public class BasicTypeRegistry implements Serializable { public BasicTypeRegistry shallowCopy() { return new BasicTypeRegistry( this.registry ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Adding type registration %s -> %s" ) - void addingTypeRegistration( String key, - BasicType type ); - - @LogMessage( level = WARN ) - @Message( value = "Type [%s] defined no registration keys; ignoring" ) - void typeDefinedNoRegistrationKeys( BasicType type ); - - @LogMessage( level = INFO ) - @Message( value = "Type registration [%s] overrides previous : %s" ) - void typeRegistrationOverridesPrevious( String key, - Type old ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java b/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java index 1dd57ad318..5d522ab877 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java @@ -23,20 +23,15 @@ */ package org.hibernate.type; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.TRACE; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; +import org.hibernate.Logger; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * dbtimestamp: An extension of {@link TimestampType} which @@ -68,11 +63,11 @@ public class DbTimestampType extends TimestampType { @Override public Date seed(SessionImplementor session) { if ( session == null ) { - LOG.incomingSessionWasNull(); + LOG.trace("Incoming session was null; using current jvm time"); return super.seed( session ); } else if ( !session.getFactory().getDialect().supportsCurrentTimestampSelection() ) { - LOG.fallingBackToVmBasedTimestamp(); + LOG.debug("Falling back to vm-based timestamp, as dialect does not support current timestamp selection"); return super.seed( session ); } else { @@ -98,7 +93,7 @@ public class DbTimestampType extends TimestampType { ResultSet rs = ps.executeQuery(); rs.next(); Timestamp ts = rs.getTimestamp( 1 ); - LOG.currentTimestampRetrievedFromDatabase(ts, ts.getNanos(), ts.getTime()); + LOG.trace("Current timestamp retreived from db : " + ts + " (nanos=" + ts.getNanos() + ", time=" + ts.getTime() + ")"); return ts; } catch( SQLException sqle ) { @@ -127,7 +122,7 @@ public class DbTimestampType extends TimestampType { cs.registerOutParameter( 1, java.sql.Types.TIMESTAMP ); cs.execute(); Timestamp ts = cs.getTimestamp( 1 ); - LOG.currentTimestampRetrievedFromDatabase(ts, ts.getNanos(), ts.getTime()); + LOG.trace("Current timestamp retreived from db : " + ts + " (nanos=" + ts.getNanos() + ", time=" + ts.getTime() + ")"); return ts; } catch( SQLException sqle ) { @@ -148,31 +143,4 @@ public class DbTimestampType extends TimestampType { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Falling back to vm-based timestamp, as dialect does not support current timestamp selection" ) - void fallingBackToVmBasedTimestamp(); - - @LogMessage( level = TRACE ) - @Message( value = "Current timestamp retreived from db : %s (nanos=%d, time=%ld)" ) - void currentTimestampRetrievedFromDatabase( Timestamp ts, - int nanos, - long time ); - - @LogMessage( level = TRACE ) - @Message( value = "Incoming session was null; using current jvm time" ) - void incomingSessionWasNull(); - - @Message( value = "Unable to clean up callable statement" ) - Object unableToCleanUpCallableStatement(); - - @Message( value = "Unable to clean up prepared statement" ) - Object unableToCleanUpPreparedStatement(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/EnumType.java b/hibernate-core/src/main/java/org/hibernate/type/EnumType.java index 75135a00e3..18d3c0a6db 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/EnumType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/EnumType.java @@ -30,6 +30,7 @@ import java.sql.SQLException; import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.usertype.EnhancedUserType; import org.hibernate.usertype.ParameterizedType; import org.hibernate.util.ReflectHelper; @@ -79,7 +80,7 @@ public class EnumType implements EnhancedUserType, ParameterizedType, Serializab public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { Object object = rs.getObject( names[0] ); if ( rs.wasNull() ) { - if (LOG.isTraceEnabled()) LOG.returningAsColumn(names[0]); + if (LOG.isTraceEnabled()) LOG.trace("Returning null as column " + names[0]); return null; } if ( object instanceof Number ) { @@ -87,12 +88,12 @@ public class EnumType implements EnhancedUserType, ParameterizedType, Serializab int ordinal = ( ( Number ) object ).intValue(); if (ordinal < 0 || ordinal >= enumValues.length) throw new IllegalArgumentException("Unknown ordinal value for enum " + enumClass + ": " + ordinal); - if (LOG.isTraceEnabled()) LOG.returningAsColumn(ordinal, names[0]); + if (LOG.isTraceEnabled()) LOG.trace("Returning '" + ordinal + "' as column " + names[0]); return enumValues[ordinal]; } else { String name = ( String ) object; - if (LOG.isTraceEnabled()) LOG.returningAsColumn(name, names[0]); + if (LOG.isTraceEnabled()) LOG.trace("Returning '" + name + "' as column " + names[0]); try { return Enum.valueOf( enumClass, name ); } @@ -104,19 +105,19 @@ public class EnumType implements EnhancedUserType, ParameterizedType, Serializab public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if ( value == null ) { - if (LOG.isTraceEnabled()) LOG.bindingToParameter(index); + if (LOG.isTraceEnabled()) LOG.trace("Binding null to parameter: " + index); st.setNull( index, sqlType ); } else { boolean isOrdinal = isOrdinal( sqlType ); if ( isOrdinal ) { int ordinal = ( ( Enum ) value ).ordinal(); - if (LOG.isTraceEnabled()) LOG.bindingToParameter(ordinal, index); + if (LOG.isTraceEnabled()) LOG.trace("Binding '" + ordinal + "' to parameter: " + index); st.setObject( index, Integer.valueOf( ordinal ), sqlType ); } else { String enumString = ( ( Enum ) value ).name(); - if (LOG.isTraceEnabled()) LOG.bindingToParameter(enumString, index); + if (LOG.isTraceEnabled()) LOG.trace("Binding '" + enumString + "' to parameter: " + index); st.setObject( index, enumString, sqlType ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/Logger.java b/hibernate-core/src/main/java/org/hibernate/type/Logger.java deleted file mode 100644 index 15b6ce65f8..0000000000 --- a/hibernate-core/src/main/java/org/hibernate/type/Logger.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate.type; - -import static org.jboss.logging.Logger.Level.INFO; -import static org.jboss.logging.Logger.Level.TRACE; -import static org.jboss.logging.Logger.Level.WARN; -import org.hibernate.engine.SessionFactoryImplementor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; - -/** - * Interface defining messages that may be logged by the outer class - */ -@MessageLogger -interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Binding null to parameter: %d" ) - void bindingToParameter( int index ); - - @LogMessage( level = TRACE ) - @Message( value = "Binding '%d' to parameter: %d" ) - void bindingToParameter( int ordinal, - int index ); - - @LogMessage( level = TRACE ) - @Message( value = "Binding '%s' to parameter: %d" ) - void bindingToParameter( String name, - int index ); - - @LogMessage( level = TRACE ) - @Message( value = "Returning null as column %s" ) - void returningAsColumn( String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Returning '%d' as column %s" ) - void returningAsColumn( int ordinal, - String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Returning '%s' as column %s" ) - void returningAsColumn( String name, - String string ); - - @LogMessage( level = TRACE ) - @Message( value = "Scoping types to session factory %s" ) - void scopingTypesToSessionFactory( SessionFactoryImplementor factory ); - - @LogMessage( level = WARN ) - @Message( value = "Scoping types to session factory %s after already scoped %s" ) - void scopingTypesToSessionFactoryAfterAlreadyScoped( SessionFactoryImplementor factory, - SessionFactoryImplementor factory2 ); - - @LogMessage( level = INFO ) - @Message( value = "Could not bind value '%s' to parameter: %d; %s" ) - void unableToBindValueToParameter( String nullSafeToString, - int index, - String message ); - - @LogMessage( level = INFO ) - @Message( value = "Could not read column value from result set: %s; %s" ) - void unableToReadColumnValueFromResultSet( String name, - String message ); -} diff --git a/hibernate-core/src/main/java/org/hibernate/type/NullableType.java b/hibernate-core/src/main/java/org/hibernate/type/NullableType.java index 3de5a459d2..8fd8e88a3f 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/NullableType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/NullableType.java @@ -29,6 +29,7 @@ import java.sql.SQLException; import org.dom4j.Node; import org.hibernate.EntityMode; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.engine.Mapping; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; @@ -123,12 +124,12 @@ public abstract class NullableType extends AbstractType implements StringReprese throws HibernateException, SQLException { try { if ( value == null ) { - if (LOG.isTraceEnabled()) LOG.bindingToParameter(index); + if (LOG.isTraceEnabled()) LOG.trace("Binding null to parameter: " + index); st.setNull( index, sqlType() ); } else { - if (LOG.isTraceEnabled()) LOG.bindingToParameter(toString(value), index); + if (LOG.isTraceEnabled()) LOG.trace("Binding '" + toString(value) + "' to parameter: " + index); set( st, value, index ); } @@ -162,10 +163,10 @@ public abstract class NullableType extends AbstractType implements StringReprese try { Object value = get(rs, name); if ( value == null || rs.wasNull() ) { - if (LOG.isTraceEnabled()) LOG.returningAsColumn(name); + if (LOG.isTraceEnabled()) LOG.trace("Returning null as column " + name); return null; } - if (LOG.isTraceEnabled()) LOG.returningAsColumn(toString(value), name); + if (LOG.isTraceEnabled()) LOG.trace("Returning '" + toString(value) + "' as column " + name); return value; } catch ( RuntimeException re ) { diff --git a/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java b/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java index b2fd85342c..bc179673a7 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java @@ -27,6 +27,7 @@ import java.io.Serializable; import java.util.Comparator; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.classic.Lifecycle; import org.hibernate.classic.Validatable; @@ -64,7 +65,7 @@ public final class TypeFactory implements Serializable { public void injectSessionFactory(SessionFactoryImplementor factory) { if (this.factory != null) LOG.scopingTypesToSessionFactoryAfterAlreadyScoped(this.factory, factory); - else LOG.scopingTypesToSessionFactory(factory); + else LOG.trace("Scoping types to session factory " + factory); this.factory = factory; } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/JdbcTypeNameMapper.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/JdbcTypeNameMapper.java index 4b50cc9847..a2572b4916 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/JdbcTypeNameMapper.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/JdbcTypeNameMapper.java @@ -23,17 +23,13 @@ */ package org.hibernate.type.descriptor; -import static org.jboss.logging.Logger.Level.INFO; import java.lang.reflect.Field; import java.sql.Types; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.hibernate.HibernateException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; /** * TODO : javadoc @@ -79,17 +75,4 @@ public class JdbcTypeNameMapper { } return name; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = INFO ) - @Message( value = "java.sql.Types mapped the same code [%d] multiple times; was [%s]; now [%s]" ) - void JavaSqlTypesMappedSameCodeMultipleTimes( int code, - String old, - String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/DataHelper.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/DataHelper.java index c844309c22..14f8045843 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/DataHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/DataHelper.java @@ -23,19 +23,15 @@ */ package org.hibernate.type.descriptor.java; -import static org.jboss.logging.Logger.Level.INFO; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.type.descriptor.BinaryStream; import org.hibernate.util.ReflectHelper; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A help for dealing with BLOB and CLOB data @@ -253,24 +249,4 @@ public class DataHelper { public static InputStream subStream(InputStream inputStream, long start, int length) { return new BinaryStreamImpl( extractBytes( inputStream, start, length ) ); } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "IOException occurred closing input stream" ) - Object unableToCloseInputStream(); - - @Message( value = "IOException occurred closing output stream" ) - Object unableToCloseOutputStream(); - - @Message( value = "IOException occurred closing stream" ) - Object unableToCloseStream(); - - @LogMessage( level = INFO ) - @Message( value = "Could not locate 'java.sql.NClob' class; assuming JDBC 3" ) - void unableToLocateNClobClass(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicBinder.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicBinder.java index f75812a4d4..5cffb5fb23 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicBinder.java @@ -25,12 +25,11 @@ package org.hibernate.type.descriptor.sql; import java.sql.PreparedStatement; import java.sql.SQLException; +import org.hibernate.Logger; import org.hibernate.type.descriptor.JdbcTypeNameMapper; import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.MessageLogger; /** * Convenience base implementation of {@link ValueBinder} @@ -89,11 +88,4 @@ public abstract class BasicBinder implements ValueBinder { * @throws SQLException Indicates a problem binding to the prepared statement. */ protected abstract void doBind(PreparedStatement st, J value, int index, WrapperOptions options) throws SQLException; - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicExtractor.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicExtractor.java index f24fb0ef01..8911c625aa 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicExtractor.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/BasicExtractor.java @@ -23,16 +23,12 @@ */ package org.hibernate.type.descriptor.sql; -import static org.jboss.logging.Logger.Level.TRACE; import java.sql.ResultSet; import java.sql.SQLException; +import org.hibernate.Logger; import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * Convenience base implementation of {@link org.hibernate.type.descriptor.ValueExtractor} @@ -66,11 +62,11 @@ public abstract class BasicExtractor implements ValueExtractor { public J extract(ResultSet rs, String name, WrapperOptions options) throws SQLException { final J value = doExtract( rs, name, options ); if ( value == null || rs.wasNull() ) { - LOG.foundAsColumn( name ); + LOG.trace("Found [null] as column [" + name + "]"); return null; } else { - LOG.foundAsColumn(getJavaDescriptor().extractLoggableRepresentation(value), name); + LOG.trace("Found [" + getJavaDescriptor().extractLoggableRepresentation(value) + "] as column [" + name + "]"); return value; } } @@ -90,20 +86,4 @@ public abstract class BasicExtractor implements ValueExtractor { * @throws SQLException Indicates a problem access the result set */ protected abstract J doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException; - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Found [null] as column [%s]" ) - void foundAsColumn( String name ); - - @LogMessage( level = TRACE ) - @Message( value = "Found [%s] as column [%s]" ) - void foundAsColumn( String extractLoggableRepresentation, - String name ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java b/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java index 165e5932eb..3473bae698 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java @@ -32,10 +32,8 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import org.hibernate.HibernateException; +import org.hibernate.Logger; import org.hibernate.cfg.Environment; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** * A simple class to centralize logic needed to locate config files on the system. @@ -202,14 +200,4 @@ public final class ConfigHelper { return stream; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @Message( value = "Unable to locate config file: %s" ) - String unableToLocateConfigFile( String path ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java b/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java index 735b444c25..141fb6e341 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java @@ -24,15 +24,9 @@ */ package org.hibernate.util; -import static org.jboss.logging.Logger.Level.DEBUG; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.WARN; import java.io.InputStream; import java.io.Serializable; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; @@ -69,23 +63,23 @@ public class DTDEntityResolver implements EntityResolver, Serializable { public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; // returning null triggers default behavior if ( systemId != null ) { - LOG.tryingToResolveSystemId(systemId); + LOG.debug("Trying to resolve system-id [" + systemId + "]"); if ( systemId.startsWith( HIBERNATE_NAMESPACE ) ) { - LOG.recognizedHibernateNamespace(); + LOG.debug("Recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/"); source = resolveOnClassPath( publicId, systemId, HIBERNATE_NAMESPACE ); } else if ( systemId.startsWith( OLD_HIBERNATE_NAMESPACE ) ) { LOG.recognizedObsoleteHibernateNamespace(OLD_HIBERNATE_NAMESPACE, HIBERNATE_NAMESPACE); - LOG.attemptingToResolveSystemId(); + LOG.debug("Attempting to resolve on classpath under org/hibernate/"); source = resolveOnClassPath( publicId, systemId, OLD_HIBERNATE_NAMESPACE ); } else if ( systemId.startsWith( USER_NAMESPACE ) ) { - LOG.recognizedLocalNamespace(); + LOG.debug("Recognized local namespace; attempting to resolve on classpath"); String path = systemId.substring( USER_NAMESPACE.length() ); InputStream stream = resolveInLocalNamespace( path ); - if (stream == null) LOG.unableToLocateSystemId(systemId); + if (stream == null) LOG.debug("Unable to locate [" + systemId + "] on classpath"); else { - LOG.systemIdLocated(systemId); + LOG.debug("Located [" + systemId + "] in classpath"); source = new InputSource( stream ); source.setPublicId( publicId ); source.setSystemId( systemId ); @@ -100,11 +94,11 @@ public class DTDEntityResolver implements EntityResolver, Serializable { String path = "org/hibernate/" + systemId.substring( namespace.length() ); InputStream dtdStream = resolveInHibernateNamespace( path ); if ( dtdStream == null ) { - LOG.unableToLocateSystemId(systemId); + LOG.debug("Unable to locate [" + systemId + "] on classpath"); if (systemId.substring(namespace.length()).indexOf("2.0") > -1) LOG.usingOldDtd(); } else { - LOG.systemIdLocated(systemId); + LOG.debug("Located [" + systemId + "] in classpath"); source = new InputSource( dtdStream ); source.setPublicId( publicId ); source.setSystemId( systemId ); @@ -124,44 +118,4 @@ public class DTDEntityResolver implements EntityResolver, Serializable { return null; } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Attempting to resolve on classpath under org/hibernate/" ) - void attemptingToResolveSystemId(); - - @LogMessage( level = DEBUG ) - @Message( value = "Recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/" ) - void recognizedHibernateNamespace(); - - @LogMessage( level = DEBUG ) - @Message( value = "Recognized local namespace; attempting to resolve on classpath" ) - void recognizedLocalNamespace(); - - @LogMessage( level = WARN ) - @Message( value = "Recognized obsolete hibernate namespace %s. Use namespace %s instead. Refer to Hibernate 3.6 Migration Guide!" ) - void recognizedObsoleteHibernateNamespace( String oldHibernateNamespace, - String hibernateNamespace ); - - @LogMessage( level = DEBUG ) - @Message( value = "Located [%s] in classpath" ) - void systemIdLocated( String systemId ); - - @LogMessage( level = DEBUG ) - @Message( value = "Trying to resolve system-id [%s]" ) - void tryingToResolveSystemId( String systemId ); - - @LogMessage( level = DEBUG ) - @Message( value = "Unable to locate [%s] on classpath" ) - void unableToLocateSystemId( String systemId ); - - @LogMessage( level = ERROR ) - @Message( value = "Don't use old DTDs, read the Hibernate 3.x Migration Guide!" ) - void usingOldDtd(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java b/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java index f293640e7c..5ca644bf90 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java +++ b/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java @@ -24,16 +24,12 @@ package org.hibernate.util; import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; public final class JDBCExceptionReporter { @@ -237,26 +233,4 @@ public final class JDBCExceptionReporter { } } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Evicting %s" ) - void evicting( String infoString ); - - @LogMessage( level = WARN ) - @Message( value = "SQL Error: %d, SQLState: %s" ) - void sqlError( int errorCode, - String sqlState ); - - @Message( value = "Could not clear warnings" ) - Object unableToClearWarnings(); - - @Message( value = "Could not log warnings" ) - Object unableToLogWarnings(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java b/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java index dd4b925e4f..ed2906b45c 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java @@ -25,7 +25,6 @@ package org.hibernate.util; import static org.hibernate.LogUtil.TMP_LOG; -import static org.jboss.logging.Logger.Level.TRACE; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -36,11 +35,8 @@ import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; import org.hibernate.Hibernate; +import org.hibernate.Logger; import org.hibernate.type.SerializationException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; /** *

Assists with the serialization process and performs additional functionality based @@ -91,7 +87,7 @@ public final class SerializationHelper { * @throws SerializationException (runtime) if the serialization fails */ public static Object clone(Serializable object) throws SerializationException { - LOG.startingCloneThroughSerialization(); + LOG.trace("Starting clone through serialization"); if ( object == null ) { return null; } @@ -123,8 +119,8 @@ public final class SerializationHelper { } if (TMP_LOG.isTraceEnabled()) { - if (Hibernate.isInitialized(obj)) LOG.startingSerializationOfObject(obj); - else LOG.startingSerializationOfUninitializedProxy(); + if (Hibernate.isInitialized(obj)) LOG.trace("Starting serialization of object [" + obj + "]"); + else LOG.trace("Starting serialization of [uninitialized proxy]"); } ObjectOutputStream out = null; @@ -230,7 +226,7 @@ public final class SerializationHelper { throw new IllegalArgumentException( "The InputStream must not be null" ); } - LOG.startingDeserializationOfObject(); + LOG.trace("Starting deserialization of object"); try { CustomObjectInputStream in = new CustomObjectInputStream( @@ -336,13 +332,13 @@ public final class SerializationHelper { @Override protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { String className = v.getName(); - LOG.attemptingToLocateClass(className); + LOG.trace("Attempting to locate class [" + className + "]"); try { return Class.forName( className, false, loader1 ); } catch ( ClassNotFoundException e ) { - LOG.unableToLocateClass(); + LOG.trace("Unable to locate class using given classloader"); } if ( different( loader1, loader2 ) ) { @@ -350,7 +346,7 @@ public final class SerializationHelper { return Class.forName( className, false, loader2 ); } catch ( ClassNotFoundException e ) { - LOG.unableToLocateClass(); + LOG.trace("Unable to locate class using given classloader"); } } @@ -359,7 +355,7 @@ public final class SerializationHelper { return Class.forName( className, false, loader3 ); } catch ( ClassNotFoundException e ) { - LOG.unableToLocateClass(); + LOG.trace("Unable to locate class using given classloader"); } } @@ -373,35 +369,4 @@ public final class SerializationHelper { return !one.equals(other); } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = TRACE ) - @Message( value = "Attempting to locate class [%s]" ) - void attemptingToLocateClass( String className ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting deserialization of object" ) - void startingDeserializationOfObject(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting clone through serialization" ) - void startingCloneThroughSerialization(); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of object [%s]" ) - void startingSerializationOfObject( Serializable obj ); - - @LogMessage( level = TRACE ) - @Message( value = "Starting serialization of [uninitialized proxy]" ) - void startingSerializationOfUninitializedProxy(); - - @LogMessage( level = TRACE ) - @Message( value = "Unable to locate class using given classloader" ) - void unableToLocateClass(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java b/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java index fa43600911..fe5e015ec5 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java @@ -23,8 +23,6 @@ */ package org.hibernate.util; -import static org.jboss.logging.Logger.Level.ERROR; -import static org.jboss.logging.Logger.Level.WARN; import java.util.List; import org.dom4j.DocumentFactory; import org.dom4j.Element; @@ -32,10 +30,7 @@ import org.dom4j.io.DOMReader; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; @@ -121,23 +116,4 @@ public final class XMLHelper { } } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = ERROR ) - @Message( value = "Error parsing XML: %s(%d) %s" ) - void parsingXmlError( String file, - int lineNumber, - String message ); - - @LogMessage( level = WARN ) - @Message( value = "Warning parsing XML: %s(%d) %s" ) - void parsingXmlWarning( String file, - int lineNumber, - String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/xml/ErrorLogger.java b/hibernate-core/src/main/java/org/hibernate/util/xml/ErrorLogger.java index e95a6bb888..f1a01d7254 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/xml/ErrorLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/util/xml/ErrorLogger.java @@ -23,12 +23,8 @@ */ package org.hibernate.util.xml; -import static org.jboss.logging.Logger.Level.ERROR; import java.io.Serializable; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; @@ -79,21 +75,4 @@ public class ErrorLogger implements ErrorHandler, Serializable { public void reset() { error = null; } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = ERROR ) - @Message( value = "Error parsing XML (%d) : %s" ) - void parsingXmlError( int lineNumber, - String message ); - - @LogMessage( level = ERROR ) - @Message( value = "Warning parsing XML (%d) : %s" ) - void parsingXmlWarning( int lineNumber, - String message ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/util/xml/MappingReader.java b/hibernate-core/src/main/java/org/hibernate/util/xml/MappingReader.java index cb8efd9492..eebf87d6ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/xml/MappingReader.java +++ b/hibernate-core/src/main/java/org/hibernate/util/xml/MappingReader.java @@ -23,15 +23,11 @@ */ package org.hibernate.util.xml; -import static org.jboss.logging.Logger.Level.DEBUG; import java.io.StringReader; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.hibernate.InvalidMappingException; -import org.jboss.logging.BasicLogger; -import org.jboss.logging.LogMessage; -import org.jboss.logging.Message; -import org.jboss.logging.MessageLogger; +import org.hibernate.Logger; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -82,7 +78,7 @@ public class MappingReader { return new XmlDocumentImpl( document, origin.getType(), origin.getName() ); } catch ( Exception orm2Problem ) { - LOG.problemParsingXmlUsingOrm2Xsd(orm2Problem.getMessage()); + LOG.debug("Problem parsing XML using orm 2 xsd : " + orm2Problem.getMessage()); failure = orm2Problem; errorHandler.reset(); @@ -97,7 +93,7 @@ public class MappingReader { return new XmlDocumentImpl( document, origin.getType(), origin.getName() ); } catch ( Exception orm1Problem ) { - LOG.problemParsingXmlUsingOrm1Xsd(orm1Problem.getMessage()); + LOG.debug("Problem parsing XML using orm 1 xsd : " + orm1Problem.getMessage()); } } } @@ -257,19 +253,4 @@ public class MappingReader { // } // // } - - /** - * Interface defining messages that may be logged by the outer class - */ - @MessageLogger - interface Logger extends BasicLogger { - - @LogMessage( level = DEBUG ) - @Message( value = "Problem parsing XML using orm 1 xsd : %s" ) - void problemParsingXmlUsingOrm1Xsd( String message ); - - @LogMessage( level = DEBUG ) - @Message( value = "Problem parsing XML using orm 2 xsd : %s" ) - void problemParsingXmlUsingOrm2Xsd( String message ); - } } diff --git a/hibernate-core/src/test/java/org/hibernate/Logger.java b/hibernate-core/src/test/java/org/hibernate/Logger.java deleted file mode 100644 index 995e7676b1..0000000000 --- a/hibernate-core/src/test/java/org/hibernate/Logger.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * - * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. - * - * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. - */ -package org.hibernate; - -import org.jboss.logging.BasicLogger; - -/** - * - */ -public interface Logger extends BasicLogger { - -} 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 f2b9253bc3..4a368d3832 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 @@ -16,8 +16,8 @@ import org.hibernate.test.common.ServiceRegistryHolder; * */ public class BackquoteTest extends TestCase { - - private ServiceRegistryHolder serviceRegistryHolder; + + private ServiceRegistryHolder serviceRegistryHolder; @Override protected void setUp() { 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 29ee0626e8..9b67d89bca 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 @@ -25,9 +25,9 @@ */ package org.hibernate.test.annotations.fetchprofile; +import static org.hibernate.aTestLogger.LOG; import java.io.InputStream; import junit.framework.TestCase; -import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; @@ -41,15 +41,15 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public class FetchProfileTest extends TestCase { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private ServiceRegistryHolder serviceRegistryHolder; - protected void setUp() { + @Override + protected void setUp() { serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); } - protected void tearDown() { + @Override + protected void tearDown() { if ( serviceRegistryHolder != null ) { serviceRegistryHolder.destroy(); } 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 6e2c930bcb..81c3bbc99c 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 @@ -1,6 +1,7 @@ // $Id$ package org.hibernate.test.annotations.fkcircularity; +import static org.hibernate.aTestLogger.LOG; import java.io.PrintWriter; import java.io.StringWriter; import junit.framework.TestCase; @@ -17,8 +18,6 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public class FkCircularityTest extends TestCase { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private ServiceRegistryHolder serviceRegistryHolder; @Override diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java index eca5a2b91c..0326db68d6 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.id; +import static org.hibernate.aTestLogger.LOG; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.test.annotations.TestCase; 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 881ca0be39..9e23f5c9f4 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 @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.id; +import static org.hibernate.aTestLogger.LOG; import java.io.PrintWriter; import java.io.StringWriter; import org.hibernate.cfg.AnnotationConfiguration; diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java index 3926cb3dda..2f713e70a6 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.id.sequences; +import static org.hibernate.aTestLogger.LOG; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.test.annotations.TestCase; 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 a0cc86e836..3c19bdf673 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 @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.id.sequences; +import static org.hibernate.aTestLogger.LOG; import java.io.PrintWriter; import java.io.StringWriter; import org.hibernate.cfg.AnnotationConfiguration; 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 559bb6fba0..d0bbb4082a 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 @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.immutable; +import static org.hibernate.aTestLogger.LOG; import java.util.ArrayList; import java.util.List; import org.hibernate.AnnotationException; 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 c3d06684b8..349cde6811 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 @@ -1,6 +1,7 @@ // $Id$ package org.hibernate.test.annotations.namingstrategy; +import static org.hibernate.aTestLogger.LOG; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; @@ -19,8 +20,6 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public class NamingStrategyTest extends TestCase { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private ServiceRegistryHolder serviceRegistryHolder; @Override diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java index 624d0d05b5..c36d9190f0 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.test.annotations.naturalid; +import static org.hibernate.aTestLogger.LOG; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; 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 40562772ff..998fa8950f 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 @@ -1,6 +1,7 @@ //$Id: A320.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $ package org.hibernate.test.annotations.onetoone.primarykey; +import static org.hibernate.aTestLogger.LOG; import junit.framework.TestCase; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; @@ -15,8 +16,6 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public class NullablePrimaryKeyTest extends TestCase { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - public void testGeneratedSql() { ServiceRegistryHolder serviceRegistryHolder = null; @@ -41,6 +40,6 @@ public class NullablePrimaryKeyTest extends TestCase { if ( serviceRegistryHolder != null ) { serviceRegistryHolder.destroy(); } - } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java index 1e0d3018ae..6f41876647 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java @@ -1,9 +1,9 @@ //$Id$ package org.hibernate.test.annotations.reflection; +import static org.hibernate.aTestLogger.LOG; import javax.persistence.PostPersist; import javax.persistence.PrePersist; -import org.hibernate.Logger; /** @@ -11,8 +11,6 @@ import org.hibernate.Logger; */ public class LogListener { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - @PrePersist @PostPersist public void log(Object entity) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java index 3cbc660a5a..b0315e33b1 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java @@ -1,17 +1,15 @@ //$Id$ package org.hibernate.test.annotations.reflection; +import static org.hibernate.aTestLogger.LOG; import javax.persistence.PostPersist; import javax.persistence.PrePersist; -import org.hibernate.Logger; /** * @author Emmanuel Bernard */ public class OtherLogListener { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - @PrePersist @PostPersist public void log(Object entity) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java b/hibernate-core/src/test/java/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java index e5b28e094a..ff13e40069 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java @@ -23,6 +23,7 @@ */ package org.hibernate.test.dialect.functional.cache; +import static org.hibernate.aTestLogger.LOG; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; @@ -34,7 +35,6 @@ import java.util.List; import java.util.Map; import junit.framework.Test; import org.hibernate.LockMode; -import org.hibernate.Logger; import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Transaction; @@ -63,8 +63,6 @@ import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; */ public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTestCase { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - public SQLFunctionsInterSystemsTest(String name) { super(name); } @@ -82,7 +80,8 @@ public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTest return new FunctionalTestClassTestSuite( SQLFunctionsInterSystemsTest.class ); } - public boolean appliesTo(Dialect dialect) { + @Override + public boolean appliesTo(Dialect dialect) { // all these test case apply only to testing InterSystems' CacheSQL dialect return dialect instanceof Cache71Dialect; } diff --git a/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java b/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java index bd47ca90bd..5d84a73292 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java @@ -1,6 +1,7 @@ // $Id: DynamicFilterTest.java 11398 2007-04-10 14:54:07Z steve.ebersole@jboss.com $ package org.hibernate.test.filter; +import static org.hibernate.aTestLogger.LOG; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java index 1e1e1cd276..d62c866eae 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java @@ -1,6 +1,7 @@ // $Id: ASTParserLoadingTest.java 11373 2007-03-29 19:09:07Z steve.ebersole@jboss.com $ package org.hibernate.test.hql; +import static org.hibernate.aTestLogger.LOG; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/BulkManipulationTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/BulkManipulationTest.java index e015940f03..452a2da7e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/BulkManipulationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/BulkManipulationTest.java @@ -1,6 +1,7 @@ // $Id: BulkManipulationTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ package org.hibernate.test.hql; +import static org.hibernate.aTestLogger.LOG; import java.util.ArrayList; import java.util.Date; import java.util.List; diff --git a/hibernate-core/src/test/java/org/hibernate/test/jdbc/proxies/AggressiveReleaseTest.java b/hibernate-core/src/test/java/org/hibernate/test/jdbc/proxies/AggressiveReleaseTest.java index e32122b4ed..94a3676cad 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/jdbc/proxies/AggressiveReleaseTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/jdbc/proxies/AggressiveReleaseTest.java @@ -23,18 +23,15 @@ */ package org.hibernate.test.jdbc.proxies; +import static org.hibernate.aTestLogger.LOG; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.ConnectionReleaseMode; import org.hibernate.engine.jdbc.internal.LogicalConnectionImpl; -import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.internal.proxy.ProxyBuilder; +import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.test.common.BasicTestingJdbcServiceImpl; import org.hibernate.testing.junit.UnitTestCase; @@ -45,7 +42,6 @@ import org.hibernate.testing.junit.UnitTestCase; */ public class AggressiveReleaseTest extends UnitTestCase { - private static final Logger log = LoggerFactory.getLogger( AggressiveReleaseTest.class ); private BasicTestingJdbcServiceImpl services = new BasicTestingJdbcServiceImpl(); private static class ConnectionCounter implements ConnectionObserver { @@ -68,7 +64,8 @@ public class AggressiveReleaseTest extends UnitTestCase { super( string ); } - public void setUp() throws SQLException { + @Override + public void setUp() throws SQLException { services.prepare( true ); Connection connection = null; @@ -85,7 +82,7 @@ public class AggressiveReleaseTest extends UnitTestCase { stmnt.close(); } catch ( SQLException ignore ) { - log.warn( "could not close statement used to set up schema", ignore ); + LOG.warn("could not close statement used to set up schema", ignore); } } if ( connection != null ) { @@ -93,13 +90,14 @@ public class AggressiveReleaseTest extends UnitTestCase { connection.close(); } catch ( SQLException ignore ) { - log.warn( "could not close connection used to set up schema", ignore ); + LOG.warn("could not close connection used to set up schema", ignore); } } } } - public void tearDown() throws SQLException { + @Override + public void tearDown() throws SQLException { Connection connection = null; Statement stmnt = null; try { @@ -113,7 +111,7 @@ public class AggressiveReleaseTest extends UnitTestCase { stmnt.close(); } catch ( SQLException ignore ) { - log.warn( "could not close statement used to set up schema", ignore ); + LOG.warn("could not close statement used to set up schema", ignore); } } if ( connection != null ) { @@ -121,7 +119,7 @@ public class AggressiveReleaseTest extends UnitTestCase { connection.close(); } catch ( SQLException ignore ) { - log.warn( "could not close connection used to set up schema", ignore ); + LOG.warn("could not close connection used to set up schema", ignore); } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/jpa/cascade/CascadeTest.java b/hibernate-core/src/test/java/org/hibernate/test/jpa/cascade/CascadeTest.java index 1bc98d04b0..797e7fab11 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/jpa/cascade/CascadeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/jpa/cascade/CascadeTest.java @@ -1,5 +1,6 @@ package org.hibernate.test.jpa.cascade; +import static org.hibernate.aTestLogger.LOG; import junit.framework.Test; import org.hibernate.Session; import org.hibernate.TransientObjectException; 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 b530c3f132..7b7c38da49 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 @@ -1,6 +1,7 @@ //$Id: FooBarTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ package org.hibernate.test.legacy; +import static org.hibernate.aTestLogger.LOG; import java.io.Serializable; import java.sql.Connection; import java.sql.Time; diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java index 5b542bca25..7ac417fcd6 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java @@ -23,6 +23,7 @@ */ package org.hibernate.test.legacy; +import static org.hibernate.aTestLogger.LOG; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; diff --git a/hibernate-core/src/test/java/org/hibernate/test/stateless/fetching/StatelessSessionFetchingTest.java b/hibernate-core/src/test/java/org/hibernate/test/stateless/fetching/StatelessSessionFetchingTest.java index 99dec7831b..aa453919f9 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/stateless/fetching/StatelessSessionFetchingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/stateless/fetching/StatelessSessionFetchingTest.java @@ -21,6 +21,7 @@ */ package org.hibernate.test.stateless.fetching; +import static org.hibernate.aTestLogger.LOG; import java.util.Date; import junit.framework.Test; import org.hibernate.Hibernate; diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java deleted file mode 100644 index e1cca6fad7..0000000000 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java +++ /dev/null @@ -1,36 +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.testing.junit; - -import org.hibernate.Logger; - -/** - * Well-known-location lookup for the test-skip log... - * - * @author Steve Ebersole - */ -public class SkipLog { - - public static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); -} 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 c99ab950ab..51f7100ea8 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 @@ -23,6 +23,7 @@ */ package org.hibernate.testing.junit; +import static org.hibernate.aTestLogger.LOG; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; @@ -31,8 +32,6 @@ import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -import org.hibernate.Logger; - import org.hibernate.cfg.Environment; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; @@ -47,8 +46,6 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public abstract class UnitTestCase extends junit.framework.TestCase { - public static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private ServiceRegistryHolder serviceRegistryHolder; public UnitTestCase(String string) { @@ -146,7 +143,7 @@ public abstract class UnitTestCase extends junit.framework.TestCase { } protected void reportSkip(String reason, String testDescription) { - SkipLog.LOG.warn( "*** skipping [" + fullTestName() + "] - " + testDescription + " : " + reason, new Exception() ); + LOG.warn("*** skipping [" + fullTestName() + "] - " + testDescription + " : " + reason, new Exception()); } // testsuite utitities --------------------------------------------------- diff --git a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/DatabaseSpecificFunctionalTestCase.java b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/DatabaseSpecificFunctionalTestCase.java index 0edd38afc3..bd7240cd81 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/DatabaseSpecificFunctionalTestCase.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/functional/DatabaseSpecificFunctionalTestCase.java @@ -23,7 +23,7 @@ */ package org.hibernate.testing.junit.functional; -import org.hibernate.testing.junit.SkipLog; +import static org.hibernate.aTestLogger.LOG; /** * {@inheritDoc} @@ -35,7 +35,8 @@ public abstract class DatabaseSpecificFunctionalTestCase extends FunctionalTestC super( string ); } - protected void runTest() throws Throwable { + @Override + protected void runTest() throws Throwable { // Note: this protection comes into play when running // tests individually. The suite as a whole is already // "protected" by the fact that these tests are actually @@ -44,7 +45,8 @@ public abstract class DatabaseSpecificFunctionalTestCase extends FunctionalTestC super.runTest(); } else { - SkipLog.LOG.warn( "skipping database-specific test [" + fullTestName() + "] for dialect [" + getDialect().getClass().getName() + "]" ); + LOG.warn("skipping database-specific test [" + fullTestName() + "] for dialect [" + getDialect().getClass().getName() + + "]"); } } } 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 ed3191e34b..bb229c07bf 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 static org.hibernate.aTestLogger.LOG; import java.sql.Connection; import java.util.Collections; import java.util.HashMap; 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 36c6eca732..67a917d420 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,7 @@ */ package org.hibernate.testing.junit.functional; +import static org.hibernate.aTestLogger.LOG; import java.util.Collections; import java.util.Map; import junit.framework.Test; @@ -39,8 +40,6 @@ import junit.framework.TestSuite; */ public class FunctionalTestClassTestSuite extends TestSuite { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private ExecutionEnvironment.Settings settings; private ExecutionEnvironment environment; private Throwable environmentSetupError; 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 a0cf7e17c2..647780152f 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 @@ -26,6 +26,7 @@ package org.hibernate.testing.junit.functional.annotations; +import static org.hibernate.aTestLogger.LOG; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -33,7 +34,6 @@ import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.SQLException; import junit.framework.TestCase; -import org.hibernate.Logger; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; @@ -46,7 +46,6 @@ import org.hibernate.testing.junit.FailureExpected; import org.hibernate.testing.junit.RequiresDialect; import org.hibernate.testing.junit.RequiresDialectFeature; import org.hibernate.testing.junit.SkipForDialect; -import org.hibernate.testing.junit.SkipLog; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.util.StringHelper; @@ -58,8 +57,6 @@ import org.hibernate.util.StringHelper; */ public abstract class HibernateTestCase extends TestCase { - public static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - protected static Configuration cfg; private static Class lastTestClass; private ServiceRegistryHolder serviceRegistryHolder; @@ -124,7 +121,7 @@ public abstract class HibernateTestCase extends TestCase { builder.append( " (" ) .append( failureExpected.jiraKey() ) .append( ")" ); - SkipLog.LOG.warn( builder.toString(), t ); + LOG.warn(builder.toString(), t); } else { throw t; @@ -334,7 +331,7 @@ public abstract class HibernateTestCase extends TestCase { builder.append( testDescription ); builder.append( " : " ); builder.append( reason ); - SkipLog.LOG.warn( builder.toString() ); + LOG.warn(builder.toString()); } public class RollbackWork implements Work { diff --git a/hibernate-core/src/test/java/org/hibernate/testing/tm/SimpleJtaTransactionImpl.java b/hibernate-core/src/test/java/org/hibernate/testing/tm/SimpleJtaTransactionImpl.java index d395874081..9ed90affed 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/tm/SimpleJtaTransactionImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/tm/SimpleJtaTransactionImpl.java @@ -23,6 +23,7 @@ */ package org.hibernate.testing.tm; +import static org.hibernate.aTestLogger.LOG; import java.sql.Connection; import java.sql.SQLException; import java.util.LinkedList; @@ -34,7 +35,6 @@ import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAResource; -import org.hibernate.Logger; /** * SimpleJtaTransactionImpl implementation @@ -43,8 +43,6 @@ import org.hibernate.Logger; */ public class SimpleJtaTransactionImpl implements Transaction { - private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); - private int status; private LinkedList synchronizations; private Connection connection; // the only resource we care about is jdbc connection diff --git a/hibernate-ehcache/hibernate-ehcache.gradle b/hibernate-ehcache/hibernate-ehcache.gradle index 93a71d998f..2dc20638b1 100644 --- a/hibernate-ehcache/hibernate-ehcache.gradle +++ b/hibernate-ehcache/hibernate-ehcache.gradle @@ -1,4 +1,4 @@ -apply plugin: 'java' + apply plugin: 'java' dependencies { compile( project( ':hibernate-core' ) ) diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.java index b638dab3c6..c926e5f5da 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCache.java @@ -23,14 +23,11 @@ */ package org.hibernate.cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; /** * EHCache plugin for Hibernate @@ -45,7 +42,9 @@ import java.util.Map; * @author Emmanuel Bernard */ public class EhCache implements Cache { - private static final Logger log = LoggerFactory.getLogger( EhCache.class ); + + private static final EhCacheLogger LOG = org.jboss.logging.Logger.getMessageLogger(EhCacheLogger.class, + EhCacheLogger.class.getPackage().getName()); private static final int SIXTY_THOUSAND_MS = 60000; @@ -70,24 +69,14 @@ public class EhCache implements Cache { */ public Object get(Object key) throws CacheException { try { - if ( log.isDebugEnabled() ) { - log.debug( "key: " + key ); - } - if ( key == null ) { + LOG.debug("Key: " + key); + if (key == null) return null; + Element element = cache.get(key); + if (element == null) { + LOG.debug("Element for " + key + " is null"); return null; } - else { - Element element = cache.get( key ); - if ( element == null ) { - if ( log.isDebugEnabled() ) { - log.debug( "Element for " + key + " is null" ); - } - return null; - } - else { - return element.getObjectValue(); - } - } + return element.getObjectValue(); } catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); @@ -274,7 +263,8 @@ public class EhCache implements Cache { } } - public String toString() { + @Override + public String toString() { return "EHCache(" + getRegionName() + ')'; } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheProvider.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheProvider.java index 5821364f1e..68def1a10e 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheProvider.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/EhCacheProvider.java @@ -23,22 +23,19 @@ */ package org.hibernate.cache; +import java.net.URL; +import java.util.Properties; import net.sf.ehcache.CacheManager; import org.hibernate.cfg.Environment; import org.hibernate.util.ConfigHelper; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URL; -import java.util.Properties; /** * Cache Provider plugin for Hibernate * * Use hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider * in Hibernate 3.x or later - * + * * Taken from EhCache 0.9 distribution * @author Greg Luck * @author Emmanuel Bernard @@ -69,7 +66,8 @@ import java.util.Properties; */ public class EhCacheProvider implements CacheProvider { - private static final Logger log = LoggerFactory.getLogger(EhCacheProvider.class); + private static final EhCacheLogger LOG = org.jboss.logging.Logger.getMessageLogger(EhCacheLogger.class, + EhCacheLogger.class.getPackage().getName()); private CacheManager manager; @@ -90,10 +88,10 @@ public class EhCacheProvider implements CacheProvider { try { net.sf.ehcache.Cache cache = manager.getCache(name); if (cache == null) { - log.warn("Could not find configuration [" + name + "]; using defaults."); + LOG.unableToFindConfiguration(name); manager.addCache(name); cache = manager.getCache(name); - log.debug("started EHCache region: " + name); + LOG.debug("Started EHCache region: " + name); } return new EhCache(cache); } @@ -117,9 +115,7 @@ public class EhCacheProvider implements CacheProvider { */ public void start(Properties properties) throws CacheException { if (manager != null) { - log.warn("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " + - " between repeated calls to buildSessionFactory. Using previously created EhCacheProvider." + - " If this behaviour is required, consider using net.sf.ehcache.hibernate.SingletonEhCacheProvider."); + LOG.attemptToRestartAlreadyStartedEhCacheProvider(); return; } try { @@ -141,18 +137,14 @@ public class EhCacheProvider implements CacheProvider { throw new CacheException("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " + " between repeated calls to buildSessionFactory. Consider using net.sf.ehcache.hibernate.SingletonEhCacheProvider." , e ); - } else { - throw e; } + throw e; } } private URL loadResource(String configurationResourceName) { URL url = ConfigHelper.locateConfig( configurationResourceName ); - if (log.isDebugEnabled()) { - log.debug("Creating EhCacheProvider from a specified resource: " - + configurationResourceName + " Resolved to URL: " + url); - } + LOG.debug("Creating EhCacheProvider from a specified resource: " + configurationResourceName + " Resolved to URL: " + url); return url; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java index aca398a737..f566d9f3d8 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java @@ -60,13 +60,8 @@ import javax.persistence.criteria.Selection; import javax.persistence.metamodel.Metamodel; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.transaction.Status; -import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.TransactionManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.CacheMode; import org.hibernate.FlushMode; @@ -117,7 +112,9 @@ import org.hibernate.util.ReflectHelper; */ @SuppressWarnings("unchecked") public abstract class AbstractEntityManagerImpl implements HibernateEntityManagerImplementor, Serializable { - private static final Logger log = LoggerFactory.getLogger( AbstractEntityManagerImpl.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private static final List entityManagerSpecificProperties = new ArrayList(); @@ -211,7 +208,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage options.setScope( true ); } else if ( lockScope instanceof PessimisticLockScope ) { - boolean extended = PessimisticLockScope.EXTENDED.equals( ( PessimisticLockScope ) lockScope ); + boolean extended = PessimisticLockScope.EXTENDED.equals( lockScope ); options.setScope( extended ); } else if ( lockScope != null ) { @@ -427,7 +424,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage } public List> getElements() { - return ( List> ) tupleElements; + return tupleElements; } } } @@ -777,10 +774,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage if ( entityManagerSpecificProperties.contains( s ) ) { properties.put( s, o ); applyProperties(); - } - else { - log.debug( "Trying to set a property which is not supported on entity manager level" ); - } + } else LOG.debug("Trying to set a property which is not supported on entity manager level"); } public Map getProperties() { @@ -945,7 +939,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage } protected void markAsRollback() { - log.debug( "mark transaction for rollback" ); + LOG.debug("Mark transaction for rollback"); if ( tx.isActive() ) { tx.setRollbackOnly(); } @@ -991,7 +985,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage getSession().isOpen(); //for sync if ( transactionType == PersistenceUnitTransactionType.JTA ) { try { - log.debug( "Looking for a JTA transaction to join" ); + LOG.debug("Looking for a JTA transaction to join"); final Session session = getSession(); final Transaction transaction = session.getTransaction(); if ( transaction != null && transaction instanceof JoinableCMTTransaction ) { @@ -999,14 +993,14 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage final JoinableCMTTransaction joinableCMTTransaction = ( JoinableCMTTransaction ) transaction; if ( joinableCMTTransaction.getStatus() == JoinableCMTTransaction.JoinStatus.JOINED ) { - log.debug( "Transaction already joined" ); + LOG.debug("Transaction already joined"); return; //no-op } joinableCMTTransaction.markForJoined(); session.isOpen(); //register to the Tx if ( joinableCMTTransaction.getStatus() == JoinableCMTTransaction.JoinStatus.NOT_JOINED ) { if ( ignoreNotJoining ) { - log.debug( "No JTA transaction found" ); + LOG.debug("No JTA transaction found"); return; } else { @@ -1020,7 +1014,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage } //flush before completion and //register clear on rollback - log.trace( "Adding flush() and close() synchronization" ); + LOG.trace("Adding flush() and close() synchronization"); CallbackCoordinator callbackCoordinator = ( (SessionImplementor ) getSession() ).getJDBCContext().getJtaSynchronizationCallbackCoordinator(); if ( callbackCoordinator == null ) { throw new AssertionFailure( "Expecting CallbackCoordinator to be non-null" ); @@ -1029,9 +1023,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage new BeforeCompletionManagedFlushChecker() { public boolean shouldDoManagedFlush(TransactionFactory.Context ctx, javax.transaction.Transaction jtaTransaction) throws SystemException { - if ( transaction == null ) { - log.warn( "Transaction not available on beforeCompletion: assuming valid" ); - } + if (transaction == null) LOG.transactionNotAvailableOnBeforeCompletion(); return !ctx.isFlushModeNever() && ( jtaTransaction == null || !JTAHelper.isRollback( jtaTransaction.getStatus() ) ); } @@ -1075,18 +1067,13 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage ); } else { - log.warn( "Cannot join transaction: do not override {}", Environment.TRANSACTION_STRATEGY ); + LOG.unableToJoinTransaction(Environment.TRANSACTION_STRATEGY); } } catch ( HibernateException he ) { throw convert( he ); } - } - else { - if ( !ignoreNotJoining ) { - log.warn( "Calling joinTransaction() on a non JTA EntityManager" ); - } - } + } else if (!ignoreNotJoining) LOG.callingJoinTransactionOnNonJtaEntityManager(); } /** @@ -1127,7 +1114,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage } catch ( Exception ne ) { //we do not want the subsequent exception to swallow the original one - log.error( "Unable to mark for rollback on PersistenceException: ", ne ); + LOG.error(LOG.unableToMarkForRollbackOnPersistenceException(), ne); } } @@ -1206,7 +1193,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage } catch ( Exception ne ) { //we do not want the subsequent exception to swallow the original one - log.error( "Unable to mark for rollback on TransientObjectException: ", ne ); + LOG.error(LOG.unableToMarkForRollbackOnTransientObjectException(), ne); } return new IllegalStateException( e ); //Spec 3.2.3 Synchronization rules } @@ -1266,7 +1253,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage else if ( e instanceof org.hibernate.PessimisticLockException ) { org.hibernate.PessimisticLockException ple = ( org.hibernate.PessimisticLockException ) e; if ( lockOptions != null && lockOptions.getTimeOut() > -1 ) { - // assume lock timeout occurred if a timeout or NO WAIT was specified + // assume lock timeout occurred if a timeout or NO WAIT was specified pe = new LockTimeoutException( ple.getMessage(), ple, ple.getEntity() ); } else { diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractQueryImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractQueryImpl.java index 3c9c383230..9308bd3ea8 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractQueryImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/AbstractQueryImpl.java @@ -23,6 +23,15 @@ */ package org.hibernate.ejb; +import static org.hibernate.ejb.QueryHints.HINT_CACHEABLE; +import static org.hibernate.ejb.QueryHints.HINT_CACHE_MODE; +import static org.hibernate.ejb.QueryHints.HINT_CACHE_REGION; +import static org.hibernate.ejb.QueryHints.HINT_COMMENT; +import static org.hibernate.ejb.QueryHints.HINT_FETCH_SIZE; +import static org.hibernate.ejb.QueryHints.HINT_FLUSH_MODE; +import static org.hibernate.ejb.QueryHints.HINT_READONLY; +import static org.hibernate.ejb.QueryHints.HINT_TIMEOUT; +import static org.hibernate.ejb.QueryHints.SPEC_HINT_TIMEOUT; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -33,25 +42,11 @@ import javax.persistence.FlushModeType; import javax.persistence.Parameter; import javax.persistence.TransactionRequiredException; import javax.persistence.TypedQuery; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.TypeMismatchException; -import static org.hibernate.ejb.QueryHints.HINT_CACHEABLE; -import static org.hibernate.ejb.QueryHints.HINT_CACHE_MODE; -import static org.hibernate.ejb.QueryHints.HINT_CACHE_REGION; -import static org.hibernate.ejb.QueryHints.HINT_COMMENT; -import static org.hibernate.ejb.QueryHints.HINT_FETCH_SIZE; -import static org.hibernate.ejb.QueryHints.HINT_FLUSH_MODE; -import static org.hibernate.ejb.QueryHints.HINT_READONLY; -import static org.hibernate.ejb.QueryHints.HINT_TIMEOUT; -import static org.hibernate.ejb.QueryHints.SPEC_HINT_TIMEOUT; - import org.hibernate.ejb.util.CacheModeHelper; import org.hibernate.ejb.util.ConfigurationHelper; import org.hibernate.ejb.util.LockModeTypeHelper; @@ -67,7 +62,9 @@ import org.hibernate.hql.QueryExecutionRequestException; * @author Steve Ebersole */ public abstract class AbstractQueryImpl implements TypedQuery { - private static final Logger log = LoggerFactory.getLogger( AbstractQueryImpl.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private final HibernateEntityManagerImplementor entityManager; @@ -207,7 +204,7 @@ public abstract class AbstractQueryImpl implements TypedQuery { } else if ( SPEC_HINT_TIMEOUT.equals( hintName ) ) { // convert milliseconds to seconds - int timeout = (int)Math.round(ConfigurationHelper.getInteger( value ).doubleValue() / 1000.0 ); + int timeout = (int)Math.round(ConfigurationHelper.getInteger( value ).doubleValue() / 1000.0 ); applyTimeout( new Integer(timeout) ); } else if ( HINT_COMMENT.equals( hintName ) ) { @@ -272,14 +269,14 @@ public abstract class AbstractQueryImpl implements TypedQuery { applyAliasSpecificLockMode( alias, lockMode ); } catch ( Exception e ) { - log.info( "Unable to determine lock mode value : {} -> {}", hintName, value ); + LOG.unableToDetermineLockModeValue(hintName, value); skipped = true; } } } else { skipped = true; - log.info( "Ignoring unrecognized query hint [" + hintName + "]" ); + LOG.ignoringUnrecognizedQueryHint(hintName); } } catch ( ClassCastException e ) { 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 ca53cc4ec3..f42e9f0093 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java @@ -57,13 +57,7 @@ import javax.persistence.PersistenceException; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.sql.DataSource; - import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; - import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.MappingException; @@ -73,7 +67,6 @@ import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; -import org.hibernate.cfg.Settings; import org.hibernate.cfg.annotations.reflection.XMLContext; import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider; import org.hibernate.ejb.instrument.InterceptFieldClassFileTransformer; @@ -94,7 +87,6 @@ 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; @@ -103,6 +95,8 @@ import org.hibernate.util.StringHelper; import org.hibernate.util.xml.MappingReader; import org.hibernate.util.xml.OriginImpl; import org.hibernate.util.xml.XmlDocument; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; /** * Allow a fine tuned configuration of an EJB 3.0 EntityManagerFactory @@ -122,7 +116,9 @@ import org.hibernate.util.xml.XmlDocument; * @author Emmanuel Bernard */ public class Ejb3Configuration implements Serializable, Referenceable { - private final Logger log = LoggerFactory.getLogger( Ejb3Configuration.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private static final String IMPLEMENTATION_NAME = HibernatePersistence.class.getName(); private static final String META_INF_ORM_XML = "META-INF/orm.xml"; private static final String PARSED_MAPPING_DOMS = "hibernate.internal.mapping_doms"; @@ -189,7 +185,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { */ @SuppressWarnings({ "unchecked" }) public Ejb3Configuration configure(PersistenceMetadata metadata, Map overridesIn) { - log.debug( "Creating Factory: {}", metadata.getName() ); + LOG.debug("Creating Factory: " + metadata.getName()); Map overrides = new HashMap(); if ( overridesIn != null ) { @@ -299,26 +295,24 @@ public class Ejb3Configuration implements Serializable, Referenceable { @SuppressWarnings({ "unchecked" }) public Ejb3Configuration configure(String persistenceUnitName, Map integration) { try { - log.debug( "Look up for persistence unit: {}", persistenceUnitName ); + LOG.debug("Look up for persistence unit: " + persistenceUnitName); integration = integration == null ? CollectionHelper.EMPTY_MAP : Collections.unmodifiableMap( integration ); Enumeration xmls = Thread.currentThread() .getContextClassLoader() .getResources( "META-INF/persistence.xml" ); - if ( ! xmls.hasMoreElements() ) { - log.info( "Could not find any META-INF/persistence.xml file in the classpath"); - } + if (!xmls.hasMoreElements()) LOG.unableToFindPersistenceXmlInClasspath(); while ( xmls.hasMoreElements() ) { URL url = xmls.nextElement(); - log.trace( "Analysing persistence.xml: {}", url ); + LOG.trace("Analyzing persistence.xml: " + url); List metadataFiles = PersistenceXmlLoader.deploy( url, integration, cfg.getEntityResolver(), PersistenceUnitTransactionType.RESOURCE_LOCAL ); for ( PersistenceMetadata metadata : metadataFiles ) { - log.trace( "{}", metadata ); + LOG.trace(metadata); if ( metadata.getProvider() == null || IMPLEMENTATION_NAME.equalsIgnoreCase( metadata.getProvider() @@ -514,12 +508,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { */ @SuppressWarnings({ "unchecked" }) public Ejb3Configuration configure(PersistenceUnitInfo info, Map integration) { - if ( log.isDebugEnabled() ) { - log.debug( "Processing {}", LogHelper.logPersistenceUnitInfo( info ) ); - } - else { - log.info( "Processing PersistenceUnitInfo [\n\tname: {}\n\t...]", info.getPersistenceUnitName() ); - } + if (LOG.isDebugEnabled()) LOG.debug("Processing " + LogHelper.logPersistenceUnitInfo(info)); + else LOG.processingPersistenceUnitInfoName(info.getPersistenceUnitName()); // Spec says the passed map may be null, so handle that to make further processing easier... integration = integration != null ? Collections.unmodifiableMap( integration ) : CollectionHelper.EMPTY_MAP; @@ -530,7 +520,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { provider = info.getPersistenceProviderClassName(); } if ( provider != null && ! provider.trim().startsWith( IMPLEMENTATION_NAME ) ) { - log.info( "Required a different provider: {}", provider ); + LOG.requiredDifferentProvider(provider); return null; } @@ -715,16 +705,13 @@ public class Ejb3Configuration implements Serializable, Referenceable { //TODO handle inputstream related hbm files ClassLoader classLoaderToUse = info.getNewTempClassLoader(); if ( classLoaderToUse == null ) { - log.warn( - "Persistence provider caller does not implement the EJB3 spec correctly." + - "PersistenceUnitInfo.getNewTempClassLoader() is null." - ); + LOG.persistenceProviderCallerDoesNotImplementEjb3SpecCorrectly(); return; } for ( final String xmlFile : xmlFiles ) { final InputStream fileInputStream = classLoaderToUse.getResourceAsStream( xmlFile ); if ( fileInputStream == null ) { - log.info( "Unable to resolve mapping file [{}]", xmlFile ); + LOG.unableToResolveMappingFile(xmlFile); continue; } final InputSource inputSource = new InputSource( fileInputStream ); @@ -771,7 +758,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { fileInputStream.close(); } catch (IOException ioe) { - log.warn( "Could not close input stream", ioe ); + LOG.warn(LOG.unableToCloseInputStream(), ioe); } } } @@ -836,13 +823,13 @@ public class Ejb3Configuration implements Serializable, Referenceable { if ( "class".equalsIgnoreCase( element ) ) detectClasses = true; if ( "hbm".equalsIgnoreCase( element ) ) detectHbm = true; } - log.debug( "Detect class: {}; detect hbm: {}", detectClasses, detectHbm ); + LOG.debug("Detect class: " + detectClasses + "; detect hbm: " + detectHbm); context.detectClasses( detectClasses ).detectHbmFiles( detectHbm ); } private void scanForClasses(ScanningContext scanningContext, List packages, List entities, List hbmFiles) { if (scanningContext.url == null) { - log.error( "Container is providing a null PersistenceUnitRootUrl: discovery impossible"); + LOG.containerProvidingNullPersistenceUnitRootUrl(); return; } try { @@ -867,7 +854,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { * @deprecated use the Java Persistence API */ // This is used directly by JBoss so don't remove until further notice. bill@jboss.org - public EntityManagerFactory createEntityManagerFactory(Map workingVars) { + @Deprecated + public EntityManagerFactory createEntityManagerFactory(Map workingVars) { Properties props = new Properties(); if ( workingVars != null ) { props.putAll( workingVars ); @@ -885,7 +873,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { * Process configuration and build an EntityManagerFactory when the configuration is ready * @deprecated */ - public EntityManagerFactory createEntityManagerFactory() { + @Deprecated + public EntityManagerFactory createEntityManagerFactory() { configure( cfg.getProperties(), new HashMap() ); return buildEntityManagerFactory(); } @@ -939,14 +928,12 @@ public class Ejb3Configuration implements Serializable, Referenceable { throw new PersistenceException( getExceptionHeader() + "Unable to instanciate " + AvailableSettings.SESSION_INTERCEPTOR + ": " + sessionInterceptorClassname, e); } - } - else { - return null; - } + } + return null; } public Reference getReference() throws NamingException { - log.debug("Returning a Reference to the Ejb3Configuration"); + LOG.debug("Returning a Reference to the Ejb3Configuration"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = null; byte[] serialized; @@ -1099,9 +1086,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { //some spec compliance checking //TODO centralize that? - if ( ! "true".equalsIgnoreCase( cfg.getProperty( Environment.AUTOCOMMIT ) ) ) { - log.warn( "{} = false break the EJB3 specification", Environment.AUTOCOMMIT ); - } + if (!"true".equalsIgnoreCase(cfg.getProperty(Environment.AUTOCOMMIT))) LOG.jdbcAutoCommitFalseBreaksEjb3Spec(Environment.AUTOCOMMIT); discardOnClose = preparedProperties.getProperty( AvailableSettings.DISCARD_PC_ON_CLOSE ) .equals( "true" ); return this; @@ -1162,14 +1147,8 @@ public class Ejb3Configuration implements Serializable, Referenceable { throw new PersistenceException( getExceptionHeader() + "Error while reading JPA XML file: " + xmlFile, me); } - if ( log.isInfoEnabled() ) { - if ( Boolean.TRUE.equals( useMetaInf ) ) { - log.info( "{} {} found", getExceptionHeader(), META_INF_ORM_XML); - } - else if (Boolean.FALSE.equals( useMetaInf ) ) { - log.info( "{} No {} found", getExceptionHeader(), META_INF_ORM_XML); - } - } + if (Boolean.TRUE.equals(useMetaInf)) LOG.exceptionHeaderFound(getExceptionHeader(), META_INF_ORM_XML); + else if (Boolean.FALSE.equals(useMetaInf)) LOG.exceptionHeaderNotFound(getExceptionHeader(), META_INF_ORM_XML); } } if ( workingVars.containsKey( AvailableSettings.HBXML_FILES ) ) { @@ -1195,12 +1174,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { } private String getExceptionHeader() { - if ( StringHelper.isNotEmpty( persistenceUnitName ) ) { - return "[PersistenceUnit: " + persistenceUnitName + "] "; - } - else { - return ""; - } + return (StringHelper.isNotEmpty(persistenceUnitName)) ? "[PersistenceUnit: " + persistenceUnitName + "] " : ""; } private Properties prepareProperties(Properties properties, Map workingVars) { @@ -1245,15 +1219,10 @@ public class Ejb3Configuration implements Serializable, Referenceable { else if ( ! hasTxStrategy && transactionType == PersistenceUnitTransactionType.RESOURCE_LOCAL ) { preparedProperties.setProperty( Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName() ); } - if ( hasTxStrategy ) { - log.warn( - "Overriding {} is dangerous, this might break the EJB3 specification implementation", - Environment.TRANSACTION_STRATEGY - ); - } + if (hasTxStrategy) LOG.overridingTransactionStrategyDangerous(Environment.TRANSACTION_STRATEGY); if ( preparedProperties.getProperty( Environment.FLUSH_BEFORE_COMPLETION ).equals( "true" ) ) { preparedProperties.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "false" ); - log.warn( "Defining {}=true ignored in HEM", Environment.FLUSH_BEFORE_COMPLETION ); + LOG.definingFlushBeforeCompletionIgnoredInHem(Environment.FLUSH_BEFORE_COMPLETION); } return preparedProperties; } @@ -1297,7 +1266,7 @@ public class Ejb3Configuration implements Serializable, Referenceable { } private void addSecurity(List keys, Map properties, Map workingVars) { - log.debug( "Adding security" ); + LOG.debug("Adding security"); if ( !properties.containsKey( AvailableSettings.JACC_CONTEXT_ID ) ) { throw new PersistenceException( getExceptionHeader() + "Entities have been configured for JACC, but " diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerImpl.java index b9d533e270..5d64d80b3f 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/EntityManagerImpl.java @@ -26,15 +26,12 @@ import javax.persistence.PersistenceContextType; import javax.persistence.PersistenceException; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.transaction.Synchronization; - import org.hibernate.HibernateException; -import org.hibernate.Session; import org.hibernate.Interceptor; +import org.hibernate.Session; import org.hibernate.annotations.common.util.ReflectHelper; import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionImplementor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Hibernate implementation of {@link javax.persistence.EntityManager}. @@ -42,7 +39,9 @@ import org.slf4j.LoggerFactory; * @author Gavin King */ public class EntityManagerImpl extends AbstractEntityManagerImpl { - private static final Logger log = LoggerFactory.getLogger( EntityManagerImpl.class ); + + public static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerImpl.class.getPackage().getName()); protected Session session; protected boolean open; @@ -53,7 +52,7 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl { EntityManagerFactoryImpl entityManagerFactory, PersistenceContextType pcType, PersistenceUnitTransactionType transactionType, - boolean discardOnClose, + boolean discardOnClose, Class sessionInterceptorClass, Map properties) { super( entityManagerFactory, pcType, transactionType, properties ); @@ -84,14 +83,16 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl { postInit(); } - public Session getSession() { + @Override + public Session getSession() { if ( !open ) { throw new IllegalStateException( "EntityManager is closed" ); } return getRawSession(); } - protected Session getRawSession() { + @Override + protected Session getRawSession() { if ( session == null ) { Interceptor interceptor = null; if (sessionInterceptorClass != null) { @@ -122,27 +123,19 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl { } if ( !discardOnClose && isTransactionInProgress() ) { //delay the closing till the end of the enlisted transaction - getSession().getTransaction().registerSynchronization( - new Synchronization() { - public void beforeCompletion() { - //nothing to do - } + getSession().getTransaction().registerSynchronization(new Synchronization() { + public void beforeCompletion() { + // nothing to do + } - public void afterCompletion(int i) { - if ( session != null ) { - if ( session.isOpen() ) { - log.debug( "Closing entity manager after transaction completion" ); - session.close(); - } - else { - log.warn( "Entity Manager closed by someone else ({} must not be used)", - Environment.AUTO_CLOSE_SESSION); - } - } - //TODO session == null should not happen - } - } - ); + public void afterCompletion( int i ) { + if (session != null) if (session.isOpen()) { + LOG.debug("Closing entity manager after transaction completion"); + session.close(); + } else LOG.entityManagerClosedBySomeoneElse(Environment.AUTO_CLOSE_SESSION); + // TODO session == null should not happen + } + }); } else { //close right now diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java index 42a25541a2..e2dbd94d86 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java @@ -23,6 +23,9 @@ */ package org.hibernate.ejb; +import static javax.persistence.TemporalType.DATE; +import static javax.persistence.TemporalType.TIME; +import static javax.persistence.TemporalType.TIMESTAMP; import java.util.Calendar; import java.util.Collection; import java.util.Collections; @@ -31,36 +34,27 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.Parameter; +import javax.persistence.PersistenceException; import javax.persistence.Query; import javax.persistence.TemporalType; -import static javax.persistence.TemporalType.DATE; -import static javax.persistence.TemporalType.TIME; -import static javax.persistence.TemporalType.TIMESTAMP; -import javax.persistence.TypedQuery; -import javax.persistence.PersistenceException; import javax.persistence.TransactionRequiredException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import javax.persistence.TypedQuery; import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.QueryParameterException; -import org.hibernate.TypeMismatchException; import org.hibernate.SQLQuery; +import org.hibernate.TypeMismatchException; import org.hibernate.ejb.util.LockModeTypeHelper; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.query.NamedParameterDescriptor; import org.hibernate.engine.query.OrdinalParameterDescriptor; import org.hibernate.hql.QueryExecutionRequestException; import org.hibernate.impl.AbstractQueryImpl; -import org.hibernate.type.TypeFactory; /** * Hibernate implementation of both the {@link Query} and {@link TypedQuery} contracts. @@ -70,7 +64,9 @@ import org.hibernate.type.TypeFactory; * @author Steve Ebersole */ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl implements TypedQuery, HibernateQuery { - private static final Logger log = LoggerFactory.getLogger( QueryImpl.class ); + + public static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + QueryImpl.class.getPackage().getName()); private org.hibernate.Query query; private Set jpaPositionalIndices; @@ -133,9 +129,7 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme ); parameters.add( parameter ); Integer position = descriptor.getOrdinalPosition(); - if ( jpaPositionalIndices != null && jpaPositionalIndices.contains( position ) ) { - log.warn( "Parameter position [" + position + "] occurred as both JPA and Hibernate positional parameter" ); - } + if (jpaPositionalIndices != null && jpaPositionalIndices.contains(position)) LOG.parameterPositionOccurredAsBothJpaAndHibernatePositionalParameter(position); } this.parameters = java.util.Collections.unmodifiableSet( parameters ); @@ -184,51 +178,63 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme return query; } - protected int internalExecuteUpdate() { + @Override + protected int internalExecuteUpdate() { return query.executeUpdate(); } - protected void applyMaxResults(int maxResults) { + @Override + protected void applyMaxResults(int maxResults) { query.setMaxResults( maxResults ); } - protected void applyFirstResult(int firstResult) { + @Override + protected void applyFirstResult(int firstResult) { query.setFirstResult( firstResult ); } - protected void applyTimeout(int timeout) { + @Override + protected void applyTimeout(int timeout) { query.setTimeout( timeout ); } - protected void applyComment(String comment) { + @Override + protected void applyComment(String comment) { query.setComment( comment ); } - protected void applyFetchSize(int fetchSize) { + @Override + protected void applyFetchSize(int fetchSize) { query.setFetchSize( fetchSize ); } - protected void applyCacheable(boolean isCacheable) { + @Override + protected void applyCacheable(boolean isCacheable) { query.setCacheable( isCacheable ); } - protected void applyCacheRegion(String regionName) { + @Override + protected void applyCacheRegion(String regionName) { query.setCacheRegion( regionName ); } - protected void applyReadOnly(boolean isReadOnly) { + @Override + protected void applyReadOnly(boolean isReadOnly) { query.setReadOnly( isReadOnly ); } - protected void applyCacheMode(CacheMode cacheMode) { + @Override + protected void applyCacheMode(CacheMode cacheMode) { query.setCacheMode( cacheMode ); } - protected void applyFlushMode(FlushMode flushMode) { + @Override + protected void applyFlushMode(FlushMode flushMode) { query.setFlushMode( flushMode ); } - protected boolean canApplyLockModes() { + @Override + protected boolean canApplyLockModes() { return org.hibernate.impl.QueryImpl.class.isInstance( query ); } @@ -243,7 +249,7 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme @SuppressWarnings({ "unchecked", "RedundantCast" }) public List getResultList() { try { - return (List) query.list(); + return query.list(); } catch (QueryExecutionRequestException he) { throw new IllegalStateException(he); @@ -271,7 +277,7 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme mucked = true; query.setMaxResults( 2 ); //avoid OOME if the list is huge } - List result = (List) query.list(); + List result = query.list(); if ( mucked ) { query.setMaxResults( getSpecifiedMaxResults() ); } @@ -608,7 +614,8 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme private javax.persistence.LockModeType jpaLockMode = javax.persistence.LockModeType.NONE; - @SuppressWarnings({ "unchecked" }) + @Override + @SuppressWarnings({ "unchecked" }) public TypedQuery setLockMode(javax.persistence.LockModeType lockModeType) { if (! getEntityManager().isTransactionInProgress()) { throw new TransactionRequiredException( "no transaction is in progress" ); @@ -623,7 +630,8 @@ public class QueryImpl extends org.hibernate.ejb.AbstractQueryImpl impleme return this; } - public javax.persistence.LockModeType getLockMode() { + @Override + public javax.persistence.LockModeType getLockMode() { return jpaLockMode; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Version.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Version.java index 68a274f10a..1ba731e2df 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Version.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/Version.java @@ -24,22 +24,21 @@ //$Id$ package org.hibernate.ejb; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Emmanuel Bernard */ public class Version { - private static Logger log = LoggerFactory.getLogger( Version.class ); + + public static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + Version.class.getPackage().getName()); public static String getVersionString() { return "[WORKING]"; } static { - log.info( "Hibernate EntityManager {}", getVersionString() ); + LOG.entityManagerVersion(getVersionString()); } public static void touch() { 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 8bcb156daa..5a839e455f 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 @@ -21,18 +21,15 @@ */ package org.hibernate.ejb.connection; -import java.util.Properties; 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.ejb.EntityManagerLogger; import org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - /** * A specialization of {@link DatasourceConnectionProviderImpl} which uses the {@link DataSource} specified vi * {@link #setDataSource} rather than locating it from JNDI. @@ -44,12 +41,15 @@ import org.slf4j.Logger; * @author Emmanuel Bernard */ public class InjectedDataSourceConnectionProvider extends DatasourceConnectionProviderImpl { - private final Logger log = LoggerFactory.getLogger( InjectedDataSourceConnectionProvider.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private String user; private String pass; - public void setDataSource(DataSource ds) { + @Override + public void setDataSource(DataSource ds) { super.setDataSource( ds ); } @@ -57,19 +57,13 @@ public class InjectedDataSourceConnectionProvider extends DatasourceConnectionPr user = props.getProperty( Environment.USER ); pass = props.getProperty( Environment.PASS ); - if ( getDataSource() == null ) { - throw new HibernateException( "No datasource provided" ); - } - log.info( "Using provided datasource" ); + if (getDataSource() == null) throw new HibernateException("No datasource provided"); + LOG.usingProvidedDataSource(); } @Override public Connection getConnection() throws SQLException { - if (user != null || pass != null) { - return getDataSource().getConnection(user, pass); - } - else { - return getDataSource().getConnection(); - } + if (user != null || pass != null) return getDataSource().getConnection(user, pass); + return getDataSource().getConnection(); } } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryCompiler.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryCompiler.java index a6f5317299..8ea5cbecb0 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryCompiler.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/criteria/CriteriaQueryCompiler.java @@ -24,28 +24,24 @@ package org.hibernate.ejb.criteria; import java.io.Serializable; -import java.util.Set; -import java.util.Map; -import java.util.HashMap; -import java.util.List; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; -import javax.persistence.TypedQuery; -import javax.persistence.Parameter; -import javax.persistence.TemporalType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; +import javax.persistence.Parameter; +import javax.persistence.TemporalType; +import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.ejb.HibernateEntityManagerImplementor; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.type.Type; -import org.hibernate.type.TypeFactory; import org.hibernate.util.StringHelper; /** @@ -58,7 +54,9 @@ import org.hibernate.util.StringHelper; * @author Steve Ebersole */ public class CriteriaQueryCompiler implements Serializable { - private static final Logger log = LoggerFactory.getLogger( CriteriaQueryCompiler.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); /** * Used to describe implicit (not defined in criteria query) parameters. @@ -222,7 +220,7 @@ public class CriteriaQueryCompiler implements Serializable { final RenderedCriteriaQuery renderedCriteriaQuery = criteriaQueryImpl.render( renderingContext ); - log.debug( "Rendered criteria query -> {}", renderedCriteriaQuery.getQueryString() ); + LOG.debug("Rendered criteria query -> " + renderedCriteriaQuery.getQueryString()); TypedQuery jpaqlQuery = entityManager.createQuery( renderedCriteriaQuery.getQueryString(), @@ -332,7 +330,7 @@ public class CriteriaQueryCompiler implements Serializable { @SuppressWarnings({ "RedundantCast" }) private Parameter mapToNamedParameter(Parameter criteriaParameter) { return jpaqlQuery.getParameter( - explicitParameterMapping.get( (ParameterExpression) criteriaParameter ) + explicitParameterMapping.get( criteriaParameter ) ); } @@ -373,7 +371,7 @@ public class CriteriaQueryCompiler implements Serializable { public Parameter getParameter(String name, Class type) { Parameter parameter = resolveExplicitCriteriaParameterName( name ); if ( type.isAssignableFrom( parameter.getParameterType() ) ) { - return (Parameter) parameter; + return parameter; } throw new IllegalArgumentException( "Named parameter [" + name + "] type is not assignanle to request type [" diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/event/CallbackResolver.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/event/CallbackResolver.java index 499378a562..e21f2f8bf0 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/event/CallbackResolver.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/event/CallbackResolver.java @@ -33,25 +33,25 @@ import javax.persistence.ExcludeDefaultListeners; import javax.persistence.ExcludeSuperclassListeners; import javax.persistence.MappedSuperclass; import javax.persistence.PersistenceException; - import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.annotations.common.reflection.XClass; import org.hibernate.annotations.common.reflection.XMethod; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.ejb.EntityManagerLogger; /** * @author Kabir Khan */ public final class CallbackResolver { - private static Logger log = LoggerFactory.getLogger(CallbackResolver.class); - + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); + private static boolean useAnnotationAnnotatedByListener; static { //check whether reading annotations of annotations is useful or not useAnnotationAnnotatedByListener = false; - Target target = (Target) EntityListeners.class.getAnnotation( Target.class ); + Target target = EntityListeners.class.getAnnotation( Target.class ); if ( target != null ) { for ( ElementType type : target.value() ) { if ( type.equals( ElementType.ANNOTATION_TYPE ) ) useAnnotationAnnotatedByListener = true; @@ -90,10 +90,9 @@ public final class CallbackResolver { .getName() + " - " + xMethod ); } - if ( ! method.isAccessible() ) { - method.setAccessible( true ); - } - log.debug("Adding {} as {} callback for entity {}.", new String[]{methodName, annotation.getSimpleName(), beanClass.getName()}); + if (!method.isAccessible()) method.setAccessible(true); + LOG.debug("Adding " + methodName + " as " + annotation.getSimpleName() + " callback for entity " + + beanClass.getName() + "."); callbacks.add( 0, callback ); //superclass first callbacksMethodNames.add( 0, methodName ); } @@ -173,10 +172,9 @@ public final class CallbackResolver { .getName() + " - " + method ); } - if ( ! method.isAccessible() ) { - method.setAccessible( true ); - } - log.debug("Adding {} as {} callback for entity {}.", new String[]{methodName, annotation.getSimpleName(), beanClass.getName()}); + if (!method.isAccessible()) method.setAccessible(true); + LOG.debug("Adding " + methodName + " as " + annotation.getSimpleName() + + " callback for entity " + beanClass.getName() + "."); callbacks.add( 0, callback ); // listeners first } else { @@ -198,7 +196,7 @@ public final class CallbackResolver { } private static void getListeners(XClass currentClazz, List orderedListeners) { - EntityListeners entityListeners = (EntityListeners) currentClazz.getAnnotation( EntityListeners.class ); + EntityListeners entityListeners = currentClazz.getAnnotation( EntityListeners.class ); if ( entityListeners != null ) { Class[] classes = entityListeners.value(); int size = classes.length; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/AttributeFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/AttributeFactory.java index 53adafd5d0..ab7b0e2b0e 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/AttributeFactory.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/AttributeFactory.java @@ -23,8 +23,8 @@ */ package org.hibernate.ejb.metamodel; -import java.lang.reflect.Member; import java.lang.reflect.Field; +import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; @@ -32,25 +32,22 @@ import java.util.Iterator; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.IdentifiableType; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.Type; -import javax.persistence.metamodel.IdentifiableType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; -import org.hibernate.type.EmbeddedComponentType; -import org.hibernate.type.ComponentType; import org.hibernate.annotations.common.AssertionFailure; +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Component; import org.hibernate.mapping.Map; import org.hibernate.mapping.OneToMany; +import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.Value; -import org.hibernate.mapping.PersistentClass; import org.hibernate.tuple.entity.EntityMetamodel; +import org.hibernate.type.ComponentType; +import org.hibernate.type.EmbeddedComponentType; import org.hibernate.type.EntityType; /** @@ -64,7 +61,9 @@ import org.hibernate.type.EntityType; * @author Emmanuel Bernard */ public class AttributeFactory { - private static final Logger log = LoggerFactory.getLogger( AttributeFactory.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private final MetadataContext context; @@ -85,33 +84,20 @@ public class AttributeFactory { public AttributeImplementor buildAttribute(AbstractManagedType ownerType, Property property) { if ( property.isSynthetic() ) { // hide synthetic/virtual properties (fabricated by Hibernate) from the JPA metamodel. - log.trace( "Skipping synthetic property {}({})", ownerType.getJavaType().getName(), property.getName() ); + LOG.trace("Skipping synthetic property " + ownerType.getJavaType().getName() + "(" + property.getName() + ")"); return null; } - log.trace( "Building attribute [{}.{}]", ownerType.getJavaType().getName(), property.getName() ); + LOG.trace("Building attribute [" + ownerType.getJavaType().getName() + "." + property.getName() + "]"); final AttributeContext attributeContext = wrap( ownerType, property ); final AttributeMetadata attributeMetadata = determineAttributeMetadata( attributeContext, NORMAL_MEMBER_RESOLVER ); - if ( attributeMetadata.isPlural() ) { - return buildPluralAttribute( (PluralAttributeMetadata) attributeMetadata ); - } - else { - final SingularAttributeMetadata singularAttributeMetadata = - (SingularAttributeMetadata) attributeMetadata; - final Type metaModelType = getMetaModelType( singularAttributeMetadata.getValueContext() ); - return new SingularAttributeImpl( - attributeMetadata.getName(), - attributeMetadata.getJavaType(), - ownerType, - attributeMetadata.getMember(), - false, - false, - property.isOptional(), - metaModelType, - attributeMetadata.getPersistentAttributeType() - ); - } + if (attributeMetadata.isPlural()) return buildPluralAttribute((PluralAttributeMetadata)attributeMetadata); + final SingularAttributeMetadata singularAttributeMetadata = (SingularAttributeMetadata)attributeMetadata; + final Type metaModelType = getMetaModelType(singularAttributeMetadata.getValueContext()); + return new SingularAttributeImpl(attributeMetadata.getName(), attributeMetadata.getJavaType(), ownerType, + attributeMetadata.getMember(), false, false, property.isOptional(), metaModelType, + attributeMetadata.getPersistentAttributeType()); } private AttributeContext wrap(final AbstractManagedType ownerType, final Property property) { @@ -137,7 +123,7 @@ public class AttributeFactory { */ @SuppressWarnings({ "unchecked" }) public SingularAttributeImpl buildIdAttribute(AbstractIdentifiableType ownerType, Property property) { - log.trace( "Building identifier attribute [{}.{}]", ownerType.getJavaType().getName(), property.getName() ); + LOG.trace("Building identifier attribute [" + ownerType.getJavaType().getName() + "." + property.getName() + "]"); final AttributeContext attributeContext = wrap( ownerType, property ); final SingularAttributeMetadata attributeMetadata = (SingularAttributeMetadata) determineAttributeMetadata( attributeContext, IDENTIFIER_MEMBER_RESOLVER ); @@ -163,7 +149,7 @@ public class AttributeFactory { */ @SuppressWarnings({ "unchecked" }) public SingularAttributeImpl buildVersionAttribute(AbstractIdentifiableType ownerType, Property property) { - log.trace( "Building version attribute [{}.{}]", ownerType.getJavaType().getName(), property.getName() ); + LOG.trace("Building version attribute [ownerType.getJavaType().getName()" + "." + "property.getName()]"); final AttributeContext attributeContext = wrap( ownerType, property ); final SingularAttributeMetadata attributeMetadata = (SingularAttributeMetadata) determineAttributeMetadata( attributeContext, VERSION_MEMBER_RESOLVER ); @@ -189,13 +175,7 @@ public class AttributeFactory { .persistentAttributeType( attributeMetadata.getPersistentAttributeType() ) .build(); } - else { - return PluralAttributeImpl.create( attributeMetadata.getOwnerType(), elementType, attributeMetadata.getJavaType(), null ) - .member( attributeMetadata.getMember() ) - .property( attributeMetadata.getPropertyMapping() ) - .persistentAttributeType( attributeMetadata.getPersistentAttributeType() ) - .build(); - } + return PluralAttributeImpl.create(attributeMetadata.getOwnerType(), elementType, attributeMetadata.getJavaType(), null).member(attributeMetadata.getMember()).property(attributeMetadata.getPropertyMapping()).persistentAttributeType(attributeMetadata.getPersistentAttributeType()).build(); } @SuppressWarnings( "unchecked" ) @@ -440,13 +420,13 @@ public class AttributeFactory { private AttributeMetadata determineAttributeMetadata( AttributeContext attributeContext, MemberResolver memberResolver) { - log.trace( "Starting attribute metadata determination [{}]", attributeContext.getPropertyMapping().getName() ); + LOG.trace("Starting attribute metadata determination [" + attributeContext.getPropertyMapping().getName() + "]"); final Member member = memberResolver.resolveMember( attributeContext ); - log.trace( " Determined member [{}]", member ); + LOG.trace(" Determined member [" + member + "]"); final Value value = attributeContext.getPropertyMapping().getValue(); final org.hibernate.type.Type type = value.getType(); - log.trace( " determined type [name={}, class={}]", type.getName(), type.getClass().getName() ); + LOG.trace(" Determined type [name=" + type.getName() + ", class=" + type.getClass().getName() + "]"); if ( type.isAnyType() ) { throw new UnsupportedOperationException( "any not supported yet" ); @@ -462,72 +442,50 @@ public class AttributeFactory { determineSingularAssociationAttributeType( member ) ); } - else { - // collection - if ( value instanceof Collection ) { - final Collection collValue = (Collection) value; - final Value elementValue = collValue.getElement(); - final org.hibernate.type.Type elementType = elementValue.getType(); + // collection + if (value instanceof Collection) { + final Collection collValue = (Collection)value; + final Value elementValue = collValue.getElement(); + final org.hibernate.type.Type elementType = elementValue.getType(); - // First, determine the type of the elements and use that to help determine the - // collection type) - final Attribute.PersistentAttributeType elementPersistentAttributeType; - final Attribute.PersistentAttributeType persistentAttributeType; - if ( elementType.isAnyType() ) { - throw new UnsupportedOperationException( "collection of any not supported yet" ); - } - final boolean isManyToMany = isManyToMany( member ); - if ( elementValue instanceof Component ) { - elementPersistentAttributeType = Attribute.PersistentAttributeType.EMBEDDED; - persistentAttributeType = Attribute.PersistentAttributeType.ELEMENT_COLLECTION; - } - else if ( elementType.isAssociationType() ) { - elementPersistentAttributeType = isManyToMany - ? Attribute.PersistentAttributeType.MANY_TO_MANY - : Attribute.PersistentAttributeType.ONE_TO_MANY; - persistentAttributeType = elementPersistentAttributeType; - } - else { - elementPersistentAttributeType = Attribute.PersistentAttributeType.BASIC; - persistentAttributeType = Attribute.PersistentAttributeType.ELEMENT_COLLECTION; - } + // First, determine the type of the elements and use that to help determine the + // collection type) + final Attribute.PersistentAttributeType elementPersistentAttributeType; + final Attribute.PersistentAttributeType persistentAttributeType; + if (elementType.isAnyType()) { + throw new UnsupportedOperationException("collection of any not supported yet"); + } + final boolean isManyToMany = isManyToMany(member); + if (elementValue instanceof Component) { + elementPersistentAttributeType = Attribute.PersistentAttributeType.EMBEDDED; + persistentAttributeType = Attribute.PersistentAttributeType.ELEMENT_COLLECTION; + } else if (elementType.isAssociationType()) { + elementPersistentAttributeType = isManyToMany ? Attribute.PersistentAttributeType.MANY_TO_MANY : Attribute.PersistentAttributeType.ONE_TO_MANY; + persistentAttributeType = elementPersistentAttributeType; + } else { + elementPersistentAttributeType = Attribute.PersistentAttributeType.BASIC; + persistentAttributeType = Attribute.PersistentAttributeType.ELEMENT_COLLECTION; + } - final Attribute.PersistentAttributeType keyPersistentAttributeType; + final Attribute.PersistentAttributeType keyPersistentAttributeType; - // Finally, we determine the type of the map key (if needed) - if ( value instanceof Map ) { - final Value keyValue = ( ( Map ) value ).getIndex(); - final org.hibernate.type.Type keyType = keyValue.getType(); + // Finally, we determine the type of the map key (if needed) + if (value instanceof Map) { + final Value keyValue = ((Map)value).getIndex(); + final org.hibernate.type.Type keyType = keyValue.getType(); - if ( keyType.isAnyType() ) { - throw new UnsupportedOperationException( "collection of any not supported yet" ); - } - if ( keyValue instanceof Component ) { - keyPersistentAttributeType = Attribute.PersistentAttributeType.EMBEDDED; - } - else if ( keyType.isAssociationType() ) { - keyPersistentAttributeType = Attribute.PersistentAttributeType.MANY_TO_ONE; - } - else { - keyPersistentAttributeType = Attribute.PersistentAttributeType.BASIC; - } - } - else { - keyPersistentAttributeType = null; - } - return new PluralAttributeMetadataImpl( - attributeContext.getPropertyMapping(), - attributeContext.getOwnerType(), - member, - persistentAttributeType, - elementPersistentAttributeType, - keyPersistentAttributeType - ); - } - else if ( value instanceof OneToMany ) { - // TODO : is this even possible??? Really OneToMany should be describing the - // element value within a o.h.mapping.Collection (see logic branch above) - throw new IllegalArgumentException( "HUH???" ); + if (keyType.isAnyType()) throw new UnsupportedOperationException("collection of any not supported yet"); + if (keyValue instanceof Component) keyPersistentAttributeType = Attribute.PersistentAttributeType.EMBEDDED; + else if (keyType.isAssociationType()) keyPersistentAttributeType = Attribute.PersistentAttributeType.MANY_TO_ONE; + else keyPersistentAttributeType = Attribute.PersistentAttributeType.BASIC; + } else keyPersistentAttributeType = null; + return new PluralAttributeMetadataImpl(attributeContext.getPropertyMapping(), attributeContext.getOwnerType(), + member, persistentAttributeType, elementPersistentAttributeType, + keyPersistentAttributeType); + } else if (value instanceof OneToMany) { + // TODO : is this even possible??? Really OneToMany should be describing the + // element value within a o.h.mapping.Collection (see logic branch above) + throw new IllegalArgumentException("HUH???"); // final boolean isManyToMany = isManyToMany( member ); // //one to many with FK => entity // return new PluralAttributeMetadataImpl( @@ -542,7 +500,6 @@ public class AttributeFactory { // Attribute.PersistentAttributeType.ONE_TO_MANY, // null, null, null // ); - } } } else if ( attributeContext.getPropertyMapping().isComposite() ) { diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java index ec3c3c2498..990882a98f 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java @@ -33,12 +33,8 @@ import java.util.Set; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.IdentifiableType; import javax.persistence.metamodel.SingularAttribute; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - import org.hibernate.annotations.common.AssertionFailure; +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.mapping.Component; import org.hibernate.mapping.KeyValue; @@ -60,7 +56,9 @@ import org.hibernate.mapping.Property; * @author Emmanuel Bernard */ class MetadataContext { - private static final Logger log = LoggerFactory.getLogger( MetadataContext.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private final SessionFactoryImplementor sessionFactory; private final AttributeFactory attributeFactory = new AttributeFactory( this ); @@ -79,7 +77,7 @@ class MetadataContext { private List orderedMappings = new ArrayList(); /** * Stack of PersistentClass being process. Last in the list is the highest in the stack. - * + * */ private List stackOfPersistentClassesBeingProcessed = new ArrayList(); @@ -160,18 +158,18 @@ class MetadataContext { @SuppressWarnings({ "unchecked" }) public void wrapUp() { - log.trace( "Wrapping up metadata context..." ); + LOG.trace("Wrapping up metadata context..."); //we need to process types from superclasses to subclasses for (Object mapping : orderedMappings) { if ( PersistentClass.class.isAssignableFrom( mapping.getClass() ) ) { @SuppressWarnings( "unchecked" ) final PersistentClass safeMapping = (PersistentClass) mapping; - log.trace( "Starting entity [{}]", safeMapping.getEntityName() ); + LOG.trace("Starting entity [" + safeMapping.getEntityName() + "]"); try { final EntityTypeImpl jpa2Mapping = entityTypesByPersistentClass.get( safeMapping ); applyIdMetadata( safeMapping, jpa2Mapping ); applyVersionAttribute( safeMapping, jpa2Mapping ); - Iterator properties = ( Iterator ) safeMapping.getDeclaredPropertyIterator(); + Iterator properties = safeMapping.getDeclaredPropertyIterator(); while ( properties.hasNext() ) { final Property property = properties.next(); if ( property.getValue() == safeMapping.getIdentifierMapper() ) { @@ -189,20 +187,20 @@ class MetadataContext { populateStaticMetamodel( jpa2Mapping ); } finally { - log.trace( "Completed entity [{}]", safeMapping.getEntityName() ); + LOG.trace("Completed entity [" + safeMapping.getEntityName() + "]"); } } else if ( MappedSuperclass.class.isAssignableFrom( mapping.getClass() ) ) { @SuppressWarnings( "unchecked" ) final MappedSuperclass safeMapping = (MappedSuperclass) mapping; - log.trace( "Starting mapped superclass [{}]", safeMapping.getMappedClass().getName() ); + LOG.trace("Starting mapped superclass [" + safeMapping.getMappedClass().getName() + "]"); try { final MappedSuperclassTypeImpl jpa2Mapping = mappedSuperclassByMappedSuperclassMapping.get( safeMapping ); applyIdMetadata( safeMapping, jpa2Mapping ); applyVersionAttribute( safeMapping, jpa2Mapping ); - Iterator properties = ( Iterator ) safeMapping.getDeclaredPropertyIterator(); + Iterator properties = safeMapping.getDeclaredPropertyIterator(); while ( properties.hasNext() ) { final Property property = properties.next(); final Attribute attribute = attributeFactory.buildAttribute( jpa2Mapping, property ); @@ -214,7 +212,7 @@ class MetadataContext { populateStaticMetamodel( jpa2Mapping ); } finally { - log.trace( "Completed mapped superclass [{}]", safeMapping.getMappedClass().getName() ); + LOG.trace("Completed mapped superclass [" + safeMapping.getMappedClass().getName() + "]"); } } else { @@ -310,7 +308,7 @@ class MetadataContext { private Set> buildIdClassAttributes( MappedSuperclassTypeImpl jpaMappingType, MappedSuperclass mappingType) { - log.trace( "Building old-school composite identifier [{}]", mappingType.getMappedClass().getName() ); + LOG.trace("Building old-school composite identifier [" + mappingType.getMappedClass().getName() + "]"); Set> attributes = new HashSet>(); @SuppressWarnings( "unchecked" ) Iterator properties = mappingType.getIdentifierMapper().getPropertyIterator(); @@ -402,15 +400,14 @@ class MetadataContext { // + "; expected type : " + attribute.getClass().getName() // + "; encountered type : " + field.getType().getName() // ); - log.error( - "Illegal argument on static metamodel field injection : " + metamodelClass.getName() + '#' + name - + "; expected type : " + attribute.getClass().getName() - + "; encountered type : " + field.getType().getName() - ); + LOG.illegalArgumentOnStaticMetamodelFieldInjection(metamodelClass.getName(), + name, + attribute.getClass().getName(), + field.getType().getName()); } } catch ( NoSuchFieldException e ) { - log.error( "Unable to locate static metamodel field : " + metamodelClass.getName() + '#' + name ); + LOG.unableToLocateStaticMetamodelField(metamodelClass.getName(), name); // throw new AssertionFailure( // "Unable to locate static metamodel field : " + metamodelClass.getName() + '#' + name // ); diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/AbstractJarVisitor.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/AbstractJarVisitor.java index 82ce1eecda..3bd133a8b2 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/AbstractJarVisitor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/AbstractJarVisitor.java @@ -29,11 +29,9 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; - import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.ejb.EntityManagerLogger; /** * Parse a JAR of any form (zip file, exploded directory, ...) @@ -46,7 +44,9 @@ public abstract class AbstractJarVisitor implements JarVisitor { //TODO shortcut when filters are null or empty - private final Logger log = LoggerFactory.getLogger( AbstractJarVisitor.class ); + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); + protected String unqualifiedJarName; protected URL jarUrl; protected boolean done = false; @@ -120,7 +120,7 @@ public abstract class AbstractJarVisitor implements JarVisitor { fileName = fileName.substring( 0, fileName.length() - 4 ); } unqualifiedJarName = fileName; - log.debug( "Searching mapped entities in jar/par: {}", jarUrl ); + LOG.debug("Searching mapped entities in jar/par: " + jarUrl); } /** @@ -166,7 +166,7 @@ public abstract class AbstractJarVisitor implements JarVisitor { } else if ( entryName.endsWith( ".class" ) ) { String name = entryName.substring( 0, entryNameLength - ".class".length() ).replace( '/', '.' ); - log.debug( "Filtering: {}", name ); + LOG.debug("Filtering: " + name); executeJavaElementFilter( name, classFilters, is, secondIs ); } else { @@ -184,7 +184,7 @@ public abstract class AbstractJarVisitor implements JarVisitor { secondIs.close(); } is.close(); - log.debug( "File Filter matched for {}", name ); + LOG.debug("File Filter matched for " + name); Entry entry = new Entry( name, localIs ); int index = this.filters.indexOf( filter ); this.entries[index].add( entry ); @@ -217,7 +217,7 @@ public abstract class AbstractJarVisitor implements JarVisitor { localIs = null; secondIs.close(); } - log.debug( "Java element filter matched for {}", name ); + LOG.debug("Java element filter matched for " + name); Entry entry = new Entry( name, localIs ); int index = this.filters.indexOf( filter ); this.entries[index].add( entry ); diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/ExplodedJarVisitor.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/ExplodedJarVisitor.java index 3429816498..2ca53b943d 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/ExplodedJarVisitor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/ExplodedJarVisitor.java @@ -30,17 +30,18 @@ import java.net.URL; import java.util.Enumeration; import java.util.jar.JarFile; import java.util.zip.ZipEntry; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; +import org.hibernate.ejb.EntityManagerLogger; /** * @author Emmanuel Bernard */ public class ExplodedJarVisitor extends AbstractJarVisitor { - private final Logger log = LoggerFactory.getLogger( ExplodedJarVisitor.class ); - private String entry; + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); + + private String entry; public ExplodedJarVisitor(URL url, Filter[] filters, String entry) { super( url, filters ); @@ -51,7 +52,8 @@ public class ExplodedJarVisitor extends AbstractJarVisitor { super( fileName, filters ); } - protected void doProcessElements() throws IOException { + @Override + protected void doProcessElements() throws IOException { File jarFile; try { String filePart = jarUrl.getFile(); @@ -64,16 +66,16 @@ public class ExplodedJarVisitor extends AbstractJarVisitor { } } catch (URISyntaxException e) { - log.warn( "Malformed url: " + jarUrl, e ); + LOG.error(LOG.malformedUrl(jarUrl), e); return; } - + if ( !jarFile.exists() ) { - log.warn( "Exploded jar does not exists (ignored): {}", jarUrl ); + LOG.explodedJarDoesNotExist(jarUrl); return; } if ( !jarFile.isDirectory() ) { - log.warn( "Exploded jar file not a directory (ignored): {}", jarUrl ); + LOG.explodedJarNotDirectory(jarUrl); return; } File rootFile; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/FileZippedJarVisitor.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/FileZippedJarVisitor.java index 24f530581e..814c1d30b4 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/FileZippedJarVisitor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/FileZippedJarVisitor.java @@ -22,18 +22,16 @@ package org.hibernate.ejb.packaging; import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.ByteArrayInputStream; -import java.net.URL; import java.net.URISyntaxException; +import java.net.URL; import java.util.Enumeration; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.zip.ZipEntry; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.ejb.EntityManagerLogger; /** * Work on a JAR that can be accessed through a File @@ -41,8 +39,11 @@ import org.slf4j.LoggerFactory; * @author Emmanuel Bernard */ public class FileZippedJarVisitor extends AbstractJarVisitor { - private final Logger log = LoggerFactory.getLogger( FileZippedJarVisitor.class ); - private String entry; + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); + + private String entry; public FileZippedJarVisitor(String fileName, Filter[] filters) { super( fileName, filters ); @@ -53,7 +54,8 @@ public class FileZippedJarVisitor extends AbstractJarVisitor { this.entry = entry; } - protected void doProcessElements() throws IOException { + @Override + protected void doProcessElements() throws IOException { JarFile jarFile; try { String filePart = jarUrl.getFile(); @@ -66,11 +68,11 @@ public class FileZippedJarVisitor extends AbstractJarVisitor { } } catch (IOException ze) { - log.warn( "Unable to find file (ignored): " + jarUrl, ze ); + LOG.warn(LOG.unableToFindFile(jarUrl), ze); return; } catch (URISyntaxException e) { - log.warn( "Malformed url: " + jarUrl, e ); + LOG.warn(LOG.malformedUrl(jarUrl), e); return; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/InputStreamZippedJarVisitor.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/InputStreamZippedJarVisitor.java index 7b5f5e9852..26d4346c1a 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/InputStreamZippedJarVisitor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/InputStreamZippedJarVisitor.java @@ -27,9 +27,7 @@ import java.net.URL; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.zip.ZipEntry; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.ejb.EntityManagerLogger; /** @@ -39,8 +37,11 @@ import org.slf4j.LoggerFactory; * @author Emmanuel Bernard */ public class InputStreamZippedJarVisitor extends AbstractJarVisitor { - private final Logger log = LoggerFactory.getLogger( InputStreamZippedJarVisitor.class ); - private String entry; + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); + + private String entry; public InputStreamZippedJarVisitor(URL url, Filter[] filters, String entry) { super( url, filters ); @@ -51,14 +52,15 @@ public class InputStreamZippedJarVisitor extends AbstractJarVisitor { super( fileName, filters ); } - protected void doProcessElements() throws IOException { + @Override + protected void doProcessElements() throws IOException { JarInputStream jis; try { jis = new JarInputStream( jarUrl.openStream() ); } catch (Exception ze) { //really should catch IOException but Eclipse is buggy and raise NPE... - log.warn( "Unable to find file (ignored): " + jarUrl, ze ); + LOG.warn(LOG.unableToFindFile(jarUrl), ze); return; } if ( entry != null && entry.length() == 1 ) entry = null; //no entry diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/JarVisitorFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/JarVisitorFactory.java index a048eada18..a62bc6fca9 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/JarVisitorFactory.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/JarVisitorFactory.java @@ -27,16 +27,16 @@ import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; - +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * @author Emmanuel Bernard */ public class JarVisitorFactory { - private static final Logger log = LoggerFactory.getLogger( JarVisitorFactory.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); /** * Get the JAR URL of the JAR containing the given entry @@ -91,7 +91,7 @@ public class JarVisitorFactory { "Unable to determine JAR Url from " + url + ". Cause: " + e.getMessage() ); } - log.trace("JAR URL from URL Entry: {} >> {}", url, jarUrl); + LOG.trace("JAR URL from URL Entry: " + url + " >> " + jarUrl); return jarUrl; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java index f0550a9870..aee79940c7 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java @@ -40,13 +40,10 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; - import org.hibernate.ejb.AvailableSettings; +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.ejb.util.ConfigurationHelper; import org.hibernate.util.StringHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -63,7 +60,9 @@ import org.xml.sax.SAXParseException; * @author Emmanuel Bernard */ public final class PersistenceXmlLoader { - private static final Logger log = LoggerFactory.getLogger( PersistenceXmlLoader.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); private PersistenceXmlLoader() { } @@ -109,12 +108,12 @@ public final class PersistenceXmlLoader { if (errors.size() == 0) { v2Validator.setErrorHandler( new ErrorLogger( errors ) ); - log.trace("Validate with persistence_2_0.xsd schema on file {}", configURL); + LOG.trace("Validate with persistence_2_0.xsd schema on file " + configURL); v2Validator.validate( new DOMSource( doc ) ); boolean isV1Schema = false; if ( errors.size() != 0 ) { //v2 fails, it could be because the file is v1. - log.trace("Found error with persistence_2_0.xsd schema on file {}", configURL); + LOG.trace("Found error with persistence_2_0.xsd schema on file " + configURL); SAXParseException exception = errors.get( 0 ); final String errorMessage = exception.getMessage(); //is it a validation error due to a v1 schema validated by a v2 @@ -124,7 +123,7 @@ public final class PersistenceXmlLoader { } if (isV1Schema) { - log.trace("Validate with persistence_1_0.xsd schema on file {}", configURL); + LOG.trace("Validate with persistence_1_0.xsd schema on file " + configURL); errors.clear(); v1Validator.setErrorHandler( new ErrorLogger( errors ) ); v1Validator.validate( new DOMSource( doc ) ); @@ -236,7 +235,7 @@ public final class PersistenceXmlLoader { PersistenceMetadata metadata = new PersistenceMetadata(); String puName = top.getAttribute( "name" ); if ( StringHelper.isNotEmpty( puName ) ) { - log.trace( "Persistent Unit name from persistence.xml: {}", puName ); + LOG.trace("Persistent Unit name from persistence.xml: " + puName); metadata.setName( puName ); } NodeList children = top.getChildNodes(); diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/util/NamingHelper.java b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/util/NamingHelper.java index 043e4299c4..d976b70ebe 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/ejb/util/NamingHelper.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/ejb/util/NamingHelper.java @@ -31,66 +31,62 @@ import javax.naming.event.NamespaceChangeListener; import javax.naming.event.NamingEvent; import javax.naming.event.NamingExceptionEvent; import javax.naming.event.NamingListener; - import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; +import org.hibernate.ejb.EntityManagerLogger; import org.hibernate.internal.util.jndi.JndiHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Emmanuel Bernard */ public class NamingHelper { private NamingHelper() {} - private static final Logger log = LoggerFactory.getLogger( NamingHelper.class ); + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); /** bind the configuration to the JNDI */ public static void bind(Ejb3Configuration cfg) { String name = cfg.getHibernateConfiguration().getProperty( AvailableSettings.CONFIGURATION_JNDI_NAME ); - if ( name == null ) { - log.debug( "No JNDI name configured for binding Ejb3Configuration" ); - } + if (name == null) LOG.debug("No JNDI name configured for binding Ejb3Configuration"); else { - log.info( "Ejb3Configuration name: {}", name ); + LOG.ejb3ConfigurationName(name); try { Context ctx = JndiHelper.getInitialContext( cfg.getProperties() ); JndiHelper.bind( ctx, name, cfg ); - log.info( "Bound Ejb3Configuration to JNDI name: {}", name ); + LOG.boundEjb3ConfigurationToJndiName(name); ( (EventContext) ctx ).addNamingListener( name, EventContext.OBJECT_SCOPE, LISTENER ); } catch (InvalidNameException ine) { - log.error( "Invalid JNDI name: " + name, ine ); + LOG.error(LOG.invalidJndiName(name), ine); } catch (NamingException ne) { - log.warn( "Could not bind Ejb3Configuration to JNDI", ne ); + LOG.warn(LOG.unableToBindEjb3ConfigurationToJndi(), ne); } catch (ClassCastException cce) { - log.warn( "InitialContext did not implement EventContext" ); + LOG.initialContextDoesNotImplementEventContext(); } } } private static final NamingListener LISTENER = new NamespaceChangeListener() { public void objectAdded(NamingEvent evt) { - log.debug( "An Ejb3Configuration was successfully bound to name: {}", evt.getNewBinding().getName() ); + LOG.debug("An Ejb3Configuration was successfully bound to name: " + evt.getNewBinding().getName()); } public void objectRemoved(NamingEvent evt) { String name = evt.getOldBinding().getName(); - log.info( "An Ejb3Configuration was unbound from name: {}", name ); + LOG.ejb3ConfigurationUnboundFromName(name); } public void objectRenamed(NamingEvent evt) { String name = evt.getOldBinding().getName(); - log.info( "An Ejb3Configuration was renamed from name: {}", name ); + LOG.ejb3ConfigurationRenamedFromName(name); } public void namingExceptionThrown(NamingExceptionEvent evt) { - log.warn( "Naming exception occurred accessing Ejb3Configuration", evt.getException() ); + LOG.warn(LOG.unableToAccessEjb3Configuration(), evt.getException()); } }; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadingAction.java b/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadingAction.java index f17e529aa6..5912facbd9 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadingAction.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/engine/EJB3CascadingAction.java @@ -21,14 +21,12 @@ */ package org.hibernate.engine; -import java.util.Map; import java.util.Iterator; - -import org.hibernate.event.EventSource; +import java.util.Map; import org.hibernate.HibernateException; +import org.hibernate.ejb.EntityManagerLogger; +import org.hibernate.event.EventSource; import org.hibernate.type.CollectionType; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; /** * Because of CascadingAction constructor visibility @@ -37,29 +35,36 @@ import org.slf4j.Logger; * @author Emmanuel Bernard */ public abstract class EJB3CascadingAction extends CascadingAction { - private static Logger log = LoggerFactory.getLogger( CascadingAction.class ); + + private static final EntityManagerLogger LOG = org.jboss.logging.Logger.getMessageLogger(EntityManagerLogger.class, + EntityManagerLogger.class.getPackage().getName()); /** * @see org.hibernate.Session#persist(Object) */ public static final CascadingAction PERSIST_SKIPLAZY = new CascadingAction() { - public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) + @Override + public void cascade(EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { - log.trace( "cascading to persist: {}", entityName ); + LOG.trace("Cascading to persist: " + entityName); session.persist( entityName, child, (Map) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // persists don't cascade to uninitialized collections return CascadingAction.getLoadedElementsIterator( session, collectionType, collection ); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { return false; } - public boolean performOnLazyProperty() { + @Override + public boolean performOnLazyProperty() { return false; } - public String toString() { + @Override + public String toString() { return "ACTION_PERSIST_SKIPLAZY"; } }; - + } diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Cat.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Cat.java index 850231c4ea..c7425f1036 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Cat.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/Cat.java @@ -1,6 +1,7 @@ //$Id$ package org.hibernate.ejb.test; +import static org.hibernate.ejb.TestEntityManagerLogger.LOG; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; @@ -8,7 +9,6 @@ import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; - import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; @@ -23,9 +23,6 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Emmanuel Bernard */ @@ -33,12 +30,10 @@ import org.slf4j.LoggerFactory; @Entity @EntityListeners( LastUpdateListener.class ) public class Cat implements Serializable { - - private static final Logger log = LoggerFactory.getLogger(Cat.class); private static final List ids = new ArrayList(); // used for assertions public static int postVersion = 0; // used for assertions - + private Integer id; private String name; private Date dateOfBirth; @@ -103,7 +98,7 @@ public class Cat implements Serializable { @PostUpdate private void someLateUpdateWorking() { - log.debug("PostUpdate for: {}", this.toString()); + LOG.debug("PostUpdate for: " + this.toString()); postVersion++; } @@ -136,7 +131,7 @@ public class Cat implements Serializable { public void setLength(long length) { this.length = length; } - + @OneToMany(cascade = CascadeType.ALL) public List getKittens() { return kittens; @@ -150,15 +145,16 @@ public class Cat implements Serializable { * Constructs a String with all attributes * in name = value format. * - * @return a String representation + * @return a String representation * of this object. */ - public String toString() + @Override + public String toString() { final String TAB = " "; - + String retValue = ""; - + retValue = "Cat ( " + super.toString() + TAB + "id = " + this.id + TAB @@ -171,7 +167,7 @@ public class Cat implements Serializable { + "postVersion = " + Cat.postVersion + TAB + "kittens = " + this.kittens + TAB + " )"; - + return retValue; - } + } } 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 fceafbe65b..05c6b3d899 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 @@ -35,15 +35,12 @@ import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.ejb.AvailableSettings; import org.hibernate.ejb.Ejb3Configuration; +import org.hibernate.ejb.TestEntityManagerLogger; import org.hibernate.testing.junit.functional.annotations.HibernateTestCase; /** @@ -53,7 +50,8 @@ import org.hibernate.testing.junit.functional.annotations.HibernateTestCase; * @author Hardy Ferentschik */ public abstract class TestCase extends HibernateTestCase { - private static final Logger log = LoggerFactory.getLogger( TestCase.class ); + + public static final TestEntityManagerLogger LOG = TestEntityManagerLogger.LOG; protected static EntityManagerFactory factory; private EntityManager em; @@ -69,18 +67,19 @@ public abstract class TestCase extends HibernateTestCase { } - public void tearDown() throws Exception { + @Override + public void tearDown() throws Exception { super.tearDown(); } @Override protected void buildConfiguration() throws Exception { Ejb3Configuration ejbconfig = new Ejb3Configuration(); - TestCase.cfg = ejbconfig.getHibernateConfiguration(); + HibernateTestCase.cfg = ejbconfig.getHibernateConfiguration(); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); } - cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); + cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); for ( String mappingFile : getMappings() ) { cfg.addResource( mappingFile ); @@ -95,17 +94,18 @@ public abstract class TestCase extends HibernateTestCase { } if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); - log.warn( "You left an open transaction! Fix your test case. For now, we are closing it for you." ); + LOG.warn("You left an open transaction! Fix your test case. For now, we are closing it for you."); } if ( em.isOpen() ) { // as we open an EM before the test runs, it will still be open if the test uses a custom EM. // or, the person may have forgotten to close. So, do not raise a "fail", but log the fact. em.close(); - log.warn( "The EntityManager is not closed. Closing it." ); + LOG.warn("The EntityManager is not closed. Closing it."); } } - protected void handleUnclosedResources() { + @Override + protected void handleUnclosedResources() { cleanUnclosed( this.em ); for ( Iterator iter = isolatedEms.iterator(); iter.hasNext(); ) { cleanUnclosed( ( EntityManager ) iter.next() ); @@ -114,7 +114,8 @@ public abstract class TestCase extends HibernateTestCase { cfg = null; } - protected void closeResources() { + @Override + protected void closeResources() { if ( factory != null ) { factory.close(); } diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RemoveTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RemoveTest.java index c1f0129f7e..1e85178a52 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RemoveTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/emops/RemoveTest.java @@ -1,22 +1,16 @@ //$Id$ package org.hibernate.ejb.test.emops; -import org.hibernate.StaleObjectStateException; -import org.hibernate.ejb.test.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.OptimisticLockException; -import java.util.Map; +import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class RemoveTest extends TestCase { - private static final Logger log = LoggerFactory.getLogger(RemoveTest.class); - public void testRemove() { Race race = new Race(); race.competitors.add( new Competitor() ); @@ -75,9 +69,9 @@ public class RemoveTest extends TestCase { em2.flush(); fail("should have an optimistic lock exception"); } - + catch( OptimisticLockException e ) { - log.debug("success"); + LOG.debug("success"); } finally { em2.getTransaction().rollback(); @@ -91,7 +85,8 @@ public class RemoveTest extends TestCase { em.close(); } - public Class[] getAnnotatedClasses() { + @Override + public Class[] getAnnotatedClasses() { return new Class[] { Race.class, Competitor.class, @@ -100,7 +95,8 @@ public class RemoveTest extends TestCase { } - public Map getConfig() { + @Override + public Map getConfig() { Map cfg = super.getConfig(); cfg.put( "hibernate.jdbc.batch_size", "0"); return cfg; diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/ExceptionTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/ExceptionTest.java index eed587b113..9ae8323fb6 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/ExceptionTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/exception/ExceptionTest.java @@ -6,10 +6,6 @@ import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cfg.Environment; import org.hibernate.ejb.test.TestCase; import org.hibernate.exception.ConstraintViolationException; @@ -20,8 +16,6 @@ import org.hibernate.exception.ConstraintViolationException; @SuppressWarnings("unchecked") public class ExceptionTest extends TestCase { - private final Logger log = LoggerFactory.getLogger( ExceptionTest.class ); - public void testOptimisticLockingException() throws Exception { EntityManager em = getOrCreateEntityManager(); EntityManager em2 = factory.createEntityManager(); @@ -73,7 +67,7 @@ public class ExceptionTest extends TestCase { fail( "Non existent entity should raise an exception when state is accessed" ); } catch ( EntityNotFoundException e ) { - log.debug( "success" ); + LOG.debug("success"); } finally { em.close(); @@ -131,7 +125,8 @@ public class ExceptionTest extends TestCase { return config; } - public Class[] getAnnotatedClasses() { + @Override + public Class[] getAnnotatedClasses() { return new Class[] { Music.class, Musician.class, Instrument.class }; diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/LockTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/LockTest.java index 8f12986e52..539f4cd705 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/LockTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/lock/LockTest.java @@ -1,18 +1,6 @@ //$Id$ package org.hibernate.ejb.test.lock; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.LockTimeoutException; -import javax.persistence.OptimisticLockException; -import javax.persistence.Query; -import javax.persistence.QueryTimeoutException; - -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.Oracle10gDialect; -import org.hibernate.ejb.AvailableSettings; -import org.hibernate.ejb.test.TestCase; - import java.util.HashMap; import java.util.List; import java.util.Map; @@ -20,15 +8,21 @@ import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.LockTimeoutException; +import javax.persistence.OptimisticLockException; +import javax.persistence.Query; +import javax.persistence.QueryTimeoutException; +import org.hibernate.dialect.HSQLDialect; +import org.hibernate.dialect.Oracle10gDialect; +import org.hibernate.ejb.AvailableSettings; +import org.hibernate.ejb.test.TestCase; /** * @author Emmanuel Bernard */ public class LockTest extends TestCase { - private static final Logger log = LoggerFactory.getLogger( LockTest.class ); public void testFindWithTimeoutHint() { EntityManager em = getOrCreateEntityManager(); @@ -74,7 +68,7 @@ public class LockTest extends TestCase { assertEquals( "surname", lock.getName() ); em.remove( lock ); em.getTransaction().commit(); - + em.close(); } @@ -239,7 +233,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticWriteLock) if ( getDialect() instanceof HSQLDialect) { - log.info("skipping testContendedPessimisticLock"); + LOG.info("skipping testContendedPessimisticLock"); return; } Lock lock = new Lock(); @@ -257,14 +251,14 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testContendedPessimisticLock: got write lock"); + LOG.info("testContendedPessimisticLock: got write lock"); final CountDownLatch latch = new CountDownLatch(1); t = new Thread( new Runnable() { public void run() { try { em2.getTransaction().begin(); - log.info("testContendedPessimisticLock: (BG) about to issue (PESSIMISTIC_READ) query against write-locked entity"); + LOG.info("testContendedPessimisticLock: (BG) about to issue (PESSIMISTIC_READ) query against write-locked entity"); // we should block on the following read Query query = em2.createQuery( "select L from Lock_ L where L.id < 10000 "); @@ -282,11 +276,11 @@ public class LockTest extends TestCase { t.setDaemon( true ); t.setName("LockTest read lock"); t.start(); - log.info("testContendedPessimisticLock: wait on BG thread"); + LOG.info("testContendedPessimisticLock: wait on BG thread"); boolean latchSet = latch.await( 10, TimeUnit.SECONDS ); // latchSet should be false (timeout) because the background thread // shouldn't be able to get a read lock on write locked entity. - log.info("testContendedPessimisticLock: BG thread completed transaction"); + LOG.info("testContendedPessimisticLock: BG thread completed transaction"); assertFalse( "shouldn't be able to get read lock while another transaction has write lock",latchSet ); em.getTransaction().commit(); } @@ -312,7 +306,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testContendedPessimisticReadLockTimeout"); + LOG.info("skipping testContendedPessimisticReadLockTimeout"); return; } Lock lock = new Lock(); @@ -332,18 +326,18 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testContendedPessimisticReadLockTimeout: got write lock"); + LOG.info("testContendedPessimisticReadLockTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { - boolean timedOut = false; // true (success) if LockTimeoutException occurred + boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info("testContendedPessimisticReadLockTimeout: (BG) about to read write-locked entity"); + LOG.info("testContendedPessimisticReadLockTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info("testContendedPessimisticReadLockTimeout: (BG) read write-locked entity"); + LOG.info("testContendedPessimisticReadLockTimeout: (BG) read write-locked entity"); Map props = new HashMap(); // timeout is in milliseconds props.put("javax.persistence.lock.timeout", new Integer(1000)); @@ -352,11 +346,11 @@ public class LockTest extends TestCase { } catch( LockTimeoutException e) { // success - log.info("testContendedPessimisticReadLockTimeout: (BG) got expected timeout exception"); + LOG.info("testContendedPessimisticReadLockTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info("Expected LockTimeoutException but got unexpected exception", e); + LOG.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); @@ -397,7 +391,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testContendedPessimisticWriteLockTimeout"); + LOG.info("skipping testContendedPessimisticWriteLockTimeout"); return; } Lock lock = new Lock(); @@ -417,18 +411,18 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testContendedPessimisticWriteLockTimeout: got write lock"); + LOG.info("testContendedPessimisticWriteLockTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info("testContendedPessimisticWriteLockTimeout: (BG) about to read write-locked entity"); + LOG.info("testContendedPessimisticWriteLockTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info("testContendedPessimisticWriteLockTimeout: (BG) read write-locked entity"); + LOG.info("testContendedPessimisticWriteLockTimeout: (BG) read write-locked entity"); Map props = new HashMap(); // timeout is in milliseconds props.put("javax.persistence.lock.timeout", new Integer(1000)); @@ -437,11 +431,11 @@ public class LockTest extends TestCase { } catch( LockTimeoutException e) { // success - log.info("testContendedPessimisticWriteLockTimeout: (BG) got expected timeout exception"); + LOG.info("testContendedPessimisticWriteLockTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info("Expected LockTimeoutException but got unexpected exception", e); + LOG.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); @@ -482,7 +476,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testContendedPessimisticWriteLockNoWait"); + LOG.info("skipping testContendedPessimisticWriteLockNoWait"); return; } Lock lock = new Lock(); @@ -502,18 +496,18 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testContendedPessimisticWriteLockNoWait: got write lock"); + LOG.info("testContendedPessimisticWriteLockNoWait: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info("testContendedPessimisticWriteLockNoWait: (BG) about to read write-locked entity"); + LOG.info("testContendedPessimisticWriteLockNoWait: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info("testContendedPessimisticWriteLockNoWait: (BG) read write-locked entity"); + LOG.info("testContendedPessimisticWriteLockNoWait: (BG) read write-locked entity"); Map props = new HashMap(); // timeout of zero means no wait (for lock) props.put("javax.persistence.lock.timeout", new Integer(0)); @@ -522,11 +516,11 @@ public class LockTest extends TestCase { } catch( LockTimeoutException e) { // success - log.info("testContendedPessimisticWriteLockNoWait: (BG) got expected timeout exception"); + LOG.info("testContendedPessimisticWriteLockNoWait: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info("Expected LockTimeoutException but got unexpected exception", e); + LOG.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); @@ -567,7 +561,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(); // TODO: replace dialect instanceof test with a Dialect.hasCapability if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testQueryTimeout"); + LOG.info("skipping testQueryTimeout"); return; } Lock lock = new Lock(); @@ -587,18 +581,18 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testQueryTimeout: got write lock"); + LOG.info("testQueryTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info( "testQueryTimeout: (BG) about to read write-locked entity" ); + LOG.info("testQueryTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info( "testQueryTimeout: (BG) read write-locked entity" ); + LOG.info("testQueryTimeout: (BG) read write-locked entity"); try { // we should block on the following read Query query = em2.createQuery( @@ -607,15 +601,15 @@ public class LockTest extends TestCase { query.setHint( "javax.persistence.query.timeout", new Integer(500) ); // 1 sec timeout List resultList = query.getResultList(); String name = resultList.get(0).getName(); // force entity to be read - log.info( "testQueryTimeout: name read =" + name ); + LOG.info("testQueryTimeout: name read =" + name); } catch( QueryTimeoutException e) { // success - log.info( "testQueryTimeout: (BG) got expected timeout exception" ); + LOG.info("testQueryTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info( "testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e ); + LOG.info("testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean( timedOut ); @@ -653,7 +647,7 @@ public class LockTest extends TestCase { public void testQueryTimeoutEMProps() throws Exception { // TODO: replace dialect instanceof test with a Dialect.hasCapability if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testQueryTimeout"); + LOG.info("skipping testQueryTimeout"); return; } EntityManager em = getOrCreateEntityManager(); @@ -677,18 +671,18 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testQueryTimeout: got write lock"); + LOG.info("testQueryTimeout: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info( "testQueryTimeout: (BG) about to read write-locked entity" ); + LOG.info("testQueryTimeout: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info( "testQueryTimeout: (BG) read write-locked entity" ); + LOG.info("testQueryTimeout: (BG) read write-locked entity"); try { // we should block on the following read Query query = em2.createQuery( @@ -696,15 +690,15 @@ public class LockTest extends TestCase { query.setLockMode( LockModeType.PESSIMISTIC_READ ); List resultList = query.getResultList(); String name = resultList.get(0).getName(); // force entity to be read - log.info( "testQueryTimeout: name read =" + name ); + LOG.info("testQueryTimeout: name read =" + name); } catch( QueryTimeoutException e) { // success - log.info( "testQueryTimeout: (BG) got expected timeout exception" ); + LOG.info("testQueryTimeout: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info( "testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e ); + LOG.info("testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean( timedOut ); @@ -748,7 +742,7 @@ public class LockTest extends TestCase { final EntityManager em2 = createIsolatedEntityManager(TimeoutProps); // TODO: replace dialect instanceof test with a Dialect.hasCapability (e.g. supportsPessimisticLockTimeout) if ( ! (getDialect() instanceof Oracle10gDialect)) { - log.info("skipping testLockTimeoutEMProps"); + LOG.info("skipping testLockTimeoutEMProps"); return; } Lock lock = new Lock(); @@ -768,29 +762,29 @@ public class LockTest extends TestCase { em.lock( lock, LockModeType.PESSIMISTIC_WRITE ); final Integer id = lock.getId(); lock.getName(); // force entity to be read - log.info("testLockTimeoutEMProps: got write lock"); + LOG.info("testLockTimeoutEMProps: got write lock"); bgTask = new FutureTask( new Callable() { public Boolean call() { try { boolean timedOut = false; // true (success) if LockTimeoutException occurred em2.getTransaction().begin(); - log.info("testLockTimeoutEMProps: (BG) about to read write-locked entity"); + LOG.info("testLockTimeoutEMProps: (BG) about to read write-locked entity"); // we should block on the following read Lock lock2 = em2.getReference( Lock.class, id ); lock2.getName(); // force entity to be read - log.info("testLockTimeoutEMProps: (BG) read write-locked entity"); + LOG.info("testLockTimeoutEMProps: (BG) read write-locked entity"); // em2 already has javax.persistence.lock.timeout of 1 second applied try { em2.lock( lock2, LockModeType.PESSIMISTIC_WRITE); } catch( LockTimeoutException e) { // success - log.info("testLockTimeoutEMProps: (BG) got expected timeout exception"); + LOG.info("testLockTimeoutEMProps: (BG) got expected timeout exception"); timedOut = true; } catch ( Throwable e) { - log.info("Expected LockTimeoutException but got unexpected exception", e); + LOG.info("Expected LockTimeoutException but got unexpected exception", e); } em2.getTransaction().commit(); return new Boolean(timedOut); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/ClassesAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/ClassesAuditingData.java index a3c3e3bb25..3d8b161d61 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/ClassesAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/ClassesAuditingData.java @@ -1,24 +1,24 @@ package org.hibernate.envers.configuration; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import org.hibernate.MappingException; +import org.hibernate.envers.EnversLogger; import org.hibernate.envers.configuration.metadata.reader.ClassAuditingData; import org.hibernate.envers.configuration.metadata.reader.PropertyAuditingData; import org.hibernate.envers.tools.MappingTools; import org.hibernate.mapping.PersistentClass; -import org.hibernate.MappingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.Collection; -import java.util.LinkedHashMap; /** * A helper class holding auditing meta-data for all persistent classes. * @author Adam Warski (adam at warski dot org) */ public class ClassesAuditingData { - private static final Logger log = LoggerFactory.getLogger(ClassesAuditingData.class); + + public static final EnversLogger LOG = org.jboss.logging.Logger.getMessageLogger(EnversLogger.class, + ClassesAuditingData.class.getPackage().getName()); private final Map entityNameToAuditingData = new HashMap(); private final Map persistentClassToAuditingData = new LinkedHashMap(); @@ -51,7 +51,7 @@ public class ClassesAuditingData { /** * After all meta-data is read, updates calculated fields. This includes: *
    - *
  • setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
  • + *
  • setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
  • *
*/ public void updateCalculatedFields() { @@ -84,9 +84,8 @@ public class ClassesAuditingData { referencedEntityName + "." + propertyName); } - log.debug("Non-insertable property " + referencedEntityName + "." + propertyName + - " will be made insertable because a matching @AuditMappedBy was found in the " + - entityName + " entity."); + LOG.debug("Non-insertable property " + referencedEntityName + "." + propertyName + + " will be made insertable because a matching @AuditMappedBy was found in the " + entityName + " entity."); classAuditingData .getPropertyAuditingData(propertyName) diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/AuditMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/AuditMetadataGenerator.java index 38d7c79dbf..34c5d64923 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/AuditMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/AuditMetadataGenerator.java @@ -26,10 +26,10 @@ package org.hibernate.envers.configuration.metadata; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import org.dom4j.Element; import org.hibernate.MappingException; import org.hibernate.cfg.Configuration; +import org.hibernate.envers.EnversLogger; import org.hibernate.envers.RelationTargetAuditMode; import org.hibernate.envers.configuration.AuditEntitiesConfiguration; import org.hibernate.envers.configuration.GlobalConfiguration; @@ -57,8 +57,6 @@ import org.hibernate.type.ManyToOneType; import org.hibernate.type.OneToOneType; import org.hibernate.type.TimestampType; import org.hibernate.type.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * @author Adam Warski (adam at warski dot org) @@ -68,7 +66,9 @@ import org.slf4j.LoggerFactory; * @author Hernán Chanfreau */ public final class AuditMetadataGenerator { - private static final Logger log = LoggerFactory.getLogger(AuditMetadataGenerator.class); + + public static final EnversLogger LOG = org.jboss.logging.Logger.getMessageLogger(EnversLogger.class, + AuditMetadataGenerator.class.getPackage().getName()); private final Configuration cfg; private final GlobalConfiguration globalCfg; @@ -154,7 +154,7 @@ public final class AuditMetadataGenerator { MetadataTools.addOrModifyColumn(end_rev_mapping, verEntCfg.getRevisionEndFieldName()); any_mapping.add(end_rev_mapping); - + if (verEntCfg.isRevisionEndTimestampEnabled()) { // add a column for the timestamp of the end revision String revisionInfoTimestampSqlType = TimestampType.INSTANCE.getName(); @@ -362,7 +362,7 @@ public final class AuditMetadataGenerator { throw new MappingException("Entity '" + pc.getEntityName() + "' is audited, but its superclass: '" + parentEntityName + "' is not."); } - + ExtendedPropertyMapper parentPropertyMapper = parentConfiguration.getPropertyMapper(); ExtendedPropertyMapper propertyMapper = new SubclassPropertyMapper(new MultiPropertyMapper(), parentPropertyMapper); @@ -382,8 +382,8 @@ public final class AuditMetadataGenerator { if (idMapper == null) { // Unsupported id mapping, e.g. key-many-to-one. If the entity is used in auditing, an exception // will be thrown later on. - log.debug("Unable to create auditing id mapping for entity " + entityName + - ", because of an unsupported Hibernate id mapping (e.g. key-many-to-one)."); + LOG.debug("Unable to create auditing id mapping for entity " + entityName + + ", because of an unsupported Hibernate id mapping (e.g. key-many-to-one)."); return; } @@ -396,7 +396,7 @@ public final class AuditMetadataGenerator { } String entityName = pc.getEntityName(); - log.debug("Generating first-pass auditing mapping for entity " + entityName + "."); + LOG.debug("Generating first-pass auditing mapping for entity " + entityName + "."); String auditEntityName = verEntCfg.getAuditEntityName(entityName); String auditTableName = verEntCfg.getAuditTableName(entityName, pc.getTable().getName()); @@ -454,7 +454,7 @@ public final class AuditMetadataGenerator { xmlMappingData.setClassMapping(class_mapping); // Mapping unjoined properties - addProperties(class_mapping, (Iterator) pc.getUnjoinedPropertyIterator(), propertyMapper, + addProperties(class_mapping, pc.getUnjoinedPropertyIterator(), propertyMapper, auditingData, pc.getEntityName(), xmlMappingData, true); @@ -472,14 +472,14 @@ public final class AuditMetadataGenerator { public void generateSecondPass(PersistentClass pc, ClassAuditingData auditingData, EntityXmlMappingData xmlMappingData) { String entityName = pc.getEntityName(); - log.debug("Generating second-pass auditing mapping for entity " + entityName + "."); + LOG.debug("Generating second-pass auditing mapping for entity " + entityName + "."); CompositeMapperBuilder propertyMapper = entitiesConfigurations.get(entityName).getPropertyMapper(); // Mapping unjoined properties Element parent = xmlMappingData.getClassMapping(); - addProperties(parent, (Iterator) pc.getUnjoinedPropertyIterator(), + addProperties(parent, pc.getUnjoinedPropertyIterator(), propertyMapper, auditingData, entityName, xmlMappingData, false); // Mapping joins (second pass) @@ -531,7 +531,7 @@ public final class AuditMetadataGenerator { * @param allowNotAuditedTarget Are not-audited target entities allowed. * @throws MappingException If a relation from an audited to a non-audited entity is detected, which is not * mapped using {@link RelationTargetAuditMode#NOT_AUDITED}. - * @return The id mapping data of the related entity. + * @return The id mapping data of the related entity. */ IdMappingData getReferencedIdMappingData(String entityName, String referencedEntityName, PropertyAuditingData propertyAuditingData, diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/CollectionMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/CollectionMetadataGenerator.java index 7c33095b37..7557714a80 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/CollectionMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/metadata/CollectionMetadataGenerator.java @@ -32,11 +32,10 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; - import javax.persistence.JoinColumn; - import org.dom4j.Element; import org.hibernate.MappingException; +import org.hibernate.envers.EnversLogger; import org.hibernate.envers.ModificationStore; import org.hibernate.envers.RelationTargetAuditMode; import org.hibernate.envers.configuration.metadata.reader.PropertyAuditingData; @@ -85,8 +84,6 @@ import org.hibernate.type.SetType; import org.hibernate.type.SortedMapType; import org.hibernate.type.SortedSetType; import org.hibernate.type.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Generates metadata for a collection-valued property. @@ -94,7 +91,9 @@ import org.slf4j.LoggerFactory; * @author Hernļæ½n Chanfreau */ public final class CollectionMetadataGenerator { - private static final Logger log = LoggerFactory.getLogger(CollectionMetadataGenerator.class); + + public static final EnversLogger LOG = org.jboss.logging.Logger.getMessageLogger(EnversLogger.class, + CollectionMetadataGenerator.class.getPackage().getName()); private final AuditMetadataGenerator mainGenerator; private final String propertyName; @@ -120,7 +119,7 @@ public final class CollectionMetadataGenerator { * be created using this object. * @param propertyAuditingData Property auditing (meta-)data. Among other things, holds the name of the * property that references the collection in the referencing entity, the user data for middle (join) - * table and the value of the @MapKey annotation, if there was one. + * table and the value of the @MapKey annotation, if there was one. */ public CollectionMetadataGenerator(AuditMetadataGenerator mainGenerator, Collection propertyValue, CompositeMapperBuilder currentMapper, @@ -166,8 +165,7 @@ public final class CollectionMetadataGenerator { @SuppressWarnings({"unchecked"}) private void addOneToManyAttached(boolean fakeOneToManyBidirectional) { - log.debug("Adding audit mapping for property " + referencingEntityName + "." + propertyName + - ": one-to-many collection, using a join column on the referenced entity."); + LOG.debug("Adding audit mapping for property " + referencingEntityName+ "." + propertyName+ ": one-to-many collection, using a join column on the referenced entity."); String mappedBy = getMappedBy(propertyValue); @@ -270,16 +268,16 @@ public final class CollectionMetadataGenerator { // This must be a @JoinColumn+@OneToMany mapping. Generating the table name, as Hibernate doesn't use a // middle table for mapping this relation. return StringTools.getLastComponent(entityName) + "_" + StringTools.getLastComponent(MappingTools.getReferencedEntityName(value.getElement())); - } else { - // Hibernate uses a middle table for mapping this relation, so we get it's name directly. - return value.getCollectionTable().getName(); } + // Hibernate uses a middle table for mapping this relation, so we get it's name directly. + return value.getCollectionTable().getName(); } @SuppressWarnings({"unchecked"}) private void addWithMiddleTable() { - log.debug("Adding audit mapping for property " + referencingEntityName + "." + propertyName + - ": collection with a join table."); + + LOG.debug("Adding audit mapping for property " + referencingEntityName + "." + propertyName + + ": collection with a join table."); // Generating the name of the middle table String auditMiddleTableName; @@ -293,18 +291,18 @@ public final class CollectionMetadataGenerator { auditMiddleEntityName = mainGenerator.getVerEntCfg().getAuditEntityName(middleTableName); } - log.debug("Using join table name: " + auditMiddleTableName); + LOG.debug("Using join table name: " + auditMiddleTableName); // Generating the XML mapping for the middle entity, only if the relation isn't inverse. // If the relation is inverse, will be later checked by comparing middleEntityXml with null. Element middleEntityXml; - if (!propertyValue.isInverse()) { + if (!propertyValue.isInverse()) { // Generating a unique middle entity name auditMiddleEntityName = mainGenerator.getAuditEntityNameRegister().createUnique(auditMiddleEntityName); // Registering the generated name mainGenerator.getAuditEntityNameRegister().register(auditMiddleEntityName); - + middleEntityXml = createMiddleEntityXml(auditMiddleTableName, auditMiddleEntityName, propertyValue.getWhere()); } else { middleEntityXml = null; @@ -557,25 +555,25 @@ public final class CollectionMetadataGenerator { // searching in referenced class String mappedBy = this.searchMappedBy(referencedClass, collectionValue); - + if(mappedBy == null) { - log.debug("Going to search the mapped by attribute for " + propertyName + " in superclasses of entity: " + referencedClass.getClassName()); - + LOG.debug("Going to search the mapped by attribute for " + propertyName + " in superclasses of entity: " + referencedClass.getClassName()); + PersistentClass tempClass = referencedClass; while ((mappedBy == null) && (tempClass.getSuperclass() != null)) { - log.debug("Searching in superclass: " + tempClass.getSuperclass().getClassName()); + LOG.debug("Searching in superclass: " + tempClass.getSuperclass().getClassName()); mappedBy = this.searchMappedBy(tempClass.getSuperclass(), collectionValue); tempClass = tempClass.getSuperclass(); } } - if(mappedBy == null) { + if(mappedBy == null) { throw new MappingException("Unable to read the mapped by attribute for " + propertyName + " in " + referencedClass.getClassName() + "!"); } - + return mappedBy; - } + } @SuppressWarnings({"unchecked"}) private String searchMappedBy(PersistentClass referencedClass, Collection collectionValue) { @@ -587,7 +585,7 @@ public final class CollectionMetadataGenerator { collectionValue.getKey().getColumnIterator())) { return property.getName(); } - } + } return null; } @@ -602,25 +600,26 @@ public final class CollectionMetadataGenerator { String mappedBy = this.searchMappedBy(referencedClass, collectionTable); // not found on referenced class, searching on superclasses - if(mappedBy == null) { - log.debug("Going to search the mapped by attribute for " + propertyName + " in superclases of entity: " + referencedClass.getClassName()); + if(mappedBy == null) { + LOG.debug("Going to search the mapped by attribute for " + propertyName + " in superclasses of entity: " + + referencedClass.getClassName()); PersistentClass tempClass = referencedClass; while ((mappedBy == null) && (tempClass.getSuperclass() != null)) { - log.debug("Searching in superclass: " + tempClass.getSuperclass().getClassName()); + LOG.debug("Searching in superclass: " + tempClass.getSuperclass().getClassName()); mappedBy = this.searchMappedBy(tempClass.getSuperclass(), collectionTable); tempClass = tempClass.getSuperclass(); } } - if(mappedBy == null) { + if(mappedBy == null) { throw new MappingException("Unable to read the mapped by attribute for " + propertyName + " in " + referencedClass.getClassName() + "!"); } - + return mappedBy; } - + @SuppressWarnings({"unchecked"}) private String searchMappedBy(PersistentClass referencedClass, Table collectionTable) { Iterator properties = referencedClass.getPropertyIterator(); @@ -633,8 +632,8 @@ public final class CollectionMetadataGenerator { return property.getName(); } } - } + } return null; } - + } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/reader/FirstLevelCache.java b/hibernate-envers/src/main/java/org/hibernate/envers/reader/FirstLevelCache.java index f21bb84b1f..f8303cd985 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/reader/FirstLevelCache.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/reader/FirstLevelCache.java @@ -23,14 +23,11 @@ */ package org.hibernate.envers.reader; -import static org.hibernate.envers.tools.Tools.newHashMap; -import static org.hibernate.envers.tools.Triple.make; - +import static org.hibernate.envers.tools.Tools.newHashMap; +import static org.hibernate.envers.tools.Triple.make; import java.util.Map; - +import org.hibernate.envers.EnversLogger; import org.hibernate.envers.tools.Triple; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * First level cache for versioned entities, versions reader-scoped. Each entity is uniquely identified by a @@ -39,15 +36,17 @@ import org.slf4j.LoggerFactory; * @author Hernán Chanfreau */ public class FirstLevelCache { - - private static final Logger log = LoggerFactory.getLogger(FirstLevelCache.class); + + public static final EnversLogger LOG = org.jboss.logging.Logger.getMessageLogger(EnversLogger.class, + FirstLevelCache.class.getPackage().getName()); + /** * cache for resolve an object for a given id, revision and entityName. */ private final Map, Object> cache; /** - * used to resolve the entityName for a given id, revision and entity. + * used to resolve the entityName for a given id, revision and entity. */ private final Map, String> entityNameCache; @@ -57,59 +56,47 @@ public class FirstLevelCache { } public Object get(String entityName, Number revision, Object id) { - if (log.isDebugEnabled()) { - log.debug("Resolving object from First Level Cache: " - + "EntytiName:" + entityName + " - primaryKey:" + id - + " - revision:" + revision); - } + LOG.debug("Resolving object from First Level Cache: " + "EntityName:" + entityName + " - primaryKey:" + id + " - revision:" + + revision); return cache.get(make(entityName, revision, id)); } public void put(String entityName, Number revision, Object id, Object entity) { - if (log.isDebugEnabled()) { - log.debug("Caching entity on First Level Cache: " - + " - primaryKey:" + id + " - revision:" + revision - + " - entityName:" + entityName); - } + LOG.debug("Caching entity on First Level Cache: " + " - primaryKey:" + id + " - revision:" + revision + " - entityName:" + + entityName); cache.put(make(entityName, revision, id), entity); } public boolean contains(String entityName, Number revision, Object id) { return cache.containsKey(make(entityName, revision, id)); } - + /** - * Adds the entityName into the cache. The key is a triple make with primaryKey, revision and entity + * Adds the entityName into the cache. The key is a triple make with primaryKey, revision and entity * @param entityName, value of the cache * @param id, primaryKey * @param revision, revision number * @param entity, object retrieved by envers */ public void putOnEntityNameCache(Object id, Number revision, Object entity, String entityName) { - if (log.isDebugEnabled()) { - log.debug("Caching entityName on First Level Cache: " - + " - primaryKey:" + id + " - revision:" + revision - + " - entity:" + entity.getClass().getName() + " -> entityName:" + entityName); - } + LOG.debug("Caching entityName on First Level Cache: " + " - primaryKey:" + id + " - revision:" + revision + " - entity:" + + entity.getClass().getName() + " -> entityName:" + entityName); entityNameCache.put(make(id, revision, entity), entityName); } - + /** - * Gets the entityName from the cache. The key is a triple make with primaryKey, revision and entity + * Gets the entityName from the cache. The key is a triple make with primaryKey, revision and entity * @param entityName, value of the cache * @param id, primaryKey * @param revision, revision number * @param entity, object retrieved by envers - */ + */ public String getFromEntityNameCache(Object id, Number revision, Object entity) { - if (log.isDebugEnabled()) { - log.debug("Trying to resolve entityName from First Level Cache:" - + " - primaryKey:" + id + " - revision:" + revision - + " - entity:" + entity); - } - return entityNameCache.get(make(id, revision, entity)); + LOG.debug("Trying to resolve entityName from First Level Cache:" + " - primaryKey:" + id + " - revision:" + revision + + " - entity:" + entity); + return entityNameCache.get(make(id, revision, entity)); } - + /** * @param id * , primaryKey @@ -120,6 +107,6 @@ public class FirstLevelCache { * @return true if entityNameCache contains the triple */ public boolean containsEntityName(Object id, Number revision, Object entity) { - return entityNameCache.containsKey(make(id, revision, entity)); - } + return entityNameCache.containsKey(make(id, revision, entity)); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java index 8b92a1cf50..4c40355439 100755 --- a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java @@ -1,25 +1,26 @@ package org.hibernate.envers.strategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.envers.EnversLogger; /** * Deprecated Audit strategy class. - * + * * @author Stephanie Pau * @author Adam Warski (adam at warski dot org) - * + * * @deprecated use {@link ValidityAuditStrategy} instead. */ +@Deprecated public class ValidTimeAuditStrategy extends ValidityAuditStrategy { - private final Logger log = LoggerFactory.getLogger(ValidTimeAuditStrategy.class); + public static final EnversLogger LOG = org.jboss.logging.Logger.getMessageLogger(EnversLogger.class, + ValidTimeAuditStrategy.class.getPackage().getName()); /** * Default constructor. Log a warn message that this class is deprecated. */ public ValidTimeAuditStrategy() { - log.warn("ValidTimeAuditStrategy is deprecated, please use ValidityAuditStrategy instead"); + LOG.validTimeAuditStrategyDeprecated(); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java index 395bf276e6..41a7f15dd0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java @@ -23,33 +23,28 @@ */ package org.hibernate.envers.test.integration.components; +import static org.hibernate.envers.TestEnversLogger.LOG; import java.math.BigInteger; import java.util.Arrays; - import javax.persistence.EntityManager; - import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.envers.test.AbstractEntityTest; import org.hibernate.envers.test.entities.components.DefaultValueComponent1; import org.hibernate.envers.test.entities.components.DefaultValueComponent2; import org.hibernate.envers.test.entities.components.DefaultValueComponentTestEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test class for components with default values. - * + * * @see * Hibernate JIRA - * + * * @author Erik-Berndt Scheper */ public class DefaultValueComponents extends AbstractEntityTest { - private static final Logger log = LoggerFactory - .getLogger(DefaultValueComponents.class); private Integer id0; private Integer id1; @@ -59,7 +54,8 @@ public class DefaultValueComponents extends AbstractEntityTest { private Integer id5; private Integer id6; - public void configure(Ejb3Configuration cfg) { + @Override + public void configure(Ejb3Configuration cfg) { cfg.addAnnotatedClass(DefaultValueComponentTestEntity.class); } @@ -140,19 +136,19 @@ public class DefaultValueComponents extends AbstractEntityTest { @Test public void testRevisionsCounts() { - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id0).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id1).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id2).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id3).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id4).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id5).toString()); - log.error(getAuditReader().getRevisions( + LOG.error(getAuditReader().getRevisions( DefaultValueComponentTestEntity.class, id6).toString()); assert Arrays.asList(1, 2).equals( @@ -192,9 +188,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id0, 2); - log.error("------------ id0 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id0 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); checkCorrectlyPersisted(id0, null, null); @@ -215,9 +211,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id1, 2); - log.error("------------ id1 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id1 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); checkCorrectlyPersisted(id1, null, "upd-c2-str1"); @@ -239,9 +235,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id2, 2); - log.error("------------ id2 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id2 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity .of(id2, DefaultValueComponent1.of("c1-str1", @@ -262,9 +258,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id3, 2); - log.error("------------ id3 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id3 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity .of(id3, DefaultValueComponent1.of(null, DefaultValueComponent2 @@ -285,9 +281,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id4, 2); - log.error("------------ id4 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id4 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity .of(id4, DefaultValueComponent1.of(null, DefaultValueComponent2 @@ -308,9 +304,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id5, 2); - log.error("------------ id5 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id5 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity .of(id5, DefaultValueComponent1.of(null, DefaultValueComponent2 @@ -331,9 +327,9 @@ public class DefaultValueComponents extends AbstractEntityTest { DefaultValueComponentTestEntity ent2 = getAuditReader().find( DefaultValueComponentTestEntity.class, id6, 2); - log.error("------------ id6 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + LOG.error("------------ id6 -------------"); + LOG.error(ent1.toString()); + LOG.error(ent2.toString()); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity .of(id6, DefaultValueComponent1.of(null, null)); 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 7f959ab380..741da6df22 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 @@ -24,7 +24,6 @@ package org.hibernate.test.cache.infinispan; import java.util.Set; - import org.hibernate.cache.GeneralDataRegion; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.Region; @@ -36,167 +35,166 @@ import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of QueryResultsRegion and TimestampsRegion. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionImplTestCase { - protected static final String KEY = "Key"; + protected static final String KEY = "Key"; - protected static final String VALUE1 = "value1"; - protected static final String VALUE2 = "value2"; + protected static final String VALUE1 = "value1"; + protected static final String VALUE2 = "value2"; - public AbstractGeneralDataRegionTestCase(String name) { - super(name); - } + public AbstractGeneralDataRegionTestCase( String name ) { + super(name); + } - @Override - protected void putInRegion(Region region, Object key, Object value) { - ((GeneralDataRegion) region).put(key, value); - } + @Override + protected void putInRegion( Region region, + Object key, + Object value ) { + ((GeneralDataRegion)region).put(key, value); + } - @Override - protected void removeFromRegion(Region region, Object key) { - ((GeneralDataRegion) region).evict(key); - } + @Override + protected void removeFromRegion( Region region, + Object key ) { + ((GeneralDataRegion)region).evict(key); + } - /** - * Test method for {@link QueryResultsRegion#evict(java.lang.Object)}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * CollectionRegionAccessStrategy API. - */ - public void testEvict() throws Exception { - evictOrRemoveTest(); - } + /** + * Test method for {@link QueryResultsRegion#evict(java.lang.Object)}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the CollectionRegionAccessStrategy API. + */ + public void testEvict() throws Exception { + evictOrRemoveTest(); + } - private void evictOrRemoveTest() throws Exception { - Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport() - ); - CacheAdapter localCache = getInfinispanCache(regionFactory); - boolean invalidation = localCache.isClusteredInvalidation(); + private void evictOrRemoveTest() throws Exception { + Configuration cfg = createConfiguration(); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); + CacheAdapter localCache = getInfinispanCache(regionFactory); + boolean invalidation = localCache.isClusteredInvalidation(); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - GeneralDataRegion localRegion = (GeneralDataRegion) createRegion(regionFactory, - getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); + GeneralDataRegion localRegion = (GeneralDataRegion)createRegion(regionFactory, + getStandardRegionName(REGION_PREFIX), + cfg.getProperties(), + null); - cfg = createConfiguration(); - regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport() - ); + cfg = createConfiguration(); + regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); - GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory, - getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); + GeneralDataRegion remoteRegion = (GeneralDataRegion)createRegion(regionFactory, + getStandardRegionName(REGION_PREFIX), + cfg.getProperties(), + null); - assertNull("local is clean", localRegion.get(KEY)); - assertNull("remote is clean", remoteRegion.get(KEY)); + assertNull("local is clean", localRegion.get(KEY)); + assertNull("remote is clean", remoteRegion.get(KEY)); - localRegion.put(KEY, VALUE1); - assertEquals(VALUE1, localRegion.get(KEY)); + localRegion.put(KEY, VALUE1); + assertEquals(VALUE1, localRegion.get(KEY)); - // allow async propagation - sleep(250); - Object expected = invalidation ? null : VALUE1; - assertEquals(expected, remoteRegion.get(KEY)); + // allow async propagation + sleep(250); + Object expected = invalidation ? null : VALUE1; + assertEquals(expected, remoteRegion.get(KEY)); - localRegion.evict(KEY); + localRegion.evict(KEY); - // allow async propagation - sleep(250); - assertEquals(null, localRegion.get(KEY)); - assertEquals(null, remoteRegion.get(KEY)); - } + // allow async propagation + sleep(250); + assertEquals(null, localRegion.get(KEY)); + assertEquals(null, remoteRegion.get(KEY)); + } - protected abstract String getStandardRegionName(String regionPrefix); + protected abstract String getStandardRegionName( String regionPrefix ); - /** - * Test method for {@link QueryResultsRegion#evictAll()}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * CollectionRegionAccessStrategy API. - */ - public void testEvictAll() throws Exception { - evictOrRemoveAllTest("entity"); - } + /** + * Test method for {@link QueryResultsRegion#evictAll()}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the CollectionRegionAccessStrategy API. + */ + public void testEvictAll() throws Exception { + evictOrRemoveAllTest("entity"); + } - private void evictOrRemoveAllTest(String configName) throws Exception { - Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport() - ); - CacheAdapter localCache = getInfinispanCache(regionFactory); + private void evictOrRemoveAllTest( String configName ) throws Exception { + Configuration cfg = createConfiguration(); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); + CacheAdapter localCache = getInfinispanCache(regionFactory); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - GeneralDataRegion localRegion = (GeneralDataRegion) createRegion(regionFactory, - getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); + GeneralDataRegion localRegion = (GeneralDataRegion)createRegion(regionFactory, + getStandardRegionName(REGION_PREFIX), + cfg.getProperties(), + null); - cfg = createConfiguration(); - regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport() - ); - CacheAdapter remoteCache = getInfinispanCache(regionFactory); + cfg = createConfiguration(); + regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); + CacheAdapter remoteCache = getInfinispanCache(regionFactory); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory, - getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null); + GeneralDataRegion remoteRegion = (GeneralDataRegion)createRegion(regionFactory, + getStandardRegionName(REGION_PREFIX), + cfg.getProperties(), + null); - Set keys = localCache.keySet(); - assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); + Set keys = localCache.keySet(); + assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); - keys = remoteCache.keySet(); - assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); + keys = remoteCache.keySet(); + assertEquals("No valid children in " + keys, 0, getValidKeyCount(keys)); - assertNull("local is clean", localRegion.get(KEY)); - assertNull("remote is clean", remoteRegion.get(KEY)); + assertNull("local is clean", localRegion.get(KEY)); + assertNull("remote is clean", remoteRegion.get(KEY)); - localRegion.put(KEY, VALUE1); - assertEquals(VALUE1, localRegion.get(KEY)); + localRegion.put(KEY, VALUE1); + assertEquals(VALUE1, localRegion.get(KEY)); - // Allow async propagation - sleep(250); + // Allow async propagation + sleep(250); - remoteRegion.put(KEY, VALUE1); - assertEquals(VALUE1, remoteRegion.get(KEY)); + remoteRegion.put(KEY, VALUE1); + assertEquals(VALUE1, remoteRegion.get(KEY)); - // Allow async propagation - sleep(250); + // Allow async propagation + sleep(250); - localRegion.evictAll(); + localRegion.evictAll(); - // allow async propagation - sleep(250); - // This should re-establish the region root node in the optimistic case - assertNull(localRegion.get(KEY)); - assertEquals("No valid children in " + keys, 0, getValidKeyCount(localCache.keySet())); + // allow async propagation + sleep(250); + // This should re-establish the region root node in the optimistic case + assertNull(localRegion.get(KEY)); + assertEquals("No valid children in " + keys, 0, getValidKeyCount(localCache.keySet())); - // Re-establishing the region root on the local node doesn't - // propagate it to other nodes. Do a get on the remote node to re-establish - // This only adds a node in the case of optimistic locking - assertEquals(null, remoteRegion.get(KEY)); - assertEquals("No valid children in " + keys, 0, getValidKeyCount(remoteCache.keySet())); + // Re-establishing the region root on the local node doesn't + // propagate it to other nodes. Do a get on the remote node to re-establish + // This only adds a node in the case of optimistic locking + assertEquals(null, remoteRegion.get(KEY)); + assertEquals("No valid children in " + keys, 0, getValidKeyCount(remoteCache.keySet())); - assertEquals("local is clean", null, localRegion.get(KEY)); - assertEquals("remote is clean", null, remoteRegion.get(KEY)); - } + assertEquals("local is clean", null, localRegion.get(KEY)); + assertEquals("remote is clean", null, remoteRegion.get(KEY)); + } - protected Configuration createConfiguration() { - Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, false, true); - return cfg; - } + protected Configuration createConfiguration() { + Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, false, true); + return cfg; + } - protected void rollback() { - try { - BatchModeTransactionManager.getInstance().rollback(); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - } -} \ No newline at end of file + protected void rollback() { + try { + BatchModeTransactionManager.getInstance().rollback(); + } catch (Exception e) { + TestInfinispanLogger.LOG.error(e.getMessage(), e); + } + } +} 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 84ffd1264b..9cf93a254e 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 @@ -24,48 +24,40 @@ package org.hibernate.test.cache.infinispan; 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.hibernate.testing.junit.UnitTestCase; import org.infinispan.Cache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Base class for all non-functional tests of Infinispan integration. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public abstract class AbstractNonFunctionalTestCase extends UnitTestCase { public static final String REGION_PREFIX = "test"; - + private CacheTestSupport testSupport; - protected final Logger log = LoggerFactory.getLogger(getClass()); - + public AbstractNonFunctionalTestCase(String name) { super(name); - testSupport = new CacheTestSupport(log); + testSupport = new CacheTestSupport(); } @Override protected void setUp() throws Exception { super.setUp(); - + testSupport.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); - + testSupport.tearDown(); } @@ -94,10 +86,10 @@ public abstract class AbstractNonFunctionalTestCase extends UnitTestCase { Thread.sleep(ms); } catch (InterruptedException e) { - log.warn("Interrupted during sleep", e); + TestInfinispanLogger.LOG.warn("Interrupted during sleep", e); } } - + protected void avoidConcurrentFlush() { testSupport.avoidConcurrentFlush(); } 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 fbcb986521..8b73258062 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 @@ -23,23 +23,18 @@ */ package org.hibernate.test.cache.infinispan.collection; -import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; - +import javax.transaction.TransactionManager; import junit.extensions.TestSetup; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; - import org.hibernate.cache.CacheDataDescription; -import org.hibernate.cache.CacheException; import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.access.AccessType; import org.hibernate.cache.access.CollectionRegionAccessStrategy; @@ -50,540 +45,529 @@ import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate; import org.hibernate.cache.infinispan.collection.CollectionRegionImpl; import org.hibernate.cache.infinispan.impl.BaseRegion; 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.TestInfinispanLogger; 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; -import javax.transaction.TransactionManager; - /** * Base class for tests of CollectionRegionAccessStrategy impls. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends AbstractNonFunctionalTestCase { - public static final String REGION_NAME = "test/com.foo.test"; - public static final String KEY_BASE = "KEY"; - public static final String VALUE1 = "VALUE1"; - public static final String VALUE2 = "VALUE2"; + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - protected static int testCount; + public static final String REGION_NAME = "test/com.foo.test"; + public static final String KEY_BASE = "KEY"; + public static final String VALUE1 = "VALUE1"; + public static final String VALUE2 = "VALUE2"; - protected static Configuration localCfg; - protected static InfinispanRegionFactory localRegionFactory; - protected CacheAdapter localCache; - protected static Configuration remoteCfg; - protected static InfinispanRegionFactory remoteRegionFactory; - protected CacheAdapter remoteCache; + protected static int testCount; - protected CollectionRegion localCollectionRegion; - protected CollectionRegionAccessStrategy localAccessStrategy; + protected static Configuration localCfg; + protected static InfinispanRegionFactory localRegionFactory; + protected CacheAdapter localCache; + protected static Configuration remoteCfg; + protected static InfinispanRegionFactory remoteRegionFactory; + protected CacheAdapter remoteCache; - protected CollectionRegion remoteCollectionRegion; - protected CollectionRegionAccessStrategy remoteAccessStrategy; + protected CollectionRegion localCollectionRegion; + protected CollectionRegionAccessStrategy localAccessStrategy; - protected boolean invalidation; - protected boolean synchronous; + protected CollectionRegion remoteCollectionRegion; + protected CollectionRegionAccessStrategy remoteAccessStrategy; - protected Exception node1Exception; - protected Exception node2Exception; + protected boolean invalidation; + protected boolean synchronous; - protected AssertionFailedError node1Failure; - protected AssertionFailedError node2Failure; + protected Exception node1Exception; + protected Exception node2Exception; - public static Test getTestSetup(Class testClass, String configName) { - TestSuite suite = new TestSuite(testClass); - return new AccessStrategyTestSetup(suite, configName); - } + protected AssertionFailedError node1Failure; + protected AssertionFailedError node2Failure; - public static Test getTestSetup(Test test, String configName) { - return new AccessStrategyTestSetup(test, configName); - } + public static Test getTestSetup( Class testClass, + String configName ) { + TestSuite suite = new TestSuite(testClass); + return new AccessStrategyTestSetup(suite, configName); + } - /** - * Create a new TransactionalAccessTestCase. - * - * @param name - */ - public AbstractCollectionRegionAccessStrategyTestCase(String name) { - super(name); - } + public static Test getTestSetup( Test test, + String configName ) { + return new AccessStrategyTestSetup(test, configName); + } - protected abstract AccessType getAccessType(); + /** + * Create a new TransactionalAccessTestCase. + * + * @param name + */ + public AbstractCollectionRegionAccessStrategyTestCase( String name ) { + super(name); + } - protected void setUp() throws Exception { - super.setUp(); + protected abstract AccessType getAccessType(); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + @Override + protected void setUp() throws Exception { + super.setUp(); - localCollectionRegion = localRegionFactory.buildCollectionRegion(REGION_NAME, localCfg.getProperties(), - getCacheDataDescription()); - localCache = ((BaseRegion) localCollectionRegion).getCacheAdapter(); - localAccessStrategy = localCollectionRegion.buildAccessStrategy(getAccessType()); - invalidation = localCache.isClusteredInvalidation(); - synchronous = localCache.isSynchronous(); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + localCollectionRegion = localRegionFactory.buildCollectionRegion(REGION_NAME, + localCfg.getProperties(), + getCacheDataDescription()); + localCache = ((BaseRegion)localCollectionRegion).getCacheAdapter(); + localAccessStrategy = localCollectionRegion.buildAccessStrategy(getAccessType()); + invalidation = localCache.isClusteredInvalidation(); + synchronous = localCache.isSynchronous(); - remoteCollectionRegion = remoteRegionFactory.buildCollectionRegion(REGION_NAME, remoteCfg.getProperties(), - getCacheDataDescription()); - remoteCache = ((BaseRegion) remoteCollectionRegion).getCacheAdapter(); - remoteAccessStrategy = remoteCollectionRegion.buildAccessStrategy(getAccessType()); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - node1Exception = null; - node2Exception = null; + remoteCollectionRegion = remoteRegionFactory.buildCollectionRegion(REGION_NAME, + remoteCfg.getProperties(), + getCacheDataDescription()); + remoteCache = ((BaseRegion)remoteCollectionRegion).getCacheAdapter(); + remoteAccessStrategy = remoteCollectionRegion.buildAccessStrategy(getAccessType()); - node1Failure = null; - node2Failure = null; - } + node1Exception = null; + node2Exception = null; - protected void tearDown() throws Exception { + node1Failure = null; + node2Failure = null; + } - super.tearDown(); + @Override + protected void tearDown() throws Exception { - try { - localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); - } catch (Exception e) { - log.error("Problem purging local cache", e); - } + super.tearDown(); - try { - remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); - } catch (Exception e) { - log.error("Problem purging remote cache", e); - } + try { + localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); + } catch (Exception e) { + LOG.error("Problem purging local cache", e); + } - node1Exception = null; - node2Exception = null; + try { + remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); + } catch (Exception e) { + LOG.error("Problem purging remote cache", e); + } - node1Failure = null; - node2Failure = null; - } + node1Exception = null; + node2Exception = null; - protected static Configuration createConfiguration(String configName, String configResource) { - Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); - cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); - return cfg; - } + node1Failure = null; + node2Failure = null; + } - protected CacheDataDescription getCacheDataDescription() { - return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); - } + protected static Configuration createConfiguration( String configName, + String configResource ) { + Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); + cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); + return cfg; + } - protected boolean isUsingInvalidation() { - return invalidation; - } + protected CacheDataDescription getCacheDataDescription() { + return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); + } - protected boolean isSynchronous() { - return synchronous; - } + protected boolean isUsingInvalidation() { + return invalidation; + } - /** - * This is just a setup test where we assert that the cache config is as we expected. - */ - public abstract void testCacheConfiguration(); + protected boolean isSynchronous() { + return synchronous; + } - /** - * Test method for {@link CollectionRegionAccessStrategy#getRegion()}. - */ - public void testGetRegion() { - assertEquals("Correct region", localCollectionRegion, localAccessStrategy.getRegion()); - } + /** + * This is just a setup test where we assert that the cache config is as we expected. + */ + public abstract void testCacheConfiguration(); - public void testPutFromLoadRemoveDoesNotProduceStaleData() throws Exception { - final CountDownLatch pferLatch = new CountDownLatch(1); - final CountDownLatch removeLatch = new CountDownLatch(1); - TransactionManager tm = DualNodeJtaTransactionManagerImpl.getInstance("test1234"); - PutFromLoadValidator validator = new PutFromLoadValidator(tm) { - @Override - public boolean acquirePutFromLoadLock(Object key) { - boolean acquired = super.acquirePutFromLoadLock(key); - try { - removeLatch.countDown(); - pferLatch.await(2, TimeUnit.SECONDS); - } catch (InterruptedException e) { - log.debug("Interrupted"); - Thread.currentThread().interrupt(); - } catch (Exception e) { - log.error("Error", e); - throw new RuntimeException("Error", e); + /** + * Test method for {@link CollectionRegionAccessStrategy#getRegion()}. + */ + public void testGetRegion() { + assertEquals("Correct region", localCollectionRegion, localAccessStrategy.getRegion()); + } + + public void testPutFromLoadRemoveDoesNotProduceStaleData() throws Exception { + final CountDownLatch pferLatch = new CountDownLatch(1); + final CountDownLatch removeLatch = new CountDownLatch(1); + TransactionManager tm = DualNodeJtaTransactionManagerImpl.getInstance("test1234"); + PutFromLoadValidator validator = new PutFromLoadValidator(tm) { + @Override + public boolean acquirePutFromLoadLock( Object key ) { + boolean acquired = super.acquirePutFromLoadLock(key); + try { + removeLatch.countDown(); + pferLatch.await(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOG.debug("Interrupted"); + Thread.currentThread().interrupt(); + } catch (Exception e) { + LOG.error("Error", e); + throw new RuntimeException("Error", e); + } + return acquired; } - return acquired; - } - }; - final TransactionalAccessDelegate delegate = new TransactionalAccessDelegate((CollectionRegionImpl) localCollectionRegion, validator); + }; + final TransactionalAccessDelegate delegate = new TransactionalAccessDelegate((CollectionRegionImpl)localCollectionRegion, + validator); - Callable pferCallable = new Callable() { - public Void call() throws Exception { - delegate.putFromLoad("k1", "v1", 0, null); - return null; - } - }; + Callable pferCallable = new Callable() { + public Void call() throws Exception { + delegate.putFromLoad("k1", "v1", 0, null); + return null; + } + }; - Callable removeCallable = new Callable() { - public Void call() throws Exception { - removeLatch.await(); - delegate.remove("k1"); - pferLatch.countDown(); - return null; - } - }; + Callable removeCallable = new Callable() { + public Void call() throws Exception { + removeLatch.await(); + delegate.remove("k1"); + pferLatch.countDown(); + return null; + } + }; - ExecutorService executorService = Executors.newCachedThreadPool(); - Future pferFuture = executorService.submit(pferCallable); - Future removeFuture = executorService.submit(removeCallable); + ExecutorService executorService = Executors.newCachedThreadPool(); + Future pferFuture = executorService.submit(pferCallable); + Future removeFuture = executorService.submit(removeCallable); - pferFuture.get(); - removeFuture.get(); + pferFuture.get(); + removeFuture.get(); - assertFalse(localCache.containsKey("k1")); - } + assertFalse(localCache.containsKey("k1")); + } - /** - * Test method for - * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} - * . - */ - public void testPutFromLoad() throws Exception { - putFromLoadTest(false); - } + /** + * Test method for + * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} . + */ + public void testPutFromLoad() throws Exception { + putFromLoadTest(false); + } - /** - * Test method for - * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} - * . - */ - public void testPutFromLoadMinimal() throws Exception { - putFromLoadTest(true); - } + /** + * Test method for + * {@link CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} . + */ + public void testPutFromLoadMinimal() throws Exception { + putFromLoadTest(true); + } - /** - * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First - * does a putFromLoad, then an evict (to represent a change). Second tries to do a putFromLoad - * with stale data (i.e. it took longer to read from the db). Both commit their tx. Then both - * start a new tx and get. First should see the updated data; second should either see the - * updated data (isInvalidation()( == false) or null (isInvalidation() == true). - * - * @param useMinimalAPI - * @throws Exception - */ - private void putFromLoadTest(final boolean useMinimalAPI) throws Exception { + /** + * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First does a putFromLoad, then an + * evict (to represent a change). Second tries to do a putFromLoad with stale data (i.e. it took longer to read from the db). + * Both commit their tx. Then both start a new tx and get. First should see the updated data; second should either see the + * updated data (isInvalidation()( == false) or null (isInvalidation() == true). + * + * @param useMinimalAPI + * @throws Exception + */ + private void putFromLoadTest( final boolean useMinimalAPI ) throws Exception { - final String KEY = KEY_BASE + testCount++; + final String KEY = KEY_BASE + testCount++; - final CountDownLatch writeLatch1 = new CountDownLatch(1); - final CountDownLatch writeLatch2 = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(2); + final CountDownLatch writeLatch1 = new CountDownLatch(1); + final CountDownLatch writeLatch2 = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(2); - Thread node1 = new Thread() { + Thread node1 = new Thread() { - public void run() { + @Override + public void run() { + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); + + assertEquals("node1 starts clean", null, localAccessStrategy.get(KEY, txTimestamp)); + + writeLatch1.await(); + + if (useMinimalAPI) { + localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2), true); + } else { + localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2)); + } + + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + // Let node2 write + writeLatch2.countDown(); + completionLatch.countDown(); + } + } + }; + + Thread node2 = new Thread() { + + @Override + public void run() { + + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); + + assertNull("node2 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); + + // Let node1 write + writeLatch1.countDown(); + // Wait for node1 to finish + writeLatch2.await(); + + // Let the first PFER propagate + sleep(200); + + if (useMinimalAPI) { + remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); + } else { + remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); + } + + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node2 caught exception", e); + node2Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node2Failure = e; + rollback(); + } finally { + completionLatch.countDown(); + } + } + }; + + node1.setDaemon(true); + node2.setDaemon(true); + + node1.start(); + node2.start(); + + assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); + + if (node1Failure != null) throw node1Failure; + if (node2Failure != null) throw node2Failure; + + assertEquals("node1 saw no exceptions", null, node1Exception); + assertEquals("node2 saw no exceptions", null, node2Exception); + + // let the final PFER propagate + sleep(100); + + long txTimestamp = System.currentTimeMillis(); + String msg1 = "Correct node1 value"; + String msg2 = "Correct node2 value"; + Object expected1 = null; + Object expected2 = null; + if (isUsingInvalidation()) { + // PFER does not generate any invalidation, so each node should + // succeed. We count on database locking and Hibernate removing + // the collection on any update to prevent the situation we have + // here where the caches have inconsistent data + expected1 = VALUE2; + expected2 = VALUE1; + } else { + // the initial VALUE2 should prevent the node2 put + expected1 = VALUE2; + expected2 = VALUE2; + } + + assertEquals(msg1, expected1, localAccessStrategy.get(KEY, txTimestamp)); + assertEquals(msg2, expected2, remoteAccessStrategy.get(KEY, txTimestamp)); + } + + /** + * Test method for {@link CollectionRegionAccessStrategy#remove(java.lang.Object)}. + */ + public void testRemove() { + evictOrRemoveTest(false); + } + + /** + * Test method for {@link CollectionRegionAccessStrategy#removeAll()}. + */ + public void testRemoveAll() { + evictOrRemoveAllTest(false); + } + + /** + * Test method for {@link CollectionRegionAccessStrategy#evict(java.lang.Object)}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the CollectionRegionAccessStrategy API. + */ + public void testEvict() { + evictOrRemoveTest(true); + } + + /** + * Test method for {@link CollectionRegionAccessStrategy#evictAll()}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the CollectionRegionAccessStrategy API. + */ + public void testEvictAll() { + evictOrRemoveAllTest(true); + } + + private void evictOrRemoveTest( boolean evict ) { + + final String KEY = KEY_BASE + testCount++; + + assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + // Wait for async propagation + sleep(250); + + if (evict) localAccessStrategy.evict(KEY); + else localAccessStrategy.remove(KEY); + + assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); + + assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + } + + private void evictOrRemoveAllTest( boolean evict ) { + + final String KEY = KEY_BASE + testCount++; + + assertEquals(0, getValidKeyCount(localCache.keySet())); + + assertEquals(0, getValidKeyCount(remoteCache.keySet())); + + assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + // Wait for async propagation + sleep(250); + + if (evict) localAccessStrategy.evictAll(); + else localAccessStrategy.removeAll(); + + // This should re-establish the region root node + assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); + + assertEquals(0, getValidKeyCount(localCache.keySet())); + + // Re-establishing the region root on the local node doesn't + // propagate it to other nodes. Do a get on the remote node to re-establish + assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + assertEquals(0, getValidKeyCount(remoteCache.keySet())); + + // Test whether the get above messes up the optimistic version + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + + assertEquals(1, getValidKeyCount(remoteCache.keySet())); + + // Wait for async propagation of the putFromLoad + sleep(250); + + assertEquals("local is correct", + (isUsingInvalidation() ? null : VALUE1), + localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + } + + private void rollback() { + try { + BatchModeTransactionManager.getInstance().rollback(); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + } + + } + + private static class AccessStrategyTestSetup extends TestSetup { + + private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; + + private final String configResource; + private final String configName; + private String preferIPv4Stack; + private ServiceRegistryHolder serviceRegistryHolder; + + public AccessStrategyTestSetup( Test test, + String configName ) { + this(test, configName, null); + } + + public AccessStrategyTestSetup( Test test, + String configName, + String configResource ) { + super(test); + this.configName = configName; + this.configResource = configResource; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // Try to ensure we use IPv4; otherwise cluster formation is very slow + preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); + System.setProperty(PREFER_IPV4STACK, "true"); + + serviceRegistryHolder = new ServiceRegistryHolder(Environment.getProperties()); + + localCfg = createConfiguration(configName, configResource); + localRegionFactory = CacheTestUtil.startRegionFactory(serviceRegistryHolder.getJdbcServicesImpl(), localCfg); + + remoteCfg = createConfiguration(configName, configResource); + remoteRegionFactory = CacheTestUtil.startRegionFactory(serviceRegistryHolder.getJdbcServicesImpl(), remoteCfg); + } + + @Override + protected void tearDown() throws Exception { try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); - - assertEquals("node1 starts clean", null, localAccessStrategy.get(KEY, txTimestamp)); - - writeLatch1.await(); - - if (useMinimalAPI) { - localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2), true); - } else { - localAccessStrategy.putFromLoad(KEY, VALUE2, txTimestamp, new Integer(2)); - } - - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); + super.tearDown(); } finally { - // Let node2 write - writeLatch2.countDown(); - completionLatch.countDown(); + if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); + else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); } - } - }; - - Thread node2 = new Thread() { - - public void run() { try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + if (localRegionFactory != null) localRegionFactory.stop(); - assertNull("node2 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); - - // Let node1 write - writeLatch1.countDown(); - // Wait for node1 to finish - writeLatch2.await(); - - // Let the first PFER propagate - sleep(200); - - if (useMinimalAPI) { - remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); - } else { - remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); - } - - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node2 caught exception", e); - node2Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node2Failure = e; - rollback(); + if (remoteRegionFactory != null) remoteRegionFactory.stop(); } finally { - completionLatch.countDown(); + if (serviceRegistryHolder != null) { + serviceRegistryHolder.destroy(); + } } - } - }; + } - node1.setDaemon(true); - node2.setDaemon(true); - - node1.start(); - node2.start(); - - assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); - - if (node1Failure != null) - throw node1Failure; - if (node2Failure != null) - throw node2Failure; - - assertEquals("node1 saw no exceptions", null, node1Exception); - assertEquals("node2 saw no exceptions", null, node2Exception); - - // let the final PFER propagate - sleep(100); - - long txTimestamp = System.currentTimeMillis(); - String msg1 = "Correct node1 value"; - String msg2 = "Correct node2 value"; - Object expected1 = null; - Object expected2 = null; - if (isUsingInvalidation()) { - // PFER does not generate any invalidation, so each node should - // succeed. We count on database locking and Hibernate removing - // the collection on any update to prevent the situation we have - // here where the caches have inconsistent data - expected1 = VALUE2; - expected2 = VALUE1; - } else { - // the initial VALUE2 should prevent the node2 put - expected1 = VALUE2; - expected2 = VALUE2; - } - - assertEquals(msg1, expected1, localAccessStrategy.get(KEY, txTimestamp)); - assertEquals(msg2, expected2, remoteAccessStrategy.get(KEY, txTimestamp)); - } - - /** - * Test method for {@link CollectionRegionAccessStrategy#remove(java.lang.Object)}. - */ - public void testRemove() { - evictOrRemoveTest(false); - } - - /** - * Test method for {@link CollectionRegionAccessStrategy#removeAll()}. - */ - public void testRemoveAll() { - evictOrRemoveAllTest(false); - } - - /** - * Test method for {@link CollectionRegionAccessStrategy#evict(java.lang.Object)}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * CollectionRegionAccessStrategy API. - */ - public void testEvict() { - evictOrRemoveTest(true); - } - - /** - * Test method for {@link CollectionRegionAccessStrategy#evictAll()}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * CollectionRegionAccessStrategy API. - */ - public void testEvictAll() { - evictOrRemoveAllTest(true); - } - - private void evictOrRemoveTest(boolean evict) { - - final String KEY = KEY_BASE + testCount++; - - assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - // Wait for async propagation - sleep(250); - - if (evict) - localAccessStrategy.evict(KEY); - else - localAccessStrategy.remove(KEY); - - assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); - - assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - } - - private void evictOrRemoveAllTest(boolean evict) { - - final String KEY = KEY_BASE + testCount++; - - assertEquals(0, getValidKeyCount(localCache.keySet())); - - assertEquals(0, getValidKeyCount(remoteCache.keySet())); - - assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - // Wait for async propagation - sleep(250); - - if (evict) - localAccessStrategy.evictAll(); - else - localAccessStrategy.removeAll(); - - // This should re-establish the region root node - assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); - - assertEquals(0, getValidKeyCount(localCache.keySet())); - - // Re-establishing the region root on the local node doesn't - // propagate it to other nodes. Do a get on the remote node to re-establish - assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - assertEquals(0, getValidKeyCount(remoteCache.keySet())); - - // Test whether the get above messes up the optimistic version - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - - assertEquals(1, getValidKeyCount(remoteCache.keySet())); - - // Wait for async propagation of the putFromLoad - sleep(250); - - assertEquals("local is correct", (isUsingInvalidation() ? null : VALUE1), localAccessStrategy.get(KEY, System - .currentTimeMillis())); - assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - } - - private void rollback() { - try { - BatchModeTransactionManager.getInstance().rollback(); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - - } - - private static class AccessStrategyTestSetup extends TestSetup { - - private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; - - private final String configResource; - private final String configName; - private String preferIPv4Stack; - private ServiceRegistryHolder serviceRegistryHolder; - - public AccessStrategyTestSetup(Test test, String configName) { - this(test, configName, null); - } - - public AccessStrategyTestSetup(Test test, String configName, String configResource) { - super(test); - this.configName = configName; - this.configResource = configResource; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - // Try to ensure we use IPv4; otherwise cluster formation is very slow - preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); - System.setProperty(PREFER_IPV4STACK, "true"); - - serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); - - localCfg = createConfiguration(configName, configResource); - localRegionFactory = CacheTestUtil.startRegionFactory( - serviceRegistryHolder.getJdbcServicesImpl(), - localCfg - ); - - remoteCfg = createConfiguration(configName, configResource); - remoteRegionFactory = CacheTestUtil.startRegionFactory( - serviceRegistryHolder.getJdbcServicesImpl(), - remoteCfg - ); - } - - @Override - protected void tearDown() throws Exception { - try { - super.tearDown(); - } finally { - if (preferIPv4Stack == null) - System.clearProperty(PREFER_IPV4STACK); - else - System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); - } - - try { - if (localRegionFactory != null) - localRegionFactory.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/AbstractEntityRegionAccessStrategyTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractEntityRegionAccessStrategyTestCase.java index 06320be78a..0b2ec0e165 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 @@ -25,12 +25,10 @@ package org.hibernate.test.cache.infinispan.entity; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import junit.extensions.TestSetup; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; - import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.EntityRegion; import org.hibernate.cache.access.AccessType; @@ -43,6 +41,7 @@ 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.TestInfinispanLogger; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.hibernate.test.common.ServiceRegistryHolder; import org.hibernate.util.ComparableComparator; @@ -50,650 +49,636 @@ import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of EntityRegionAccessStrategy impls. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public abstract class AbstractEntityRegionAccessStrategyTestCase extends AbstractNonFunctionalTestCase { - public static final String REGION_NAME = "test/com.foo.test"; - public static final String KEY_BASE = "KEY"; - public static final String VALUE1 = "VALUE1"; - public static final String VALUE2 = "VALUE2"; + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - protected static int testCount; + public static final String REGION_NAME = "test/com.foo.test"; + public static final String KEY_BASE = "KEY"; + public static final String VALUE1 = "VALUE1"; + public static final String VALUE2 = "VALUE2"; - protected static Configuration localCfg; - protected static InfinispanRegionFactory localRegionFactory; - protected CacheAdapter localCache; - protected static Configuration remoteCfg; - protected static InfinispanRegionFactory remoteRegionFactory; - protected CacheAdapter remoteCache; + protected static int testCount; - protected boolean invalidation; - protected boolean synchronous; + protected static Configuration localCfg; + protected static InfinispanRegionFactory localRegionFactory; + protected CacheAdapter localCache; + protected static Configuration remoteCfg; + protected static InfinispanRegionFactory remoteRegionFactory; + protected CacheAdapter remoteCache; - protected EntityRegion localEntityRegion; - protected EntityRegionAccessStrategy localAccessStrategy; + protected boolean invalidation; + protected boolean synchronous; - protected EntityRegion remoteEntityRegion; - protected EntityRegionAccessStrategy remoteAccessStrategy; + protected EntityRegion localEntityRegion; + protected EntityRegionAccessStrategy localAccessStrategy; - protected Exception node1Exception; - protected Exception node2Exception; + protected EntityRegion remoteEntityRegion; + protected EntityRegionAccessStrategy remoteAccessStrategy; - protected AssertionFailedError node1Failure; - protected AssertionFailedError node2Failure; + protected Exception node1Exception; + protected Exception node2Exception; - public static Test getTestSetup(Class testClass, String configName) { - TestSuite suite = new TestSuite(testClass); - return new AccessStrategyTestSetup(suite, configName); - } + protected AssertionFailedError node1Failure; + protected AssertionFailedError node2Failure; - public static Test getTestSetup(Test test, String configName) { - return new AccessStrategyTestSetup(test, configName); - } + public static Test getTestSetup( Class testClass, + String configName ) { + TestSuite suite = new TestSuite(testClass); + return new AccessStrategyTestSetup(suite, configName); + } - /** - * Create a new TransactionalAccessTestCase. - * - * @param name - */ - public AbstractEntityRegionAccessStrategyTestCase(String name) { - super(name); - } + public static Test getTestSetup( Test test, + String configName ) { + return new AccessStrategyTestSetup(test, configName); + } - protected abstract AccessType getAccessType(); + /** + * Create a new TransactionalAccessTestCase. + * + * @param name + */ + public AbstractEntityRegionAccessStrategyTestCase( String name ) { + super(name); + } - protected void setUp() throws Exception { - super.setUp(); + protected abstract AccessType getAccessType(); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + @Override + protected void setUp() throws Exception { + super.setUp(); - localEntityRegion = localRegionFactory.buildEntityRegion(REGION_NAME, localCfg - .getProperties(), getCacheDataDescription()); - localAccessStrategy = localEntityRegion.buildAccessStrategy(getAccessType()); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - localCache = ((BaseRegion) localEntityRegion).getCacheAdapter(); + localEntityRegion = localRegionFactory.buildEntityRegion(REGION_NAME, localCfg.getProperties(), getCacheDataDescription()); + localAccessStrategy = localEntityRegion.buildAccessStrategy(getAccessType()); - invalidation = localCache.isClusteredInvalidation(); - synchronous = localCache.isSynchronous(); + localCache = ((BaseRegion)localEntityRegion).getCacheAdapter(); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + invalidation = localCache.isClusteredInvalidation(); + synchronous = localCache.isSynchronous(); - remoteEntityRegion = remoteRegionFactory.buildEntityRegion(REGION_NAME, remoteCfg - .getProperties(), getCacheDataDescription()); - remoteAccessStrategy = remoteEntityRegion.buildAccessStrategy(getAccessType()); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - remoteCache = ((BaseRegion) remoteEntityRegion).getCacheAdapter(); + remoteEntityRegion = remoteRegionFactory.buildEntityRegion(REGION_NAME, + remoteCfg.getProperties(), + getCacheDataDescription()); + remoteAccessStrategy = remoteEntityRegion.buildAccessStrategy(getAccessType()); - node1Exception = null; - node2Exception = null; + remoteCache = ((BaseRegion)remoteEntityRegion).getCacheAdapter(); - node1Failure = null; - node2Failure = null; - } + node1Exception = null; + node2Exception = null; - protected void tearDown() throws Exception { + node1Failure = null; + node2Failure = null; + } - super.tearDown(); + @Override + protected void tearDown() throws Exception { - try { - localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); - } catch (Exception e) { - log.error("Problem purging local cache", e); - } + super.tearDown(); - try { - remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); - } catch (Exception e) { - log.error("Problem purging remote cache", e); - } + try { + localCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); + } catch (Exception e) { + LOG.error("Problem purging local cache", e); + } - node1Exception = null; - node2Exception = null; + try { + remoteCache.withFlags(FlagAdapter.CACHE_MODE_LOCAL).clear(); + } catch (Exception e) { + LOG.error("Problem purging remote cache", e); + } - node1Failure = null; - node2Failure = null; - } + node1Exception = null; + node2Exception = null; - protected static Configuration createConfiguration(String configName) { - Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); - cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); - return cfg; - } + node1Failure = null; + node2Failure = null; + } - protected CacheDataDescription getCacheDataDescription() { - return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); - } + protected static Configuration createConfiguration( String configName ) { + Configuration cfg = CacheTestUtil.buildConfiguration(REGION_PREFIX, InfinispanRegionFactory.class, true, false); + cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, configName); + return cfg; + } - protected boolean isUsingInvalidation() { - return invalidation; - } + protected CacheDataDescription getCacheDataDescription() { + return new CacheDataDescriptionImpl(true, true, ComparableComparator.INSTANCE); + } - protected boolean isSynchronous() { - return synchronous; - } + protected boolean isUsingInvalidation() { + return invalidation; + } - protected void assertThreadsRanCleanly() { - if (node1Failure != null) - throw node1Failure; - if (node2Failure != null) - throw node2Failure; + protected boolean isSynchronous() { + return synchronous; + } - if (node1Exception != null) { - log.error("node1 saw an exception", node1Exception); - assertEquals("node1 saw no exceptions", null, node1Exception); - } + protected void assertThreadsRanCleanly() { + if (node1Failure != null) throw node1Failure; + if (node2Failure != null) throw node2Failure; - if (node2Exception != null) { - log.error("node2 saw an exception", node2Exception); - assertEquals("node2 saw no exceptions", null, node2Exception); - } - } + if (node1Exception != null) { + LOG.error("node1 saw an exception", node1Exception); + assertEquals("node1 saw no exceptions", null, node1Exception); + } - /** - * This is just a setup test where we assert that the cache config is as we expected. - */ - public abstract void testCacheConfiguration(); + if (node2Exception != null) { + LOG.error("node2 saw an exception", node2Exception); + assertEquals("node2 saw no exceptions", null, node2Exception); + } + } - /** - * Test method for {@link TransactionalAccess#getRegion()}. - */ - public void testGetRegion() { - assertEquals("Correct region", localEntityRegion, localAccessStrategy.getRegion()); - } + /** + * This is just a setup test where we assert that the cache config is as we expected. + */ + public abstract void testCacheConfiguration(); - /** - * Test method for - * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} - * . - */ - public void testPutFromLoad() throws Exception { - putFromLoadTest(false); - } + /** + * Test method for {@link TransactionalAccess#getRegion()}. + */ + public void testGetRegion() { + assertEquals("Correct region", localEntityRegion, localAccessStrategy.getRegion()); + } - /** - * Test method for - * {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} - * . - */ - public void testPutFromLoadMinimal() throws Exception { - putFromLoadTest(true); - } + /** + * Test method for {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)} . + */ + public void testPutFromLoad() throws Exception { + putFromLoadTest(false); + } - /** - * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First - * does a putFromLoad, then an update. Second tries to do a putFromLoad with stale data (i.e. it - * took longer to read from the db). Both commit their tx. Then both start a new tx and get. - * First should see the updated data; second should either see the updated data (isInvalidation() - * == false) or null (isInvalidation() == true). - * - * @param useMinimalAPI - * @throws Exception - */ - private void putFromLoadTest(final boolean useMinimalAPI) throws Exception { + /** + * Test method for {@link TransactionalAccess#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)} + * . + */ + public void testPutFromLoadMinimal() throws Exception { + putFromLoadTest(true); + } - final String KEY = KEY_BASE + testCount++; + /** + * Simulate 2 nodes, both start, tx do a get, experience a cache miss, then 'read from db.' First does a putFromLoad, then an + * update. Second tries to do a putFromLoad with stale data (i.e. it took longer to read from the db). Both commit their tx. + * Then both start a new tx and get. First should see the updated data; second should either see the updated data + * (isInvalidation() == false) or null (isInvalidation() == true). + * + * @param useMinimalAPI + * @throws Exception + */ + private void putFromLoadTest( final boolean useMinimalAPI ) throws Exception { - final CountDownLatch writeLatch1 = new CountDownLatch(1); - final CountDownLatch writeLatch2 = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(2); + final String KEY = KEY_BASE + testCount++; - Thread node1 = new Thread() { + final CountDownLatch writeLatch1 = new CountDownLatch(1); + final CountDownLatch writeLatch2 = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(2); - public void run() { + Thread node1 = new Thread() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + @Override + public void run() { - assertNull("node1 starts clean", localAccessStrategy.get(KEY, txTimestamp)); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - writeLatch1.await(); + assertNull("node1 starts clean", localAccessStrategy.get(KEY, txTimestamp)); - if (useMinimalAPI) { - localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); - } else { - localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); - } + writeLatch1.await(); - localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); + if (useMinimalAPI) { + localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); + } else { + localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); + } - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - // Let node2 write - writeLatch2.countDown(); - completionLatch.countDown(); + localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); + + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + // Let node2 write + writeLatch2.countDown(); + completionLatch.countDown(); + } } - } - }; + }; - Thread node2 = new Thread() { + Thread node2 = new Thread() { - public void run() { + @Override + public void run() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - assertNull("node1 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); + assertNull("node1 starts clean", remoteAccessStrategy.get(KEY, txTimestamp)); - // Let node1 write - writeLatch1.countDown(); - // Wait for node1 to finish - writeLatch2.await(); + // Let node1 write + writeLatch1.countDown(); + // Wait for node1 to finish + writeLatch2.await(); - if (useMinimalAPI) { - remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); - } else { - remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); - } + if (useMinimalAPI) { + remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1), true); + } else { + remoteAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); + } - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node2 caught exception", e); - node2Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node2Failure = e; - rollback(); - } finally { - completionLatch.countDown(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node2 caught exception", e); + node2Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node2Failure = e; + rollback(); + } finally { + completionLatch.countDown(); + } } - } - }; + }; - node1.setDaemon(true); - node2.setDaemon(true); + node1.setDaemon(true); + node2.setDaemon(true); - node1.start(); - node2.start(); + node1.start(); + node2.start(); - assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); + assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS)); - assertThreadsRanCleanly(); + assertThreadsRanCleanly(); - long txTimestamp = System.currentTimeMillis(); - assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); + long txTimestamp = System.currentTimeMillis(); + assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); - if (isUsingInvalidation()) { - // no data version to prevent the PFER; we count on db locks preventing this - assertEquals("Expected node2 value", VALUE1, remoteAccessStrategy.get(KEY, txTimestamp)); - } else { - // The node1 update is replicated, preventing the node2 PFER - assertEquals("Correct node2 value", VALUE2, remoteAccessStrategy.get(KEY, txTimestamp)); - } - } + if (isUsingInvalidation()) { + // no data version to prevent the PFER; we count on db locks preventing this + assertEquals("Expected node2 value", VALUE1, remoteAccessStrategy.get(KEY, txTimestamp)); + } else { + // The node1 update is replicated, preventing the node2 PFER + assertEquals("Correct node2 value", VALUE2, remoteAccessStrategy.get(KEY, txTimestamp)); + } + } - /** - * Test method for - * {@link TransactionalAccess#insert(java.lang.Object, java.lang.Object, java.lang.Object)}. - */ - public void testInsert() throws Exception { + /** + * Test method for {@link TransactionalAccess#insert(java.lang.Object, java.lang.Object, java.lang.Object)}. + */ + public void testInsert() throws Exception { - final String KEY = KEY_BASE + testCount++; + final String KEY = KEY_BASE + testCount++; - final CountDownLatch readLatch = new CountDownLatch(1); - final CountDownLatch commitLatch = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(2); + final CountDownLatch readLatch = new CountDownLatch(1); + final CountDownLatch commitLatch = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(2); - Thread inserter = new Thread() { + Thread inserter = new Thread() { - public void run() { + @Override + public void run() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - assertNull("Correct initial value", localAccessStrategy.get(KEY, txTimestamp)); + assertNull("Correct initial value", localAccessStrategy.get(KEY, txTimestamp)); - localAccessStrategy.insert(KEY, VALUE1, new Integer(1)); + localAccessStrategy.insert(KEY, VALUE1, new Integer(1)); - readLatch.countDown(); - commitLatch.await(); + readLatch.countDown(); + commitLatch.await(); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - completionLatch.countDown(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + completionLatch.countDown(); + } } - } - }; + }; - Thread reader = new Thread() { + Thread reader = new Thread() { - public void run() { + @Override + public void run() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - readLatch.await(); -// Object expected = !isBlockingReads() ? null : VALUE1; - Object expected = null; + readLatch.await(); + // Object expected = !isBlockingReads() ? null : VALUE1; + Object expected = null; - assertEquals("Correct initial value", expected, localAccessStrategy.get(KEY, - txTimestamp)); + assertEquals("Correct initial value", expected, localAccessStrategy.get(KEY, txTimestamp)); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - commitLatch.countDown(); - completionLatch.countDown(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + commitLatch.countDown(); + completionLatch.countDown(); + } } - } - }; + }; - inserter.setDaemon(true); - reader.setDaemon(true); - inserter.start(); - reader.start(); + inserter.setDaemon(true); + reader.setDaemon(true); + inserter.start(); + reader.start(); - assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); + assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); - assertThreadsRanCleanly(); + assertThreadsRanCleanly(); - long txTimestamp = System.currentTimeMillis(); - assertEquals("Correct node1 value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); - Object expected = isUsingInvalidation() ? null : VALUE1; - assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); - } + long txTimestamp = System.currentTimeMillis(); + assertEquals("Correct node1 value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); + Object expected = isUsingInvalidation() ? null : VALUE1; + assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); + } - /** - * Test method for - * {@link TransactionalAccess#update(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)} - * . - */ - public void testUpdate() throws Exception { + /** + * Test method for {@link TransactionalAccess#update(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)} . + */ + public void testUpdate() throws Exception { - final String KEY = KEY_BASE + testCount++; + final String KEY = KEY_BASE + testCount++; - // Set up initial state - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + // Set up initial state + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - // Let the async put propagate - sleep(250); + // Let the async put propagate + sleep(250); - final CountDownLatch readLatch = new CountDownLatch(1); - final CountDownLatch commitLatch = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(2); + final CountDownLatch readLatch = new CountDownLatch(1); + final CountDownLatch commitLatch = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(2); - Thread updater = new Thread("testUpdate-updater") { + Thread updater = new Thread("testUpdate-updater") { - public void run() { - boolean readerUnlocked = false; - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); - log.debug("Transaction began, get initial value"); - assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); - log.debug("Now update value"); - localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); - log.debug("Notify the read latch"); - readLatch.countDown(); - readerUnlocked = true; - log.debug("Await commit"); - commitLatch.await(); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - if (!readerUnlocked) readLatch.countDown(); - log.debug("Completion latch countdown"); - completionLatch.countDown(); + @Override + public void run() { + boolean readerUnlocked = false; + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); + LOG.debug("Transaction began, get initial value"); + assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); + LOG.debug("Now update value"); + localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); + LOG.debug("Notify the read latch"); + readLatch.countDown(); + readerUnlocked = true; + LOG.debug("Await commit"); + commitLatch.await(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + if (!readerUnlocked) readLatch.countDown(); + LOG.debug("Completion latch countdown"); + completionLatch.countDown(); + } } - } - }; + }; - Thread reader = new Thread("testUpdate-reader") { + Thread reader = new Thread("testUpdate-reader") { - public void run() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); - log.debug("Transaction began, await read latch"); - readLatch.await(); - log.debug("Read latch acquired, verify local access strategy"); + @Override + public void run() { + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); + LOG.debug("Transaction began, await read latch"); + readLatch.await(); + LOG.debug("Read latch acquired, verify local access strategy"); - // This won't block w/ mvc and will read the old value - Object expected = VALUE1; - assertEquals("Correct value", expected, localAccessStrategy.get(KEY, txTimestamp)); + // This won't block w/ mvc and will read the old value + Object expected = VALUE1; + assertEquals("Correct value", expected, localAccessStrategy.get(KEY, txTimestamp)); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - commitLatch.countDown(); - log.debug("Completion latch countdown"); - completionLatch.countDown(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + commitLatch.countDown(); + LOG.debug("Completion latch countdown"); + completionLatch.countDown(); + } } - } - }; + }; - updater.setDaemon(true); - reader.setDaemon(true); - updater.start(); - reader.start(); + updater.setDaemon(true); + reader.setDaemon(true); + updater.start(); + reader.start(); - // Should complete promptly - assertTrue(completionLatch.await(2, TimeUnit.SECONDS)); + // Should complete promptly + assertTrue(completionLatch.await(2, TimeUnit.SECONDS)); - assertThreadsRanCleanly(); + assertThreadsRanCleanly(); - long txTimestamp = System.currentTimeMillis(); - assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); - Object expected = isUsingInvalidation() ? null : VALUE2; - assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); - } + long txTimestamp = System.currentTimeMillis(); + assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); + Object expected = isUsingInvalidation() ? null : VALUE2; + assertEquals("Correct node2 value", expected, remoteAccessStrategy.get(KEY, txTimestamp)); + } - /** - * Test method for {@link TransactionalAccess#remove(java.lang.Object)}. - */ - public void testRemove() { - evictOrRemoveTest(false); - } + /** + * Test method for {@link TransactionalAccess#remove(java.lang.Object)}. + */ + public void testRemove() { + evictOrRemoveTest(false); + } - /** - * Test method for {@link TransactionalAccess#removeAll()}. - */ - public void testRemoveAll() { - evictOrRemoveAllTest(false); - } + /** + * Test method for {@link TransactionalAccess#removeAll()}. + */ + public void testRemoveAll() { + evictOrRemoveAllTest(false); + } - /** - * Test method for {@link TransactionalAccess#evict(java.lang.Object)}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * EntityRegionAccessStrategy API. - */ - public void testEvict() { - evictOrRemoveTest(true); - } + /** + * Test method for {@link TransactionalAccess#evict(java.lang.Object)}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the EntityRegionAccessStrategy API. + */ + public void testEvict() { + evictOrRemoveTest(true); + } - /** - * Test method for {@link TransactionalAccess#evictAll()}. - * - * FIXME add testing of the "immediately without regard for transaction isolation" bit in the - * EntityRegionAccessStrategy API. - */ - public void testEvictAll() { - evictOrRemoveAllTest(true); - } + /** + * Test method for {@link TransactionalAccess#evictAll()}. FIXME add testing of the + * "immediately without regard for transaction isolation" bit in the EntityRegionAccessStrategy API. + */ + public void testEvictAll() { + evictOrRemoveAllTest(true); + } - private void evictOrRemoveTest(boolean evict) { - final String KEY = KEY_BASE + testCount++; - assertEquals(0, getValidKeyCount(localCache.keySet())); - assertEquals(0, getValidKeyCount(remoteCache.keySet())); + private void evictOrRemoveTest( boolean evict ) { + final String KEY = KEY_BASE + testCount++; + assertEquals(0, getValidKeyCount(localCache.keySet())); + assertEquals(0, getValidKeyCount(remoteCache.keySet())); - assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - if (evict) - localAccessStrategy.evict(KEY); - else - localAccessStrategy.remove(KEY); + if (evict) localAccessStrategy.evict(KEY); + else localAccessStrategy.remove(KEY); - assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertEquals(0, getValidKeyCount(localCache.keySet())); - assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - assertEquals(0, getValidKeyCount(remoteCache.keySet())); - } + assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals(0, getValidKeyCount(localCache.keySet())); + assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals(0, getValidKeyCount(remoteCache.keySet())); + } - private void evictOrRemoveAllTest(boolean evict) { - final String KEY = KEY_BASE + testCount++; - assertEquals(0, getValidKeyCount(localCache.keySet())); - assertEquals(0, getValidKeyCount(remoteCache.keySet())); - assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + private void evictOrRemoveAllTest( boolean evict ) { + final String KEY = KEY_BASE + testCount++; + assertEquals(0, getValidKeyCount(localCache.keySet())); + assertEquals(0, getValidKeyCount(remoteCache.keySet())); + assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis())); - // Wait for async propagation - sleep(250); + // Wait for async propagation + sleep(250); - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - // Wait for async propagation - sleep(250); + // Wait for async propagation + sleep(250); - if (evict) { - log.debug("Call evict all locally"); - localAccessStrategy.evictAll(); - } else { - localAccessStrategy.removeAll(); - } + if (evict) { + LOG.debug("Call evict all locally"); + localAccessStrategy.evictAll(); + } else { + localAccessStrategy.removeAll(); + } - // This should re-establish the region root node in the optimistic case - assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); - assertEquals(0, getValidKeyCount(localCache.keySet())); + // This should re-establish the region root node in the optimistic case + assertNull(localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals(0, getValidKeyCount(localCache.keySet())); - // Re-establishing the region root on the local node doesn't - // propagate it to other nodes. Do a get on the remote node to re-establish - assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - assertEquals(0, getValidKeyCount(remoteCache.keySet())); + // Re-establishing the region root on the local node doesn't + // propagate it to other nodes. Do a get on the remote node to re-establish + assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals(0, getValidKeyCount(remoteCache.keySet())); - // Test whether the get above messes up the optimistic version - remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); - assertEquals(1, getValidKeyCount(remoteCache.keySet())); + // Test whether the get above messes up the optimistic version + remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals(1, getValidKeyCount(remoteCache.keySet())); - // Wait for async propagation - sleep(250); + // Wait for async propagation + sleep(250); - assertEquals("local is correct", (isUsingInvalidation() ? null : VALUE1), localAccessStrategy - .get(KEY, System.currentTimeMillis())); - assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System - .currentTimeMillis())); - } + assertEquals("local is correct", + (isUsingInvalidation() ? null : VALUE1), + localAccessStrategy.get(KEY, System.currentTimeMillis())); + assertEquals("remote is correct", VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis())); + } - protected void rollback() { - try { - BatchModeTransactionManager.getInstance().rollback(); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - } + protected void rollback() { + try { + BatchModeTransactionManager.getInstance().rollback(); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + } + } - private static class AccessStrategyTestSetup extends TestSetup { + private static class AccessStrategyTestSetup extends TestSetup { - private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; - private final String configName; - private String preferIPv4Stack; - private ServiceRegistryHolder serviceRegistryHolder; + 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); - this.configName = configName; - } + public AccessStrategyTestSetup( Test test, + String configName ) { + super(test); + this.configName = configName; + } - @Override - protected void setUp() throws Exception { - try { + @Override + protected void setUp() throws Exception { + try { + super.tearDown(); + } finally { + if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); + else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); + } + + // Try to ensure we use IPv4; otherwise cluster formation is very slow + preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); + System.setProperty(PREFER_IPV4STACK, "true"); + + serviceRegistryHolder = new ServiceRegistryHolder(Environment.getProperties()); + + localCfg = createConfiguration(configName); + localRegionFactory = CacheTestUtil.startRegionFactory(serviceRegistryHolder.getJdbcServicesImpl(), localCfg); + + remoteCfg = createConfiguration(configName); + remoteRegionFactory = CacheTestUtil.startRegionFactory(serviceRegistryHolder.getJdbcServicesImpl(), remoteCfg); + } + + @Override + protected void tearDown() throws Exception { super.tearDown(); - } finally { - if (preferIPv4Stack == null) - System.clearProperty(PREFER_IPV4STACK); - else - System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); - } - // Try to ensure we use IPv4; otherwise cluster formation is very slow - preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); - System.setProperty(PREFER_IPV4STACK, "true"); + try { + if (localRegionFactory != null) localRegionFactory.stop(); - serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() ); - - localCfg = createConfiguration(configName); - localRegionFactory = CacheTestUtil.startRegionFactory( - serviceRegistryHolder.getJdbcServicesImpl(), - localCfg - ); - - remoteCfg = createConfiguration(configName); - remoteRegionFactory = CacheTestUtil.startRegionFactory( - serviceRegistryHolder.getJdbcServicesImpl(), - remoteCfg - ); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - - try { - if (localRegionFactory != null) - localRegionFactory.stop(); - - if (remoteRegionFactory != null) - remoteRegionFactory.stop(); - } - finally { - if ( serviceRegistryHolder != null ) { - serviceRegistryHolder.destroy(); + 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/AbstractTransactionalAccessTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractTransactionalAccessTestCase.java index 7f93396961..330b851b67 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractTransactionalAccessTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/entity/AbstractTransactionalAccessTestCase.java @@ -25,107 +25,109 @@ package org.hibernate.test.cache.infinispan.entity; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import junit.framework.AssertionFailedError; - import org.hibernate.cache.access.AccessType; +import org.hibernate.test.cache.infinispan.TestInfinispanLogger; import org.infinispan.transaction.tm.BatchModeTransactionManager; /** * Base class for tests of TRANSACTIONAL access. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public abstract class AbstractTransactionalAccessTestCase extends AbstractEntityRegionAccessStrategyTestCase { - public AbstractTransactionalAccessTestCase(String name) { - super(name); - } + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - @Override - protected AccessType getAccessType() { - return AccessType.TRANSACTIONAL; - } + public AbstractTransactionalAccessTestCase( String name ) { + super(name); + } - public void testContestedPutFromLoad() throws Exception { + @Override + protected AccessType getAccessType() { + return AccessType.TRANSACTIONAL; + } - final String KEY = KEY_BASE + testCount++; + public void testContestedPutFromLoad() throws Exception { - localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); + final String KEY = KEY_BASE + testCount++; - final CountDownLatch pferLatch = new CountDownLatch(1); - final CountDownLatch pferCompletionLatch = new CountDownLatch(1); - final CountDownLatch commitLatch = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(1); + localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1)); - Thread blocker = new Thread("Blocker") { + final CountDownLatch pferLatch = new CountDownLatch(1); + final CountDownLatch pferCompletionLatch = new CountDownLatch(1); + final CountDownLatch commitLatch = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(1); - public void run() { + Thread blocker = new Thread("Blocker") { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + @Override + public void run() { - assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, - txTimestamp)); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); + assertEquals("Correct initial value", VALUE1, localAccessStrategy.get(KEY, txTimestamp)); - pferLatch.countDown(); - commitLatch.await(); + localAccessStrategy.update(KEY, VALUE2, new Integer(2), new Integer(1)); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - completionLatch.countDown(); + pferLatch.countDown(); + commitLatch.await(); + + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + completionLatch.countDown(); + } } - } - }; + }; - Thread putter = new Thread("Putter") { + Thread putter = new Thread("Putter") { - public void run() { + @Override + public void run() { - try { - long txTimestamp = System.currentTimeMillis(); - BatchModeTransactionManager.getInstance().begin(); + try { + long txTimestamp = System.currentTimeMillis(); + BatchModeTransactionManager.getInstance().begin(); - localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); + localAccessStrategy.putFromLoad(KEY, VALUE1, txTimestamp, new Integer(1)); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - log.error("node1 caught exception", e); - node1Exception = e; - rollback(); - } catch (AssertionFailedError e) { - node1Failure = e; - rollback(); - } finally { - pferCompletionLatch.countDown(); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + LOG.error("node1 caught exception", e); + node1Exception = e; + rollback(); + } catch (AssertionFailedError e) { + node1Failure = e; + rollback(); + } finally { + pferCompletionLatch.countDown(); + } } - } - }; + }; - blocker.start(); - assertTrue("Active tx has done an update", pferLatch.await(1, TimeUnit.SECONDS)); - putter.start(); - assertTrue("putFromLoadreturns promtly", pferCompletionLatch.await(10, TimeUnit.MILLISECONDS)); + blocker.start(); + assertTrue("Active tx has done an update", pferLatch.await(1, TimeUnit.SECONDS)); + putter.start(); + assertTrue("putFromLoadreturns promtly", pferCompletionLatch.await(10, TimeUnit.MILLISECONDS)); - commitLatch.countDown(); + commitLatch.countDown(); - assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); + assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS)); - assertThreadsRanCleanly(); + assertThreadsRanCleanly(); - long txTimestamp = System.currentTimeMillis(); - assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); - } + long txTimestamp = System.currentTimeMillis(); + assertEquals("Correct node1 value", VALUE2, localAccessStrategy.get(KEY, txTimestamp)); + } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/CacheAccessListener.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/CacheAccessListener.java index aa7c4edad2..07058cd565 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/CacheAccessListener.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/CacheAccessListener.java @@ -23,9 +23,9 @@ */ package org.hibernate.test.cache.infinispan.functional.classloader; +import static org.hibernate.test.cache.infinispan.TestInfinispanLogger.LOG; import java.util.HashSet; import java.util.Set; - import org.hibernate.cache.infinispan.util.CacheHelper; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; @@ -34,78 +34,76 @@ import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @Listener public class CacheAccessListener { - protected final Logger log = LoggerFactory.getLogger(getClass()); - - HashSet modified = new HashSet(); - HashSet accessed = new HashSet(); - public void clear() { - modified.clear(); - accessed.clear(); - } + HashSet modified = new HashSet(); + HashSet accessed = new HashSet(); - @CacheEntryModified - public void nodeModified(CacheEntryModifiedEvent event) { - if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { - Object key = event.getKey(); - log.info("Modified node " + key); - modified.add(key.toString()); - } - } - - @CacheEntryCreated - public void nodeCreated(CacheEntryCreatedEvent event) { - if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { - Object key = event.getKey(); - log.info("Created node " + key); - modified.add(key.toString()); - } - } + public void clear() { + modified.clear(); + accessed.clear(); + } - @CacheEntryVisited - public void nodeVisited(CacheEntryVisitedEvent event) { - if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { - Object key = event.getKey(); - log.info("Visited node " + key); - accessed.add(key.toString()); - } - } + @CacheEntryModified + public void nodeModified( CacheEntryModifiedEvent event ) { + if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { + Object key = event.getKey(); + LOG.info("Modified node " + key); + modified.add(key.toString()); + } + } - public boolean getSawRegionModification(Object key) { - return getSawRegion(key, modified); - } - - public int getSawRegionModificationCount() { - return modified.size(); - } - - public void clearSawRegionModification() { - modified.clear(); - } + @CacheEntryCreated + public void nodeCreated( CacheEntryCreatedEvent event ) { + if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { + Object key = event.getKey(); + LOG.info("Created node " + key); + modified.add(key.toString()); + } + } - public boolean getSawRegionAccess(Object key) { - return getSawRegion(key, accessed); - } + @CacheEntryVisited + public void nodeVisited( CacheEntryVisitedEvent event ) { + if (!event.isPre() && !CacheHelper.isEvictAllNotification(event.getKey())) { + Object key = event.getKey(); + LOG.info("Visited node " + key); + accessed.add(key.toString()); + } + } - public int getSawRegionAccessCount() { - return accessed.size(); - } - - public void clearSawRegionAccess() { - accessed.clear(); - } + public boolean getSawRegionModification( Object key ) { + return getSawRegion(key, modified); + } - private boolean getSawRegion(Object key, Set sawEvents) { - if (sawEvents.contains(key)) { - sawEvents.remove(key); - return true; - } - return false; - } + public int getSawRegionModificationCount() { + return modified.size(); + } -} \ No newline at end of file + public void clearSawRegionModification() { + modified.clear(); + } + + public boolean getSawRegionAccess( Object key ) { + return getSawRegion(key, accessed); + } + + public int getSawRegionAccessCount() { + return accessed.size(); + } + + public void clearSawRegionAccess() { + accessed.clear(); + } + + private boolean getSawRegion( Object key, + Set sawEvents ) { + if (sawEvents.contains(key)) { + sawEvents.remove(key); + return true; + } + return false; + } + +} diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedClassLoaderTest.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedClassLoaderTest.java index 04e22473f6..8844e546f1 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedClassLoaderTest.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/IsolatedClassLoaderTest.java @@ -22,306 +22,299 @@ package org.hibernate.test.cache.infinispan.functional.classloader; import javax.transaction.TransactionManager; - import junit.framework.Test; import junit.framework.TestSuite; - import org.hibernate.SessionFactory; import org.hibernate.cache.StandardQueryCache; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; -import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase; +import org.hibernate.test.cache.infinispan.TestInfinispanLogger; import org.hibernate.test.cache.infinispan.functional.cluster.ClusterAwareRegionFactory; import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl; +import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * Tests entity and query caching when class of objects being cached are not visible to Infinispan's - * classloader. Also serves as a general integration test. + * Tests entity and query caching when class of objects being cached are not visible to Infinispan's classloader. Also serves as a + * general integration test. *

- * This test stores an object (AccountHolder) that isn't visible to the Infinispan classloader in - * the cache in two places: - * - * 1) As part of the value tuple in an Account entity 2) As part of the FQN in a query cache entry - * (see query in ClassLoaderTestDAO.getBranch()) - * + * This test stores an object (AccountHolder) that isn't visible to the Infinispan classloader in the cache in two places: 1) As + * part of the value tuple in an Account entity 2) As part of the FQN in a query cache entry (see query in + * ClassLoaderTestDAO.getBranch()) + * * @author Galder ZamarreƱo * @since 3.5 */ public class IsolatedClassLoaderTest extends DualNodeTestCase { - public static final String OUR_PACKAGE = IsolatedClassLoaderTest.class.getPackage().getName(); + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - private static final String CACHE_CONFIG = "classloader"; + public static final String OUR_PACKAGE = IsolatedClassLoaderTest.class.getPackage().getName(); - protected static final long SLEEP_TIME = 300L; + private static final String CACHE_CONFIG = "classloader"; - protected final Logger log = LoggerFactory.getLogger(getClass()); + protected static final long SLEEP_TIME = 300L; - static int test = 0; + static int test = 0; - private Cache localQueryCache ; - private CacheAccessListener localQueryListener; + private Cache localQueryCache; + private CacheAccessListener localQueryListener; - private Cache remoteQueryCache; - private CacheAccessListener remoteQueryListener; + private Cache remoteQueryCache; + private CacheAccessListener remoteQueryListener; - public IsolatedClassLoaderTest(String string) { - super(string); - } + public IsolatedClassLoaderTest( String string ) { + super(string); + } - public static Test suite() throws Exception { - TestSuite suite = new TestSuite(IsolatedClassLoaderTest.class); - String[] acctClasses = { OUR_PACKAGE + ".Account", OUR_PACKAGE + ".AccountHolder" }; - return new IsolatedCacheTestSetup(suite, acctClasses); - } + public static Test suite() throws Exception { + TestSuite suite = new TestSuite(IsolatedClassLoaderTest.class); + String[] acctClasses = {OUR_PACKAGE + ".Account", OUR_PACKAGE + ".AccountHolder"}; + return new IsolatedCacheTestSetup(suite, acctClasses); + } - @Override - public String[] getMappings() { - return new String[] { "cache/infinispan/functional/classloader/Account.hbm.xml" }; - } - - @Override - protected void standardConfigure(Configuration cfg) { - super.standardConfigure(cfg); - cfg.setProperty(InfinispanRegionFactory.QUERY_CACHE_RESOURCE_PROP, "replicated-query"); - cfg.setProperty("hibernate.cache.infinispan.AccountRegion.cfg", "replicated-query"); - } + @Override + public String[] getMappings() { + return new String[] {"cache/infinispan/functional/classloader/Account.hbm.xml"}; + } + @Override + protected void standardConfigure( Configuration cfg ) { + super.standardConfigure(cfg); + cfg.setProperty(InfinispanRegionFactory.QUERY_CACHE_RESOURCE_PROP, "replicated-query"); + cfg.setProperty("hibernate.cache.infinispan.AccountRegion.cfg", "replicated-query"); + } - @Override - protected void cleanupTransactionManagement() { - // Don't clean up the managers, just the transactions - // Managers are still needed by the long-lived caches - DualNodeJtaTransactionManagerImpl.cleanupTransactions(); - } + @Override + protected void cleanupTransactionManagement() { + // Don't clean up the managers, just the transactions + // Managers are still needed by the long-lived caches + DualNodeJtaTransactionManagerImpl.cleanupTransactions(); + } - @Override - protected void cleanupTest() throws Exception { - try { - if (localQueryCache != null && localQueryListener != null) - localQueryCache.removeListener(localQueryListener); - if (remoteQueryCache != null && remoteQueryListener != null) - remoteQueryCache.removeListener(remoteQueryListener); - } finally { - super.cleanupTest(); - } - } + @Override + protected void cleanupTest() throws Exception { + try { + if (localQueryCache != null && localQueryListener != null) localQueryCache.removeListener(localQueryListener); + if (remoteQueryCache != null && remoteQueryListener != null) remoteQueryCache.removeListener(remoteQueryListener); + } finally { + super.cleanupTest(); + } + } - /** - * Simply confirms that the test fixture's classloader isolation setup is functioning as - * expected. - * - * @throws Exception - */ - public void testIsolatedSetup() throws Exception { - // Bind a listener to the "local" cache - // Our region factory makes its CacheManager available to us - CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); - Cache localReplicatedCache = localManager.getCache("replicated-entity"); + /** + * Simply confirms that the test fixture's classloader isolation setup is functioning as expected. + * + * @throws Exception + */ + public void testIsolatedSetup() throws Exception { + // Bind a listener to the "local" cache + // Our region factory makes its CacheManager available to us + CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); + Cache localReplicatedCache = localManager.getCache("replicated-entity"); - // Bind a listener to the "remote" cache - CacheContainer remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); - Cache remoteReplicatedCache = remoteManager.getCache("replicated-entity"); + // Bind a listener to the "remote" cache + CacheContainer remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); + Cache remoteReplicatedCache = remoteManager.getCache("replicated-entity"); - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(cl.getParent()); - log.info("TCCL is " + cl.getParent()); + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(cl.getParent()); + LOG.info("TCCL is " + cl.getParent()); - Account acct = new Account(); - acct.setAccountHolder(new AccountHolder()); + Account acct = new Account(); + acct.setAccountHolder(new AccountHolder()); - try { - localReplicatedCache.put("isolated1", acct); - // With lazy deserialization, retrieval in remote forces class resolution - remoteReplicatedCache.get("isolated1"); - fail("Should not have succeeded in putting acct -- classloader not isolated"); - } catch (Exception e) { - if (e.getCause() instanceof ClassNotFoundException) { - log.info("Caught exception as desired", e); - } else { - throw new IllegalStateException("Unexpected exception", e); - } - } + try { + localReplicatedCache.put("isolated1", acct); + // With lazy deserialization, retrieval in remote forces class resolution + remoteReplicatedCache.get("isolated1"); + fail("Should not have succeeded in putting acct -- classloader not isolated"); + } catch (Exception e) { + if (e.getCause() instanceof ClassNotFoundException) { + LOG.info("Caught exception as desired", e); + } else { + throw new IllegalStateException("Unexpected exception", e); + } + } - Thread.currentThread().setContextClassLoader(cl); - log.info("TCCL is " + cl); - localReplicatedCache.put("isolated2", acct); - assertEquals(acct.getClass().getName(), remoteReplicatedCache.get("isolated2").getClass().getName()); - } + Thread.currentThread().setContextClassLoader(cl); + LOG.info("TCCL is " + cl); + localReplicatedCache.put("isolated2", acct); + assertEquals(acct.getClass().getName(), remoteReplicatedCache.get("isolated2").getClass().getName()); + } - public void testClassLoaderHandlingNamedQueryRegion() throws Exception { - queryTest(true); - } + public void testClassLoaderHandlingNamedQueryRegion() throws Exception { + queryTest(true); + } - public void testClassLoaderHandlingStandardQueryCache() throws Exception { - queryTest(false); - } + public void testClassLoaderHandlingStandardQueryCache() throws Exception { + queryTest(false); + } - protected void queryTest(boolean useNamedRegion) throws Exception { - // Bind a listener to the "local" cache - // Our region factory makes its CacheManager available to us - EmbeddedCacheManager localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); - // Bind a listener to the "remote" cache - EmbeddedCacheManager remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); - String cacheName; - if (useNamedRegion) { - cacheName = "AccountRegion"; // As defined by ClassLoaderTestDAO via calls to query.setCacheRegion - // Define cache configurations for region early to avoid ending up with local caches for this region - localManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); - remoteManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); - } else { - cacheName = "replicated-query"; - } + protected void queryTest( boolean useNamedRegion ) throws Exception { + // Bind a listener to the "local" cache + // Our region factory makes its CacheManager available to us + EmbeddedCacheManager localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); + // Bind a listener to the "remote" cache + EmbeddedCacheManager remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE); + String cacheName; + if (useNamedRegion) { + cacheName = "AccountRegion"; // As defined by ClassLoaderTestDAO via calls to query.setCacheRegion + // Define cache configurations for region early to avoid ending up with local caches for this region + localManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); + remoteManager.defineConfiguration(cacheName, "replicated-query", new org.infinispan.config.Configuration()); + } else { + cacheName = "replicated-query"; + } - localQueryCache = localManager.getCache(cacheName); - localQueryListener = new CacheAccessListener(); - localQueryCache.addListener(localQueryListener); + localQueryCache = localManager.getCache(cacheName); + localQueryListener = new CacheAccessListener(); + localQueryCache.addListener(localQueryListener); - TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); + TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); - remoteQueryCache = remoteManager.getCache(cacheName); - remoteQueryListener = new CacheAccessListener(); - remoteQueryCache.addListener(remoteQueryListener); + remoteQueryCache = remoteManager.getCache(cacheName); + remoteQueryListener = new CacheAccessListener(); + remoteQueryCache.addListener(remoteQueryListener); - TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); + TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); - SessionFactory localFactory = getEnvironment().getSessionFactory(); - SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); + SessionFactory localFactory = getEnvironment().getSessionFactory(); + SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); - ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); - ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); + ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); + ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); - // Initial ops on node 0 - setupEntities(dao0); + // Initial ops on node 0 + setupEntities(dao0); - String branch = "63088"; - // Query on post code count - assertEquals(branch + " has correct # of accounts", 6, dao0.getCountForBranch(branch, useNamedRegion)); - - assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); - localQueryListener.clearSawRegionModification(); - -// log.info("First query (get count for branch + " + branch + " ) on node0 done, contents of local query cache are: " + TestingUtil.printCache(localQueryCache)); + String branch = "63088"; + // Query on post code count + assertEquals(branch + " has correct # of accounts", 6, dao0.getCountForBranch(branch, useNamedRegion)); - // Sleep a bit to allow async repl to happen - sleep(SLEEP_TIME); + assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); + localQueryListener.clearSawRegionModification(); - assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); - remoteQueryListener.clearSawRegionModification(); + // LOG.info("First query (get count for branch + " + branch + " ) on node0 done, contents of local query cache are: " + + // TestingUtil.printCache(localQueryCache)); - // Do query again from node 1 - log.info("Repeat first query (get count for branch + " + branch + " ) on remote node"); - assertEquals("63088 has correct # of accounts", 6, dao1.getCountForBranch(branch, useNamedRegion)); - assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); - remoteQueryListener.clearSawRegionModification(); + // Sleep a bit to allow async repl to happen + sleep(SLEEP_TIME); - sleep(SLEEP_TIME); + assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); + remoteQueryListener.clearSawRegionModification(); - assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); - localQueryListener.clearSawRegionModification(); + // Do query again from node 1 + LOG.info("Repeat first query (get count for branch + " + branch + " ) on remote node"); + assertEquals("63088 has correct # of accounts", 6, dao1.getCountForBranch(branch, useNamedRegion)); + assertEquals("Query cache used", 1, remoteQueryListener.getSawRegionModificationCount()); + remoteQueryListener.clearSawRegionModification(); - log.info("First query on node 1 done"); + sleep(SLEEP_TIME); - // Sleep a bit to allow async repl to happen - sleep(SLEEP_TIME); + assertEquals("Query cache used", 1, localQueryListener.getSawRegionModificationCount()); + localQueryListener.clearSawRegionModification(); - // Do some more queries on node 0 - log.info("Do query Smith's branch"); - assertEquals("Correct branch for Smith", "94536", dao0.getBranch(dao0.getSmith(), useNamedRegion)); - log.info("Do query Jone's balance"); - assertEquals("Correct high balances for Jones", 40, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); + LOG.info("First query on node 1 done"); - assertEquals("Query cache used", 2, localQueryListener.getSawRegionModificationCount()); - localQueryListener.clearSawRegionModification(); -// // Clear the access state -// localQueryListener.getSawRegionAccess("???"); + // Sleep a bit to allow async repl to happen + sleep(SLEEP_TIME); - log.info("Second set of queries on node0 done"); + // Do some more queries on node 0 + LOG.info("Do query Smith's branch"); + assertEquals("Correct branch for Smith", "94536", dao0.getBranch(dao0.getSmith(), useNamedRegion)); + LOG.info("Do query Jone's balance"); + assertEquals("Correct high balances for Jones", 40, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); - // Sleep a bit to allow async repl to happen - sleep(SLEEP_TIME); + assertEquals("Query cache used", 2, localQueryListener.getSawRegionModificationCount()); + localQueryListener.clearSawRegionModification(); + // // Clear the access state + // localQueryListener.getSawRegionAccess("???"); - // Check if the previous queries replicated - assertEquals("Query cache remotely modified", 2, remoteQueryListener.getSawRegionModificationCount()); - remoteQueryListener.clearSawRegionModification(); + LOG.info("Second set of queries on node0 done"); - log.info("Repeat second set of queries on node1"); + // Sleep a bit to allow async repl to happen + sleep(SLEEP_TIME); - // Do queries again from node 1 - log.info("Again query Smith's branch"); - assertEquals("Correct branch for Smith", "94536", dao1.getBranch(dao1.getSmith(), useNamedRegion)); - log.info("Again query Jone's balance"); - assertEquals("Correct high balances for Jones", 40, dao1.getTotalBalance(dao1.getJones(), useNamedRegion)); + // Check if the previous queries replicated + assertEquals("Query cache remotely modified", 2, remoteQueryListener.getSawRegionModificationCount()); + remoteQueryListener.clearSawRegionModification(); - // Should be no change; query was already there - assertEquals("Query cache modified", 0, remoteQueryListener.getSawRegionModificationCount()); - assertEquals("Query cache accessed", 2, remoteQueryListener.getSawRegionAccessCount()); - remoteQueryListener.clearSawRegionAccess(); + LOG.info("Repeat second set of queries on node1"); - log.info("Second set of queries on node1 done"); + // Do queries again from node 1 + LOG.info("Again query Smith's branch"); + assertEquals("Correct branch for Smith", "94536", dao1.getBranch(dao1.getSmith(), useNamedRegion)); + LOG.info("Again query Jone's balance"); + assertEquals("Correct high balances for Jones", 40, dao1.getTotalBalance(dao1.getJones(), useNamedRegion)); - // allow async to propagate - sleep(SLEEP_TIME); + // Should be no change; query was already there + assertEquals("Query cache modified", 0, remoteQueryListener.getSawRegionModificationCount()); + assertEquals("Query cache accessed", 2, remoteQueryListener.getSawRegionAccessCount()); + remoteQueryListener.clearSawRegionAccess(); - // Modify underlying data on node 1 - modifyEntities(dao1); + LOG.info("Second set of queries on node1 done"); - // allow async timestamp change to propagate - sleep(SLEEP_TIME); + // allow async to propagate + sleep(SLEEP_TIME); - // Confirm query results are correct on node 0 - assertEquals("63088 has correct # of accounts", 7, dao0.getCountForBranch("63088", useNamedRegion)); - assertEquals("Correct branch for Smith", "63088", dao0.getBranch(dao0.getSmith(), useNamedRegion)); - assertEquals("Correct high balances for Jones", 50, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); - log.info("Third set of queries on node0 done"); - } + // Modify underlying data on node 1 + modifyEntities(dao1); - protected void setupEntities(ClassLoaderTestDAO dao) throws Exception { - dao.cleanup(); + // allow async timestamp change to propagate + sleep(SLEEP_TIME); - dao.createAccount(dao.getSmith(), new Integer(1001), new Integer(5), "94536"); - dao.createAccount(dao.getSmith(), new Integer(1002), new Integer(15), "94536"); - dao.createAccount(dao.getSmith(), new Integer(1003), new Integer(20), "94536"); + // Confirm query results are correct on node 0 + assertEquals("63088 has correct # of accounts", 7, dao0.getCountForBranch("63088", useNamedRegion)); + assertEquals("Correct branch for Smith", "63088", dao0.getBranch(dao0.getSmith(), useNamedRegion)); + assertEquals("Correct high balances for Jones", 50, dao0.getTotalBalance(dao0.getJones(), useNamedRegion)); + LOG.info("Third set of queries on node0 done"); + } - dao.createAccount(dao.getJones(), new Integer(2001), new Integer(5), "63088"); - dao.createAccount(dao.getJones(), new Integer(2002), new Integer(15), "63088"); - dao.createAccount(dao.getJones(), new Integer(2003), new Integer(20), "63088"); + protected void setupEntities( ClassLoaderTestDAO dao ) throws Exception { + dao.cleanup(); - dao.createAccount(dao.getBarney(), new Integer(3001), new Integer(5), "63088"); - dao.createAccount(dao.getBarney(), new Integer(3002), new Integer(15), "63088"); - dao.createAccount(dao.getBarney(), new Integer(3003), new Integer(20), "63088"); + dao.createAccount(dao.getSmith(), new Integer(1001), new Integer(5), "94536"); + dao.createAccount(dao.getSmith(), new Integer(1002), new Integer(15), "94536"); + dao.createAccount(dao.getSmith(), new Integer(1003), new Integer(20), "94536"); - log.info("Standard entities created"); - } + dao.createAccount(dao.getJones(), new Integer(2001), new Integer(5), "63088"); + dao.createAccount(dao.getJones(), new Integer(2002), new Integer(15), "63088"); + dao.createAccount(dao.getJones(), new Integer(2003), new Integer(20), "63088"); - protected void resetRegionUsageState(CacheAccessListener localListener, CacheAccessListener remoteListener) { - String stdName = StandardQueryCache.class.getName(); - String acctName = Account.class.getName(); + dao.createAccount(dao.getBarney(), new Integer(3001), new Integer(5), "63088"); + dao.createAccount(dao.getBarney(), new Integer(3002), new Integer(15), "63088"); + dao.createAccount(dao.getBarney(), new Integer(3003), new Integer(20), "63088"); - localListener.getSawRegionModification(stdName); - localListener.getSawRegionModification(acctName); + LOG.info("Standard entities created"); + } - localListener.getSawRegionAccess(stdName); - localListener.getSawRegionAccess(acctName); + protected void resetRegionUsageState( CacheAccessListener localListener, + CacheAccessListener remoteListener ) { + String stdName = StandardQueryCache.class.getName(); + String acctName = Account.class.getName(); - remoteListener.getSawRegionModification(stdName); - remoteListener.getSawRegionModification(acctName); + localListener.getSawRegionModification(stdName); + localListener.getSawRegionModification(acctName); - remoteListener.getSawRegionAccess(stdName); - remoteListener.getSawRegionAccess(acctName); + localListener.getSawRegionAccess(stdName); + localListener.getSawRegionAccess(acctName); - log.info("Region usage state cleared"); - } + remoteListener.getSawRegionModification(stdName); + remoteListener.getSawRegionModification(acctName); - protected void modifyEntities(ClassLoaderTestDAO dao) throws Exception { - dao.updateAccountBranch(1001, "63088"); - dao.updateAccountBalance(2001, 15); + remoteListener.getSawRegionAccess(stdName); + remoteListener.getSawRegionAccess(acctName); - log.info("Entities modified"); - } + LOG.info("Region usage state cleared"); + } + + protected void modifyEntities( ClassLoaderTestDAO dao ) throws Exception { + dao.updateAccountBranch(1001, "63088"); + dao.updateAccountBalance(2001, 15); + + LOG.info("Entities modified"); + } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoader.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoader.java index 33623ddb83..adfe1f3a93 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoader.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/classloader/SelectedClassnameClassLoader.java @@ -23,210 +23,201 @@ */ package org.hibernate.test.cache.infinispan.functional.classloader; +import static org.hibernate.test.cache.infinispan.TestInfinispanLogger.LOG; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** - * A ClassLoader that loads classes whose classname begins with one of a given set of strings, - * without attempting first to delegate to its parent loader. + * A ClassLoader that loads classes whose classname begins with one of a given set of strings, without attempting first to delegate + * to its parent loader. *

- * This class is intended to allow emulation of 2 different types of common J2EE classloading - * situations. + * This class is intended to allow emulation of 2 different types of common J2EE classloading situations. *

    *
  • Servlet-style child-first classloading, where this class is the child loader.
  • *
  • Parent-first classloading where the parent does not have access to certain classes
  • *
*

*

- * This class can also be configured to raise a ClassNotFoundException if asked to load certain - * classes, thus allowing classes on the classpath to be hidden from a test environment. + * This class can also be configured to raise a ClassNotFoundException if asked to load certain classes, thus allowing classes on + * the classpath to be hidden from a test environment. *

- * + * * @author Brian Stansberry */ public class SelectedClassnameClassLoader extends ClassLoader { - private Logger log = LoggerFactory.getLogger(SelectedClassnameClassLoader.class); - private String[] includedClasses = null; - private String[] excludedClasses = null; - private String[] notFoundClasses = null; + private String[] includedClasses = null; + private String[] excludedClasses = null; + private String[] notFoundClasses = null; - private Map classes = new java.util.HashMap(); + private Map classes = new java.util.HashMap(); - /** - * Creates a new classloader that loads the given classes. - * - * @param includedClasses - * array of class or package names that should be directly loaded by this loader. - * Classes whose name starts with any of the strings in this array will be loaded by - * this class, unless their name appears in excludedClasses. Can be - * null - * @param excludedClasses - * array of class or package names that should NOT be directly loaded by this loader. - * Loading of classes whose name starts with any of the strings in this array will be - * delegated to parent, even if the classes package or classname appears - * in includedClasses. Typically this parameter is used to exclude loading - * one or more classes in a package whose other classes are loaded by this object. - * @param parent - * ClassLoader to which loading of classes should be delegated if necessary - */ - public SelectedClassnameClassLoader(String[] includedClasses, String[] excludedClasses, ClassLoader parent) { - this(includedClasses, excludedClasses, null, parent); - } + /** + * Creates a new classloader that loads the given classes. + * + * @param includedClasses array of class or package names that should be directly loaded by this loader. Classes whose name + * starts with any of the strings in this array will be loaded by this class, unless their name appears in + * excludedClasses. Can be null + * @param excludedClasses array of class or package names that should NOT be directly loaded by this loader. Loading of classes + * whose name starts with any of the strings in this array will be delegated to parent, even if the classes + * package or classname appears in includedClasses. Typically this parameter is used to exclude loading one + * or more classes in a package whose other classes are loaded by this object. + * @param parent ClassLoader to which loading of classes should be delegated if necessary + */ + public SelectedClassnameClassLoader( String[] includedClasses, + String[] excludedClasses, + ClassLoader parent ) { + this(includedClasses, excludedClasses, null, parent); + } - /** - * Creates a new classloader that loads the given classes. - * - * @param includedClasses - * array of class or package names that should be directly loaded by this loader. - * Classes whose name starts with any of the strings in this array will be loaded by - * this class, unless their name appears in excludedClasses. Can be - * null - * @param excludedClasses - * array of class or package names that should NOT be directly loaded by this loader. - * Loading of classes whose name starts with any of the strings in this array will be - * delegated to parent, even if the classes package or classname appears - * in includedClasses. Typically this parameter is used to exclude loading - * one or more classes in a package whose other classes are loaded by this object. - * @param notFoundClasses - * array of class or package names for which this should raise a ClassNotFoundException - * @param parent - * ClassLoader to which loading of classes should be delegated if necessary - */ - public SelectedClassnameClassLoader(String[] includedClasses, String[] excludedClasses, String[] notFoundClasses, - ClassLoader parent) { - super(parent); - this.includedClasses = includedClasses; - this.excludedClasses = excludedClasses; - this.notFoundClasses = notFoundClasses; + /** + * Creates a new classloader that loads the given classes. + * + * @param includedClasses array of class or package names that should be directly loaded by this loader. Classes whose name + * starts with any of the strings in this array will be loaded by this class, unless their name appears in + * excludedClasses. Can be null + * @param excludedClasses array of class or package names that should NOT be directly loaded by this loader. Loading of classes + * whose name starts with any of the strings in this array will be delegated to parent, even if the classes + * package or classname appears in includedClasses. Typically this parameter is used to exclude loading one + * or more classes in a package whose other classes are loaded by this object. + * @param notFoundClasses array of class or package names for which this should raise a ClassNotFoundException + * @param parent ClassLoader to which loading of classes should be delegated if necessary + */ + public SelectedClassnameClassLoader( String[] includedClasses, + String[] excludedClasses, + String[] notFoundClasses, + ClassLoader parent ) { + super(parent); + this.includedClasses = includedClasses; + this.excludedClasses = excludedClasses; + this.notFoundClasses = notFoundClasses; - log.debug("created " + this); - } + LOG.debug("created " + this); + } - protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - log.trace("loadClass(" + name + "," + resolve + ")"); - if (isIncluded(name) && (isExcluded(name) == false)) { - Class c = findClass(name); + @Override + protected synchronized Class loadClass( String name, + boolean resolve ) throws ClassNotFoundException { + LOG.trace("loadClass(" + name + "," + resolve + ")"); + if (isIncluded(name) && (isExcluded(name) == false)) { + Class c = findClass(name); - if (resolve) { - resolveClass(c); - } - return c; - } else if (isNotFound(name)) { - throw new ClassNotFoundException(name + " is discarded"); - } else { - return super.loadClass(name, resolve); - } - } - - protected Class findClass(String name) throws ClassNotFoundException { - log.trace("findClass(" + name + ")"); - Class result = classes.get(name); - if (result != null) { - return result; - } - - if (isIncluded(name) && (isExcluded(name) == false)) { - result = createClass(name); - } else if (isNotFound(name)) { - throw new ClassNotFoundException(name + " is discarded"); - } else { - result = super.findClass(name); - } - - classes.put(name, result); - - return result; - } - - protected Class createClass(String name) throws ClassFormatError, ClassNotFoundException { - log.info("createClass(" + name + ")"); - try { - InputStream is = getResourceAsStream(name.replace('.', '/').concat(".class")); - byte[] bytes = new byte[1024]; - ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); - int read; - while ((read = is.read(bytes)) > -1) { - baos.write(bytes, 0, read); - } - bytes = baos.toByteArray(); - return this.defineClass(name, bytes, 0, bytes.length); - } catch (FileNotFoundException e) { - throw new ClassNotFoundException("cannot find " + name, e); - } catch (IOException e) { - throw new ClassNotFoundException("cannot read " + name, e); - } - } - - protected boolean isIncluded(String className) { - - if (includedClasses != null) { - for (int i = 0; i < includedClasses.length; i++) { - if (className.startsWith(includedClasses[i])) { - return true; + if (resolve) { + resolveClass(c); } - } - } + return c; + } else if (isNotFound(name)) { + throw new ClassNotFoundException(name + " is discarded"); + } else { + return super.loadClass(name, resolve); + } + } - return false; - } + @Override + protected Class findClass( String name ) throws ClassNotFoundException { + LOG.trace("findClass(" + name + ")"); + Class result = classes.get(name); + if (result != null) { + return result; + } - protected boolean isExcluded(String className) { + if (isIncluded(name) && (isExcluded(name) == false)) { + result = createClass(name); + } else if (isNotFound(name)) { + throw new ClassNotFoundException(name + " is discarded"); + } else { + result = super.findClass(name); + } - if (excludedClasses != null) { - for (int i = 0; i < excludedClasses.length; i++) { - if (className.startsWith(excludedClasses[i])) { - return true; + classes.put(name, result); + + return result; + } + + protected Class createClass( String name ) throws ClassFormatError, ClassNotFoundException { + LOG.info("createClass(" + name + ")"); + try { + InputStream is = getResourceAsStream(name.replace('.', '/').concat(".class")); + byte[] bytes = new byte[1024]; + ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); + int read; + while ((read = is.read(bytes)) > -1) { + baos.write(bytes, 0, read); } - } - } + bytes = baos.toByteArray(); + return this.defineClass(name, bytes, 0, bytes.length); + } catch (FileNotFoundException e) { + throw new ClassNotFoundException("cannot find " + name, e); + } catch (IOException e) { + throw new ClassNotFoundException("cannot read " + name, e); + } + } - return false; - } + protected boolean isIncluded( String className ) { - protected boolean isNotFound(String className) { - - if (notFoundClasses != null) { - for (int i = 0; i < notFoundClasses.length; i++) { - if (className.startsWith(notFoundClasses[i])) { - return true; + if (includedClasses != null) { + for (int i = 0; i < includedClasses.length; i++) { + if (className.startsWith(includedClasses[i])) { + return true; + } } - } - } + } - return false; - } + return false; + } - public String toString() { - String s = getClass().getName(); - s += "[includedClasses="; - s += listClasses(includedClasses); - s += ";excludedClasses="; - s += listClasses(excludedClasses); - s += ";notFoundClasses="; - s += listClasses(notFoundClasses); - s += ";parent="; - s += getParent(); - s += "]"; - return s; - } + protected boolean isExcluded( String className ) { - private static String listClasses(String[] classes) { - if (classes == null) - return null; - String s = ""; - for (int i = 0; i < classes.length; i++) { - if (i > 0) - s += ","; - s += classes[i]; - } - return s; - } + if (excludedClasses != null) { + for (int i = 0; i < excludedClasses.length; i++) { + if (className.startsWith(excludedClasses[i])) { + return true; + } + } + } + + return false; + } + + protected boolean isNotFound( String className ) { + + if (notFoundClasses != null) { + for (int i = 0; i < notFoundClasses.length; i++) { + if (className.startsWith(notFoundClasses[i])) { + return true; + } + } + } + + return false; + } + + @Override + public String toString() { + String s = getClass().getName(); + s += "[includedClasses="; + s += listClasses(includedClasses); + s += ";excludedClasses="; + s += listClasses(excludedClasses); + s += ";notFoundClasses="; + s += listClasses(notFoundClasses); + s += ";parent="; + s += getParent(); + s += "]"; + return s; + } + + private static String listClasses( String[] classes ) { + if (classes == null) return null; + String s = ""; + for (int i = 0; i < classes.length; i++) { + if (i > 0) s += ","; + s += classes[i]; + } + return s; + } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/SessionRefreshTestCase.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/SessionRefreshTestCase.java index a33bba069d..20741e81db 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/SessionRefreshTestCase.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/cluster/SessionRefreshTestCase.java @@ -22,119 +22,115 @@ package org.hibernate.test.cache.infinispan.functional.cluster; import javax.transaction.TransactionManager; - import org.hibernate.SessionFactory; import org.hibernate.cache.infinispan.InfinispanRegionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; +import org.hibernate.test.cache.infinispan.TestInfinispanLogger; import org.hibernate.test.cache.infinispan.functional.classloader.Account; import org.hibernate.test.cache.infinispan.functional.classloader.ClassLoaderTestDAO; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.test.TestingUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * SessionRefreshTestCase. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public class SessionRefreshTestCase extends DualNodeTestCase { - public static final String OUR_PACKAGE = SessionRefreshTestCase.class.getPackage().getName(); - - protected final Logger log = LoggerFactory.getLogger(getClass()); + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - static int test = 0; - - private Cache localCache; + public static final String OUR_PACKAGE = SessionRefreshTestCase.class.getPackage().getName(); - public SessionRefreshTestCase(String string) { - super(string); - } + static int test = 0; - protected String getEntityCacheConfigName() { - return "entity"; - } - - /** - * Disables use of the second level cache for this session factory. - * - * {@inheritDoc} - */ - @Override - protected void configureSecondNode(Configuration cfg) { - super.configureSecondNode(cfg); - cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false"); - } - - @Override - protected void standardConfigure(Configuration cfg) { - super.standardConfigure(cfg); - cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, getEntityCacheConfigName()); - } + private Cache localCache; - @Override - public String[] getMappings() { - return new String[] { "cache/infinispan/functional/classloader/Account.hbm.xml" }; - } + public SessionRefreshTestCase( String string ) { + super(string); + } - @Override - protected void cleanupTransactionManagement() { - // Don't clean up the managers, just the transactions - // Managers are still needed by the long-lived caches - DualNodeJtaTransactionManagerImpl.cleanupTransactions(); - } + protected String getEntityCacheConfigName() { + return "entity"; + } - public void testRefreshAfterExternalChange() throws Exception { - // First session factory uses a cache - CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); - localCache = localManager.getCache(Account.class.getName()); - TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); - SessionFactory localFactory = getEnvironment().getSessionFactory(); + /** + * Disables use of the second level cache for this session factory. {@inheritDoc} + */ + @Override + protected void configureSecondNode( Configuration cfg ) { + super.configureSecondNode(cfg); + cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false"); + } - // Second session factory doesn't; just needs a transaction manager - // However, start at least the cache to avoid issues with replication and cache not being there - ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE).getCache(Account.class.getName()); - TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); - SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); + @Override + protected void standardConfigure( Configuration cfg ) { + super.standardConfigure(cfg); + cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, getEntityCacheConfigName()); + } - ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); - ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); + @Override + public String[] getMappings() { + return new String[] {"cache/infinispan/functional/classloader/Account.hbm.xml"}; + } - Integer id = new Integer(1); - dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTestCase.LOCAL); + @Override + protected void cleanupTransactionManagement() { + // Don't clean up the managers, just the transactions + // Managers are still needed by the long-lived caches + DualNodeJtaTransactionManagerImpl.cleanupTransactions(); + } - // Basic sanity check - Account acct1 = dao1.getAccount(id); - assertNotNull(acct1); - assertEquals(DualNodeTestCase.LOCAL, acct1.getBranch()); + public void testRefreshAfterExternalChange() throws Exception { + // First session factory uses a cache + CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.LOCAL); + localCache = localManager.getCache(Account.class.getName()); + TransactionManager localTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.LOCAL); + SessionFactory localFactory = getEnvironment().getSessionFactory(); - // This dao's session factory isn't caching, so cache won't see this change - dao1.updateAccountBranch(id, DualNodeTestCase.REMOTE); + // Second session factory doesn't; just needs a transaction manager + // However, start at least the cache to avoid issues with replication and cache not being there + ClusterAwareRegionFactory.getCacheManager(DualNodeTestCase.REMOTE).getCache(Account.class.getName()); + TransactionManager remoteTM = DualNodeJtaTransactionManagerImpl.getInstance(DualNodeTestCase.REMOTE); + SessionFactory remoteFactory = getSecondNodeEnvironment().getSessionFactory(); - // dao1's session doesn't touch the cache, - // so reading from dao0 should show a stale value from the cache - // (we check to confirm the cache is used) - Account acct0 = dao0.getAccount(id); - assertNotNull(acct0); - assertEquals(DualNodeTestCase.LOCAL, acct0.getBranch()); - log.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache)); + ClassLoaderTestDAO dao0 = new ClassLoaderTestDAO(localFactory, localTM); + ClassLoaderTestDAO dao1 = new ClassLoaderTestDAO(remoteFactory, remoteTM); - // Now call session.refresh and confirm we get the correct value - acct0 = dao0.getAccountWithRefresh(id); - assertNotNull(acct0); - assertEquals(DualNodeTestCase.REMOTE, acct0.getBranch()); - log.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache)); + Integer id = new Integer(1); + dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTestCase.LOCAL); - // Double check with a brand new session, in case the other session - // for some reason bypassed the 2nd level cache - ClassLoaderTestDAO dao0A = new ClassLoaderTestDAO(localFactory, localTM); - Account acct0A = dao0A.getAccount(id); - assertNotNull(acct0A); - assertEquals(DualNodeTestCase.REMOTE, acct0A.getBranch()); - log.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache)); - } + // Basic sanity check + Account acct1 = dao1.getAccount(id); + assertNotNull(acct1); + assertEquals(DualNodeTestCase.LOCAL, acct1.getBranch()); + + // This dao's session factory isn't caching, so cache won't see this change + dao1.updateAccountBranch(id, DualNodeTestCase.REMOTE); + + // dao1's session doesn't touch the cache, + // so reading from dao0 should show a stale value from the cache + // (we check to confirm the cache is used) + Account acct0 = dao0.getAccount(id); + assertNotNull(acct0); + assertEquals(DualNodeTestCase.LOCAL, acct0.getBranch()); + LOG.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache)); + + // Now call session.refresh and confirm we get the correct value + acct0 = dao0.getAccountWithRefresh(id); + assertNotNull(acct0); + assertEquals(DualNodeTestCase.REMOTE, acct0.getBranch()); + LOG.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache)); + + // Double check with a brand new session, in case the other session + // for some reason bypassed the 2nd level cache + ClassLoaderTestDAO dao0A = new ClassLoaderTestDAO(localFactory, localTM); + Account acct0A = dao0A.getAccount(id); + assertNotNull(acct0A); + assertEquals(DualNodeTestCase.REMOTE, acct0A.getBranch()); + LOG.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache)); + } } 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 e1180116d9..9a0e1efbfc 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 @@ -26,9 +26,7 @@ package org.hibernate.test.cache.infinispan.query; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import junit.framework.AssertionFailedError; - import org.hibernate.cache.CacheDataDescription; import org.hibernate.cache.QueryResultsRegion; import org.hibernate.cache.Region; @@ -38,6 +36,7 @@ import org.hibernate.cache.infinispan.util.CacheAdapter; import org.hibernate.cache.infinispan.util.CacheAdapterImpl; import org.hibernate.cfg.Configuration; import org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTestCase; +import org.hibernate.test.cache.infinispan.TestInfinispanLogger; import org.hibernate.test.cache.infinispan.util.CacheTestUtil; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; @@ -47,257 +46,259 @@ import org.infinispan.util.concurrent.IsolationLevel; /** * Tests of QueryResultRegionImpl. - * + * * @author Galder ZamarreƱo * @since 3.5 */ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase { - // protected static final String REGION_NAME = "test/" + StandardQueryCache.class.getName(); + private static final TestInfinispanLogger LOG = TestInfinispanLogger.LOG; - /** - * Create a new EntityRegionImplTestCase. - * - * @param name - */ - public QueryRegionImplTestCase(String name) { - super(name); - } + // protected static final String REGION_NAME = "test/" + StandardQueryCache.class.getName(); - @Override - protected Region createRegion(InfinispanRegionFactory regionFactory, String regionName, Properties properties, CacheDataDescription cdd) { - return regionFactory.buildQueryResultsRegion(regionName, properties); - } + /** + * Create a new EntityRegionImplTestCase. + * + * @param name + */ + public QueryRegionImplTestCase( String name ) { + super(name); + } - @Override - protected String getStandardRegionName(String regionPrefix) { - return regionPrefix + "/" + StandardQueryCache.class.getName(); - } + @Override + protected Region createRegion( InfinispanRegionFactory regionFactory, + String regionName, + Properties properties, + CacheDataDescription cdd ) { + return regionFactory.buildQueryResultsRegion(regionName, properties); + } - @Override - protected CacheAdapter getInfinispanCache(InfinispanRegionFactory regionFactory) { - return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache("local-query")); - } - - @Override - protected Configuration createConfiguration() { - return CacheTestUtil.buildCustomQueryCacheConfiguration("test", "replicated-query"); - } + @Override + protected String getStandardRegionName( String regionPrefix ) { + return regionPrefix + "/" + StandardQueryCache.class.getName(); + } - public void testPutDoesNotBlockGet() throws Exception { - putDoesNotBlockGetTest(); - } + @Override + protected CacheAdapter getInfinispanCache( InfinispanRegionFactory regionFactory ) { + return CacheAdapterImpl.newInstance(regionFactory.getCacheManager().getCache("local-query")); + } - private void putDoesNotBlockGetTest() throws Exception { - Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport()); + @Override + protected Configuration createConfiguration() { + return CacheTestUtil.buildCustomQueryCacheConfiguration("test", "replicated-query"); + } - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + public void testPutDoesNotBlockGet() throws Exception { + putDoesNotBlockGetTest(); + } - final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), cfg - .getProperties()); + private void putDoesNotBlockGetTest() throws Exception { + Configuration cfg = createConfiguration(); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); - region.put(KEY, VALUE1); - assertEquals(VALUE1, region.get(KEY)); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - final CountDownLatch readerLatch = new CountDownLatch(1); - final CountDownLatch writerLatch = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(1); - final ExceptionHolder holder = new ExceptionHolder(); + final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), + cfg.getProperties()); - Thread reader = new Thread() { - public void run() { - try { - BatchModeTransactionManager.getInstance().begin(); - log.debug("Transaction began, get value for key"); - assertTrue(VALUE2.equals(region.get(KEY)) == false); - BatchModeTransactionManager.getInstance().commit(); - } catch (AssertionFailedError e) { - holder.a1 = e; - rollback(); - } catch (Exception e) { - holder.e1 = e; - rollback(); - } finally { - readerLatch.countDown(); + region.put(KEY, VALUE1); + assertEquals(VALUE1, region.get(KEY)); + + final CountDownLatch readerLatch = new CountDownLatch(1); + final CountDownLatch writerLatch = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(1); + final ExceptionHolder holder = new ExceptionHolder(); + + Thread reader = new Thread() { + @Override + public void run() { + try { + BatchModeTransactionManager.getInstance().begin(); + LOG.debug("Transaction began, get value for key"); + assertTrue(VALUE2.equals(region.get(KEY)) == false); + BatchModeTransactionManager.getInstance().commit(); + } catch (AssertionFailedError e) { + holder.a1 = e; + rollback(); + } catch (Exception e) { + holder.e1 = e; + rollback(); + } finally { + readerLatch.countDown(); + } } - } - }; + }; - Thread writer = new Thread() { - public void run() { - try { - BatchModeTransactionManager.getInstance().begin(); - log.debug("Put value2"); - region.put(KEY, VALUE2); - log.debug("Put finished for value2, await writer latch"); - writerLatch.await(); - log.debug("Writer latch finished"); - BatchModeTransactionManager.getInstance().commit(); - log.debug("Transaction committed"); - } catch (Exception e) { - holder.e2 = e; - rollback(); - } finally { - completionLatch.countDown(); + Thread writer = new Thread() { + @Override + public void run() { + try { + BatchModeTransactionManager.getInstance().begin(); + LOG.debug("Put value2"); + region.put(KEY, VALUE2); + LOG.debug("Put finished for value2, await writer latch"); + writerLatch.await(); + LOG.debug("Writer latch finished"); + BatchModeTransactionManager.getInstance().commit(); + LOG.debug("Transaction committed"); + } catch (Exception e) { + holder.e2 = e; + rollback(); + } finally { + completionLatch.countDown(); + } } - } - }; + }; - reader.setDaemon(true); - writer.setDaemon(true); + reader.setDaemon(true); + writer.setDaemon(true); - writer.start(); - assertFalse("Writer is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); + writer.start(); + assertFalse("Writer is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); - // Start the reader - reader.start(); - assertTrue("Reader finished promptly", readerLatch.await(1000000000, TimeUnit.MILLISECONDS)); + // Start the reader + reader.start(); + assertTrue("Reader finished promptly", readerLatch.await(1000000000, TimeUnit.MILLISECONDS)); - writerLatch.countDown(); - assertTrue("Reader finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); + writerLatch.countDown(); + assertTrue("Reader finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); - assertEquals(VALUE2, region.get(KEY)); + assertEquals(VALUE2, region.get(KEY)); - if (holder.a1 != null) - throw holder.a1; - else if (holder.a2 != null) - throw holder.a2; + if (holder.a1 != null) throw holder.a1; + else if (holder.a2 != null) throw holder.a2; - assertEquals("writer saw no exceptions", null, holder.e1); - assertEquals("reader saw no exceptions", null, holder.e2); - } + assertEquals("writer saw no exceptions", null, holder.e1); + assertEquals("reader saw no exceptions", null, holder.e2); + } - public void testGetDoesNotBlockPut() throws Exception { - getDoesNotBlockPutTest(); - } + public void testGetDoesNotBlockPut() throws Exception { + getDoesNotBlockPutTest(); + } - private void getDoesNotBlockPutTest() throws Exception { - Configuration cfg = createConfiguration(); - InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory( - getJdbcServices(), cfg, getCacheTestSupport() - ); + private void getDoesNotBlockPutTest() throws Exception { + Configuration cfg = createConfiguration(); + InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(getJdbcServices(), cfg, getCacheTestSupport()); - // Sleep a bit to avoid concurrent FLUSH problem - avoidConcurrentFlush(); + // Sleep a bit to avoid concurrent FLUSH problem + avoidConcurrentFlush(); - final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), cfg - .getProperties()); + final QueryResultsRegion region = regionFactory.buildQueryResultsRegion(getStandardRegionName(REGION_PREFIX), + cfg.getProperties()); - region.put(KEY, VALUE1); - assertEquals(VALUE1, region.get(KEY)); + region.put(KEY, VALUE1); + assertEquals(VALUE1, region.get(KEY)); - // final Fqn rootFqn = getRegionFqn(getStandardRegionName(REGION_PREFIX), REGION_PREFIX); - final CacheAdapter jbc = getInfinispanCache(regionFactory); + // final Fqn rootFqn = getRegionFqn(getStandardRegionName(REGION_PREFIX), REGION_PREFIX); + final CacheAdapter jbc = getInfinispanCache(regionFactory); - final CountDownLatch blockerLatch = new CountDownLatch(1); - final CountDownLatch writerLatch = new CountDownLatch(1); - final CountDownLatch completionLatch = new CountDownLatch(1); - final ExceptionHolder holder = new ExceptionHolder(); + final CountDownLatch blockerLatch = new CountDownLatch(1); + final CountDownLatch writerLatch = new CountDownLatch(1); + final CountDownLatch completionLatch = new CountDownLatch(1); + final ExceptionHolder holder = new ExceptionHolder(); - Thread blocker = new Thread() { + Thread blocker = new Thread() { - public void run() { - // Fqn toBlock = new Fqn(rootFqn, KEY); - GetBlocker blocker = new GetBlocker(blockerLatch, KEY); - try { - jbc.addListener(blocker); + @Override + public void run() { + // Fqn toBlock = new Fqn(rootFqn, KEY); + GetBlocker blocker = new GetBlocker(blockerLatch, KEY); + try { + jbc.addListener(blocker); - BatchModeTransactionManager.getInstance().begin(); - region.get(KEY); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - holder.e1 = e; - rollback(); - } finally { - jbc.removeListener(blocker); + BatchModeTransactionManager.getInstance().begin(); + region.get(KEY); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + holder.e1 = e; + rollback(); + } finally { + jbc.removeListener(blocker); + } } - } - }; + }; - Thread writer = new Thread() { + Thread writer = new Thread() { - public void run() { - try { - writerLatch.await(); + @Override + public void run() { + try { + writerLatch.await(); - BatchModeTransactionManager.getInstance().begin(); - region.put(KEY, VALUE2); - BatchModeTransactionManager.getInstance().commit(); - } catch (Exception e) { - holder.e2 = e; - rollback(); - } finally { - completionLatch.countDown(); + BatchModeTransactionManager.getInstance().begin(); + region.put(KEY, VALUE2); + BatchModeTransactionManager.getInstance().commit(); + } catch (Exception e) { + holder.e2 = e; + rollback(); + } finally { + completionLatch.countDown(); + } } - } - }; + }; - blocker.setDaemon(true); - writer.setDaemon(true); + blocker.setDaemon(true); + writer.setDaemon(true); - boolean unblocked = false; - try { - blocker.start(); - writer.start(); + boolean unblocked = false; + try { + blocker.start(); + writer.start(); - assertFalse("Blocker is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); - // Start the writer - writerLatch.countDown(); - assertTrue("Writer finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); + assertFalse("Blocker is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS)); + // Start the writer + writerLatch.countDown(); + assertTrue("Writer finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS)); - blockerLatch.countDown(); - unblocked = true; - - if (IsolationLevel.REPEATABLE_READ.equals(jbc.getConfiguration().getIsolationLevel())) { - assertEquals(VALUE1, region.get(KEY)); - } else { - assertEquals(VALUE2, region.get(KEY)); - } - - if (holder.a1 != null) - throw holder.a1; - else if (holder.a2 != null) - throw holder.a2; - - assertEquals("blocker saw no exceptions", null, holder.e1); - assertEquals("writer saw no exceptions", null, holder.e2); - } finally { - if (!unblocked) blockerLatch.countDown(); - } - } + unblocked = true; - @Listener - public class GetBlocker { - - private CountDownLatch latch; - // private Fqn fqn; - private Object key; - - GetBlocker(CountDownLatch latch, Object key) { - this.latch = latch; - this.key = key; - } - - @CacheEntryVisited - public void nodeVisisted(CacheEntryVisitedEvent event) { - if (event.isPre() && event.getKey().equals(key)) { - try { - latch.await(); - } catch (InterruptedException e) { - log.error("Interrupted waiting for latch", e); + if (IsolationLevel.REPEATABLE_READ.equals(jbc.getConfiguration().getIsolationLevel())) { + assertEquals(VALUE1, region.get(KEY)); + } else { + assertEquals(VALUE2, region.get(KEY)); } - } - } - } - private class ExceptionHolder { - Exception e1; - Exception e2; - AssertionFailedError a1; - AssertionFailedError a2; - } + if (holder.a1 != null) throw holder.a1; + else if (holder.a2 != null) throw holder.a2; + + assertEquals("blocker saw no exceptions", null, holder.e1); + assertEquals("writer saw no exceptions", null, holder.e2); + } finally { + if (!unblocked) blockerLatch.countDown(); + } + } + + @Listener + public class GetBlocker { + + private CountDownLatch latch; + // private Fqn fqn; + private Object key; + + GetBlocker( CountDownLatch latch, + Object key ) { + this.latch = latch; + this.key = key; + } + + @CacheEntryVisited + public void nodeVisisted( CacheEntryVisitedEvent event ) { + if (event.isPre() && event.getKey().equals(key)) { + try { + latch.await(); + } catch (InterruptedException e) { + LOG.error("Interrupted waiting for latch", e); + } + } + } + } + + private class ExceptionHolder { + Exception e1; + Exception e2; + AssertionFailedError a1; + AssertionFailedError a2; + } } diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestSupport.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestSupport.java index 6de9b2d2a9..5c2d50b477 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestSupport.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/util/CacheTestSupport.java @@ -23,54 +23,46 @@ */ package org.hibernate.test.cache.infinispan.util; +import static org.hibernate.test.cache.infinispan.TestInfinispanLogger.LOG; import java.util.HashSet; import java.util.Iterator; import java.util.Set; - -import org.slf4j.Logger; - import org.hibernate.cache.RegionFactory; import org.infinispan.Cache; /** * Support class for tracking and cleaning up objects used in tests. - * + * * @author Brian Stansberry */ public class CacheTestSupport { - + private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack"; - - private Logger log; - + private Set caches = new HashSet(); private Set factories = new HashSet(); private Exception exception; private String preferIPv4Stack; - - public CacheTestSupport(Logger log) { - this.log = log; - } - + public void registerCache(Cache cache) { caches.add(cache); } - + public void registerFactory(RegionFactory factory) { factories.add(factory); } - + public void unregisterCache(Cache cache) { caches.remove(cache); } - + public void unregisterFactory(RegionFactory factory) { factories.remove(factory); } - - public void setUp() throws Exception { - - // Try to ensure we use IPv4; otherwise cluster formation is very slow + + public void setUp() throws Exception { + + // Try to ensure we use IPv4; otherwise cluster formation is very slow preferIPv4Stack = System.getProperty(PREFER_IPV4STACK); System.setProperty(PREFER_IPV4STACK, "true"); @@ -78,29 +70,29 @@ public class CacheTestSupport { throwStoredException(); } - public void tearDown() throws Exception { - + public void tearDown() throws Exception { + if (preferIPv4Stack == null) System.clearProperty(PREFER_IPV4STACK); - else + else System.setProperty(PREFER_IPV4STACK, preferIPv4Stack); - + cleanUp(); throwStoredException(); } - + public void avoidConcurrentFlush() { // JG 2.6.1 has a problem where calling flush more than once too quickly // can result in several second delays sleep(100); } - + private void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { - log.warn("Interrupted during sleep", e); + LOG.warn("Interrupted during sleep", e); } } @@ -115,9 +107,9 @@ public class CacheTestSupport { finally { it.remove(); } - } + } factories.clear(); - + for (Iterator it = caches.iterator(); it.hasNext(); ) { try { Cache cache = (Cache) it.next(); @@ -130,16 +122,16 @@ public class CacheTestSupport { it.remove(); } avoidConcurrentFlush(); - } + } caches.clear(); } - + private void storeException(Exception e) { if (this.exception == null) { this.exception = e; } } - + private void throwStoredException() throws Exception { if (exception != null) { Exception toThrow = exception; diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java index 43c111220c..b3cc938353 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java +++ b/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java @@ -27,17 +27,12 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.util.StringHelper; import org.hibernate.util.ConfigHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import org.hibernate.util.StringHelper; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.ProxoolFacade; import org.logicalcobwebs.proxool.configuration.JAXPConfigurator; @@ -50,11 +45,11 @@ import org.logicalcobwebs.proxool.configuration.PropertyConfigurator; */ public class ProxoolConnectionProvider implements ConnectionProvider { + public static final ProxoolLogger LOG = org.jboss.logging.Logger.getMessageLogger(ProxoolLogger.class, + ProxoolConnectionProvider.class.getPackage().getName()); private static final String PROXOOL_JDBC_STEM = "proxool."; - private static final Logger log = LoggerFactory.getLogger(ProxoolConnectionProvider.class); - private String proxoolAlias; // TRUE if the pool is borrowed from the outside, FALSE if we used to create it @@ -63,7 +58,7 @@ public class ProxoolConnectionProvider implements ConnectionProvider { // Not null if the Isolation level has been specified in the configuration file. // Otherwise, it is left to the Driver's default value. private Integer isolation; - + private boolean autocommit; /** @@ -114,8 +109,8 @@ public class ProxoolConnectionProvider implements ConnectionProvider { // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = "Cannot configure Proxool Provider to use an existing in memory pool without the " + Environment.PROXOOL_POOL_ALIAS + " property set."; - log.error( msg ); + String msg = LOG.unableToConfigureProxoolProviderToUseExistingInMemoryPool(Environment.PROXOOL_POOL_ALIAS); + LOG.error(msg); throw new HibernateException( msg ); } // Append the stem to the proxool pool alias @@ -124,18 +119,18 @@ public class ProxoolConnectionProvider implements ConnectionProvider { // Set the existing pool flag to true existingPool = true; - log.info( "Configuring Proxool Provider using existing pool in memory: " + proxoolAlias ); + LOG.configuringProxoolProviderUsingExistingPool(proxoolAlias); // Configured using the JAXP Configurator } else if ( StringHelper.isNotEmpty( jaxpFile ) ) { - log.info( "Configuring Proxool Provider using JAXPConfigurator: " + jaxpFile ); + LOG.configuringProxoolProviderUsingJaxpConfigurator(jaxpFile); // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = "Cannot configure Proxool Provider to use JAXP without the " + Environment.PROXOOL_POOL_ALIAS + " property set."; - log.error( msg ); + String msg = LOG.unableToConfigureProxoolProviderToUseJaxp(Environment.PROXOOL_POOL_ALIAS); + LOG.error(msg); throw new HibernateException( msg ); } @@ -143,25 +138,25 @@ public class ProxoolConnectionProvider implements ConnectionProvider { JAXPConfigurator.configure( ConfigHelper.getConfigStreamReader( jaxpFile ), false ); } catch ( ProxoolException e ) { - String msg = "Proxool Provider unable to load JAXP configurator file: " + jaxpFile; - log.error( msg, e ); + String msg = LOG.unableToLoadJaxpConfiguratorFile(jaxpFile); + LOG.error(msg, e); throw new HibernateException( msg, e ); } // Append the stem to the proxool pool alias proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias; - log.info("Configuring Proxool Provider to use pool alias: " + proxoolAlias); + LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias); // Configured using the Properties File Configurator } else if ( StringHelper.isNotEmpty( propFile ) ) { - log.info( "Configuring Proxool Provider using Properties File: " + propFile ); + LOG.configuringProxoolProviderUsingPropertiesFile(propFile); // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = "Cannot configure Proxool Provider to use Properties File without the " + Environment.PROXOOL_POOL_ALIAS + " property set."; - log.error( msg ); + String msg = LOG.unableToConfigureProxoolProviderToUsePropertiesFile(Environment.PROXOOL_POOL_ALIAS); + LOG.error(msg); throw new HibernateException( msg ); } @@ -169,24 +164,22 @@ public class ProxoolConnectionProvider implements ConnectionProvider { PropertyConfigurator.configure( ConfigHelper.getConfigProperties( propFile ) ); } catch ( ProxoolException e ) { - String msg = "Proxool Provider unable to load load Property configurator file: " + propFile; - log.error( msg, e ); + String msg = LOG.unableToLoadPropertyConfiguratorFile(propFile); + LOG.error(msg, e); throw new HibernateException( msg, e ); } // Append the stem to the proxool pool alias proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias; - log.info("Configuring Proxool Provider to use pool alias: " + proxoolAlias); + LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias); } // Remember Isolation level isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props); - if (isolation!=null) { - log.info("JDBC isolation level: " + Environment.isolationLevelToString( isolation.intValue() ) ); - } - + if (isolation != null) LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation.intValue())); + autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props); - log.info("autocommit mode: " + autocommit); + LOG.autoCommmitMode(autocommit); } /** @@ -212,8 +205,9 @@ public class ProxoolConnectionProvider implements ConnectionProvider { catch (Exception e) { // If you're closing down the ConnectionProvider chances are an // is not a real big deal, just warn - log.warn("Exception occured when closing the Proxool pool", e); - throw new HibernateException("Exception occured when closing the Proxool pool", e); + String msg = LOG.exceptionClosingProxoolPool(); + LOG.warn(msg, e); + throw new HibernateException(msg, e); } }