diff --git a/build.gradle b/build.gradle index 6864913c62..efb969cc55 100644 --- a/build.gradle +++ b/build.gradle @@ -61,6 +61,8 @@ libraries = [ jacc: 'org.jboss.javaee:jboss-jacc-api:1.1.0.GA', // logging + logging: 'org.jboss.logging:jboss-logging:3.0.0.Beta4', + logging_tools: 'org.jboss.logging:jboss-logging-tools:1.0.0.Beta1', slf4j_api: 'org.slf4j:slf4j-api:' + slf4jVersion, slf4j_simple: 'org.slf4j:slf4j-simple:' + slf4jVersion, jcl_slf4j: 'org.slf4j:jcl-over-slf4j:' + slf4jVersion, @@ -105,6 +107,8 @@ subprojects { subProject -> // appropriately inject the common dependencies into each sub-project dependencies { + compile(libraries.logging) + compile(libraries.logging_tools) compile( libraries.slf4j_api ) testCompile( libraries.junit ) testRuntime( libraries.slf4j_simple ) @@ -132,6 +136,7 @@ subprojects { subProject -> test { systemProperties['hibernate.test.validatefailureexpected'] = true + // systemProperties['jboss.i18n.generate-proxies'] = true maxHeapSize = "1024m" } diff --git a/hibernate-core/hibernate-core.gradle b/hibernate-core/hibernate-core.gradle index 59f80aa93a..ab006a8b17 100644 --- a/hibernate-core/hibernate-core.gradle +++ b/hibernate-core/hibernate-core.gradle @@ -17,7 +17,9 @@ dependencies { transitive = true } provided( libraries.ant ) - provided( libraries.jacc ) + provided( libraries.jacc ) { + transitive = false + } provided( libraries.validation ) testCompile( libraries.validation ) testCompile( libraries.validator ) { diff --git a/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java b/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java index 590a327a7e..179b893803 100644 --- a/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java +++ b/hibernate-core/src/main/java/org/hibernate/AssertionFailure.java @@ -24,8 +24,10 @@ */ package org.hibernate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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. @@ -34,20 +36,30 @@ import org.slf4j.LoggerFactory; */ public class AssertionFailure extends RuntimeException { - private static final Logger log = LoggerFactory.getLogger( AssertionFailure.class ); + private static final long serialVersionUID = 1L; - private static final String MESSAGE = "an assertion failure occured" + - " (this may indicate a bug in Hibernate, but is more likely due" + - " to unsafe use of the session)"; + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, AssertionFailure.class.getName()); - public AssertionFailure(String s) { - super( s ); - log.error( MESSAGE, this ); - } + public AssertionFailure( String s ) { + super(s); + LOG.failed(this); + } - public AssertionFailure(String s, Throwable t) { - super( s, t ); - log.error( MESSAGE, t ); - } + public AssertionFailure( String s, + Throwable t ) { + 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 7e17079898..661b80aa3c 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 @@ -25,13 +25,11 @@ package org.hibernate.bytecode.cglib; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; 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; @@ -46,70 +44,66 @@ import org.hibernate.util.StringHelper; */ @Deprecated public class BytecodeProviderImpl implements BytecodeProvider { - private static final Logger log = LoggerFactory.getLogger( BytecodeProviderImpl.class ); - public BytecodeProviderImpl() { - log.warn( "Per HHH-5451 support for cglib as a bytecode provider has been deprecated." ); - } + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); - public ProxyFactoryFactory getProxyFactoryFactory() { - return new ProxyFactoryFactoryImpl(); - } + public BytecodeProviderImpl() { + LOG.deprecated(); + } - public ReflectionOptimizer getReflectionOptimizer( - Class clazz, - String[] getterNames, - String[] setterNames, - Class[] types) { - FastClass fastClass; - BulkBean bulkBean; - try { - fastClass = FastClass.create( clazz ); - bulkBean = BulkBean.create( clazz, getterNames, setterNames, types ); - if ( !clazz.isInterface() && !Modifier.isAbstract( clazz.getModifiers() ) ) { - if ( fastClass == null ) { - bulkBean = null; - } - else { - //test out the optimizer: - Object instance = fastClass.newInstance(); - bulkBean.setPropertyValues( instance, bulkBean.getPropertyValues( instance ) ); - } - } - } - catch( Throwable t ) { - fastClass = null; - bulkBean = null; - String message = "reflection optimizer disabled for: " + - clazz.getName() + - " [" + - StringHelper.unqualify( t.getClass().getName() ) + - ": " + - t.getMessage(); + public ProxyFactoryFactory getProxyFactoryFactory() { + return new ProxyFactoryFactoryImpl(); + } - if (t instanceof BulkBeanException ) { - int index = ( (BulkBeanException) t ).getIndex(); - if (index >= 0) { - message += " (property " + setterNames[index] + ")"; - } - } + public ReflectionOptimizer getReflectionOptimizer( + Class clazz, + String[] getterNames, + String[] setterNames, + Class[] types) { + FastClass fastClass; + BulkBean bulkBean; + try { + fastClass = FastClass.create( clazz ); + bulkBean = BulkBean.create( clazz, getterNames, setterNames, types ); + if ( !clazz.isInterface() && !Modifier.isAbstract( clazz.getModifiers() ) ) { + if ( fastClass == null ) { + bulkBean = null; + } + else { + //test out the optimizer: + Object instance = fastClass.newInstance(); + bulkBean.setPropertyValues( instance, bulkBean.getPropertyValues( instance ) ); + } + } + } + catch( Throwable t ) { + fastClass = null; + bulkBean = null; + 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()); + } + } - log.debug( message ); - } - - if ( fastClass != null && bulkBean != null ) { - return new ReflectionOptimizerImpl( - new InstantiationOptimizerAdapter( fastClass ), - new AccessOptimizerAdapter( bulkBean, clazz ) - ); - } - else { - return null; - } - } - - public org.hibernate.bytecode.ClassTransformer getTransformer(org.hibernate.bytecode.util.ClassFilter classFilter, FieldFilter fieldFilter) { - return new CglibClassTransformer( classFilter, fieldFilter ); - } + if ( fastClass != null && bulkBean != null ) { + return new ReflectionOptimizerImpl( + new InstantiationOptimizerAdapter( fastClass ), + new AccessOptimizerAdapter( bulkBean, clazz ) + ); + } + else { + return null; + } + } + public org.hibernate.bytecode.ClassTransformer getTransformer(org.hibernate.bytecode.util.ClassFilter classFilter, FieldFilter fieldFilter) { + return new CglibClassTransformer( classFilter, 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 c33f15cda8..5f82735c10 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 @@ -24,28 +24,26 @@ */ package org.hibernate.bytecode.cglib; -import java.security.ProtectionDomain; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.ByteArrayOutputStream; - +import java.io.IOException; +import java.security.ProtectionDomain; +import net.sf.cglib.core.ClassNameReader; +import net.sf.cglib.core.DebuggingClassWriter; +import net.sf.cglib.transform.ClassReaderGenerator; import net.sf.cglib.transform.ClassTransformer; import net.sf.cglib.transform.TransformingClassGenerator; -import net.sf.cglib.transform.ClassReaderGenerator; import net.sf.cglib.transform.impl.InterceptFieldEnabled; import net.sf.cglib.transform.impl.InterceptFieldFilter; import net.sf.cglib.transform.impl.InterceptFieldTransformer; -import net.sf.cglib.core.ClassNameReader; -import net.sf.cglib.core.DebuggingClassWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.bytecode.AbstractClassTransformerImpl; -import org.hibernate.bytecode.util.FieldFilter; -import org.hibernate.bytecode.util.ClassFilter; import org.hibernate.HibernateException; -import org.objectweb.asm.Type; +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; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Type; /** * Enhance the classes allowing them to implements InterceptFieldEnabled @@ -58,13 +56,14 @@ import org.objectweb.asm.ClassWriter; @Deprecated public class CglibClassTransformer extends AbstractClassTransformerImpl { - private static Logger log = LoggerFactory.getLogger( CglibClassTransformer.class.getName() ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public CglibClassTransformer(ClassFilter classFilter, FieldFilter fieldFilter) { super( classFilter, fieldFilter ); } - protected byte[] doTransform( + @Override + protected byte[] doTransform( ClassLoader loader, String className, Class classBeingRedefined, @@ -75,7 +74,7 @@ public class CglibClassTransformer extends AbstractClassTransformerImpl { reader = new ClassReader( new ByteArrayInputStream( classfileBuffer ) ); } catch (IOException e) { - log.error( "Unable to read class", e ); + LOG.unableToReadClass(e.getMessage()); throw new HibernateException( "Unable to read class: " + e.getMessage() ); } @@ -83,9 +82,7 @@ public class CglibClassTransformer extends AbstractClassTransformerImpl { ClassWriter w = new DebuggingClassWriter( ClassWriter.COMPUTE_MAXS ); ClassTransformer t = getClassTransformer( names ); if ( t != null ) { - if ( log.isDebugEnabled() ) { - log.debug( "Enhancing " + className ); - } + LOG.enhancingClass(className); ByteArrayOutputStream out; byte[] result; try { @@ -99,7 +96,7 @@ public class CglibClassTransformer extends AbstractClassTransformerImpl { out.close(); } catch (Exception e) { - log.error( "Unable to transform class", e ); + LOG.unableToTransformClass(e.getMessage()); throw new HibernateException( "Unable to transform class: " + e.getMessage() ); } return result; 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 0c2a9a17af..47dc683df3 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,11 +25,9 @@ package org.hibernate.bytecode.javassist; import java.lang.reflect.Modifier; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; 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; @@ -43,7 +41,7 @@ import org.hibernate.util.StringHelper; */ public class BytecodeProviderImpl implements BytecodeProvider { - private static final Logger log = LoggerFactory.getLogger( BytecodeProviderImpl.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public ProxyFactoryFactory getProxyFactoryFactory() { return new ProxyFactoryFactoryImpl(); @@ -73,21 +71,17 @@ public class BytecodeProviderImpl implements BytecodeProvider { catch ( Throwable t ) { fastClass = null; bulkAccessor = null; - String message = "reflection optimizer disabled for: " + - clazz.getName() + - " [" + - StringHelper.unqualify( t.getClass().getName() ) + - ": " + - t.getMessage(); - - if ( t instanceof BulkAccessorException ) { - int index = ( ( BulkAccessorException ) t ).getIndex(); - if ( index >= 0 ) { - message += " (property " + setterNames[index] + ")"; - } - } - - log.debug( message ); + 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 ( fastClass != null && bulkAccessor != null ) { @@ -104,5 +98,4 @@ public class BytecodeProviderImpl implements BytecodeProvider { public ClassTransformer getTransformer(ClassFilter classFilter, FieldFilter fieldFilter) { return new JavassistClassTransformer( classFilter, 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 0d1992c25b..d75ec5bbc5 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 @@ -30,12 +30,10 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.ProtectionDomain; - import javassist.bytecode.ClassFile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.bytecode.AbstractClassTransformerImpl; +import org.hibernate.bytecode.Logger; import org.hibernate.bytecode.util.ClassFilter; /** @@ -47,13 +45,14 @@ import org.hibernate.bytecode.util.ClassFilter; */ public class JavassistClassTransformer extends AbstractClassTransformerImpl { - private static Logger log = LoggerFactory.getLogger( JavassistClassTransformer.class.getName() ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public JavassistClassTransformer(ClassFilter classFilter, org.hibernate.bytecode.util.FieldFilter fieldFilter) { super( classFilter, fieldFilter ); } - protected byte[] doTransform( + @Override + protected byte[] doTransform( ClassLoader loader, String className, Class classBeingRedefined, @@ -65,14 +64,12 @@ public class JavassistClassTransformer extends AbstractClassTransformerImpl { classfile = new ClassFile( new DataInputStream( new ByteArrayInputStream( classfileBuffer ) ) ); } catch (IOException e) { - log.error( "Unable to build enhancement metamodel for " + className ); + LOG.unableToBuildEnhancementMetamodel(className); return classfileBuffer; } FieldTransformer transformer = getFieldTransformer( classfile ); if ( transformer != null ) { - if ( log.isDebugEnabled() ) { - log.debug( "Enhancing " + className ); - } + LOG.enhancingClass("Enhancing " + className); DataOutputStream out = null; try { transformer.transform( classfile ); @@ -82,7 +79,7 @@ public class JavassistClassTransformer extends AbstractClassTransformerImpl { return byteStream.toByteArray(); } catch (Exception e) { - log.error( "Unable to transform class", e ); + LOG.unableToTransformClass(e.getMessage()); throw new HibernateException( "Unable to transform class: " + e.getMessage() ); } finally { 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 94e26ab6c1..3c7757678f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/AbstractJndiBoundCacheProvider.java @@ -25,13 +25,9 @@ package org.hibernate.cache; import java.util.Properties; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.jndi.JndiHelper; import org.hibernate.util.StringHelper; @@ -44,7 +40,8 @@ import org.hibernate.util.StringHelper; */ public abstract class AbstractJndiBoundCacheProvider implements CacheProvider { - private static final Logger log = LoggerFactory.getLogger( AbstractJndiBoundCacheProvider.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); + private Object cache; protected void prepare(Properties properties) { @@ -88,7 +85,7 @@ public abstract class AbstractJndiBoundCacheProvider implements CacheProvider { } catch (NamingException ne) { String msg = "Unable to retreive Cache from JNDI [" + jndiNamespace + "]"; - log.info( msg, ne ); + LOG.unableToRetrieveCache(jndiNamespace, ne.getMessage()); throw new CacheException( msg ); } finally { @@ -97,12 +94,12 @@ public abstract class AbstractJndiBoundCacheProvider implements CacheProvider { ctx.close(); } catch( NamingException ne ) { - log.info( "Unable to release initial context", ne ); + LOG.unableToReleaseContext(ne.getMessage()); } } } } - + public Object getCache() { return cache; } 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 7d51941f81..ea0c72e7c1 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/NonstrictReadWriteCache.java @@ -25,10 +25,6 @@ package org.hibernate.cache; import java.util.Comparator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cache.access.SoftLock; /** @@ -43,9 +39,9 @@ import org.hibernate.cache.access.SoftLock; */ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { - private Cache cache; + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); - private static final Logger log = LoggerFactory.getLogger( NonstrictReadWriteCache.class ); + private Cache cache; public NonstrictReadWriteCache() { } @@ -62,16 +58,14 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Get the most recent version, if available. */ public Object get(Object key, long txTimestamp) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "Cache lookup: " + key ); - } + LOG.lookup(key); Object result = cache.get( key ); if ( result != null ) { - log.debug( "Cache hit" ); + LOG.hit(key); } else { - log.debug( "Cache miss" ); + LOG.miss(key); } return result; } @@ -87,14 +81,10 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { Comparator versionComparator, boolean minimalPut) throws CacheException { if ( minimalPut && cache.get( key ) != null ) { - if ( log.isDebugEnabled() ) { - log.debug( "item already cached: " + key ); - } + LOG.exists(key); return false; } - if ( log.isDebugEnabled() ) { - log.debug( "Caching: " + key ); - } + LOG.caching(key); cache.put( key, value ); return true; @@ -111,16 +101,12 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { } public void remove(Object key) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "Removing: " + key ); - } + LOG.removing(key); cache.remove( key ); } public void clear() throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "Clearing" ); - } + LOG.clearing(); cache.clear(); } @@ -129,7 +115,7 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { cache.destroy(); } catch ( Exception e ) { - log.warn( "could not destroy cache", e ); + LOG.unableToDestroyCache(e.getMessage()); } } @@ -137,10 +123,7 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Invalidate the item */ public void evict(Object key) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "Invalidating: " + key ); - } - + LOG.invalidating(key); cache.remove( key ); } @@ -163,10 +146,7 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { * Invalidate the item (again, for safety). */ public void release(Object key, SoftLock lock) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "Invalidating (again): " + key ); - } - + LOG.invalidating(key); cache.remove( key ); } @@ -189,7 +169,8 @@ public class NonstrictReadWriteCache implements CacheConcurrencyStrategy { return cache.getRegionName(); } - public String toString() { + @Override + public String toString() { return cache + "(nonstrict-read-write)"; } } 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 2b13749a97..aa38d76727 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/ReadOnlyCache.java @@ -25,10 +25,6 @@ package org.hibernate.cache; import java.util.Comparator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cache.access.SoftLock; /** @@ -36,12 +32,13 @@ import org.hibernate.cache.access.SoftLock; * @see CacheConcurrencyStrategy */ public class ReadOnlyCache implements CacheConcurrencyStrategy { - + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); + private Cache cache; - private static final Logger log = LoggerFactory.getLogger(ReadOnlyCache.class); - + public ReadOnlyCache() {} - + public void setCache(Cache cache) { this.cache=cache; } @@ -53,46 +50,46 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { public String getRegionName() { return cache.getRegionName(); } - + public synchronized Object get(Object key, long timestamp) throws CacheException { Object result = cache.get(key); - if ( result!=null && log.isDebugEnabled() ) log.debug("Cache hit: " + key); + if (result != null) LOG.hit(key); return result; } - + /** * Unsupported! */ public SoftLock lock(Object key, Object version) { - log.error("Application attempted to edit read only item: " + key); + LOG.invalidEditOfReadOnlyItem(key); throw new UnsupportedOperationException("Can't write to a readonly object"); } - + public synchronized boolean put( - Object key, - Object value, - long timestamp, - Object version, + Object key, + Object value, + long timestamp, + Object version, Comparator versionComparator, - boolean minimalPut) + boolean minimalPut) throws CacheException { if ( minimalPut && cache.get(key)!=null ) { - if ( log.isDebugEnabled() ) log.debug("item already cached: " + key); + LOG.exists(key); return false; } - if ( log.isDebugEnabled() ) log.debug("Caching: " + key); + LOG.caching(key); cache.put(key, value); return true; } - + /** * Unsupported! */ public void release(Object key, SoftLock lock) { - log.error("Application attempted to edit read only item: " + key); + LOG.invalidEditOfReadOnlyItem(key); //throw new UnsupportedOperationException("Can't write to a readonly object"); } - + public void clear() throws CacheException { cache.clear(); } @@ -100,13 +97,13 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { public void remove(Object key) throws CacheException { cache.remove(key); } - + public void destroy() { try { cache.destroy(); } catch (Exception e) { - log.warn("could not destroy cache", e); + LOG.unableToDestroyCache(e.getMessage()); } } @@ -114,15 +111,15 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { * Unsupported! */ public boolean afterUpdate(Object key, Object value, Object version, SoftLock lock) throws CacheException { - log.error("Application attempted to edit read only item: " + key); + LOG.invalidEditOfReadOnlyItem(key); throw new UnsupportedOperationException("Can't write to a readonly object"); } /** * Do nothing. */ - public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - if ( log.isDebugEnabled() ) log.debug("Caching after insert: " + key); + public boolean afterInsert(Object key, Object value, Object version) throws CacheException { + LOG.cachingAfterInsert(key); cache.update(key, value); return true; } @@ -145,11 +142,12 @@ public class ReadOnlyCache implements CacheConcurrencyStrategy { * Unsupported! */ public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) { - log.error("Application attempted to edit read only item: " + key); + LOG.invalidEditOfReadOnlyItem(key); throw new UnsupportedOperationException("Can't write to a readonly object"); } - public String toString() { + @Override + public String toString() { return cache + "(read-only)"; } 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 8556d76b89..6d1ae16149 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/ReadWriteCache.java @@ -26,10 +26,6 @@ package org.hibernate.cache; import java.io.Serializable; import java.util.Comparator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cache.access.SoftLock; /** @@ -50,7 +46,7 @@ import org.hibernate.cache.access.SoftLock; */ public class ReadWriteCache implements CacheConcurrencyStrategy { - private static final Logger log = LoggerFactory.getLogger(ReadWriteCache.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private Cache cache; private int nextLockId; @@ -68,7 +64,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { public String getRegionName() { return cache.getRegionName(); } - + /** * Generate an id for a new lock. Uniqueness per cache instance is very * desirable but not absolutely critical. Must be called from one of the @@ -96,35 +92,16 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * the data is versioned or timestamped. */ public synchronized Object get(Object key, long txTimestamp) throws CacheException { - - if ( log.isTraceEnabled() ) log.trace("Cache lookup: " + key); - - /*try { - cache.lock(key);*/ - - Lockable lockable = (Lockable) cache.get(key); - - boolean gettable = lockable!=null && lockable.isGettable(txTimestamp); - - if (gettable) { - if ( log.isTraceEnabled() ) log.trace("Cache hit: " + key); - return ( (Item) lockable ).getValue(); - } - else { - if ( log.isTraceEnabled() ) { - if (lockable==null) { - log.trace("Cache miss: " + key); - } - else { - log.trace("Cached item was locked: " + key); - } - } - return null; - } - /*} - finally { - cache.unlock(key); - }*/ + LOG.lookup(key); + Lockable lockable = (Lockable)cache.get(key); + boolean gettable = lockable != null && lockable.isGettable(txTimestamp); + if (gettable) { + LOG.hit(key); + return ((Item)lockable).getValue(); + } + if (lockable == null) LOG.miss(key); + else LOG.locked(key); + return null; } /** @@ -135,8 +112,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * item. */ public synchronized SoftLock lock(Object key, Object version) throws CacheException { - if ( log.isTraceEnabled() ) log.trace("Invalidating: " + key); - + LOG.invalidating(key); try { cache.lock(key); @@ -163,37 +139,31 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * version. */ public synchronized boolean put( - Object key, - Object value, - long txTimestamp, - Object version, + Object key, + Object value, + long txTimestamp, + Object version, Comparator versionComparator, - boolean minimalPut) + boolean minimalPut) throws CacheException { - if ( log.isTraceEnabled() ) log.trace("Caching: " + key); + LOG.caching(key); try { cache.lock(key); Lockable lockable = (Lockable) cache.get(key); - boolean puttable = lockable==null || + boolean puttable = lockable==null || lockable.isPuttable(txTimestamp, version, versionComparator); if (puttable) { cache.put( key, new Item( value, version, cache.nextTimestamp() ) ); - if ( log.isTraceEnabled() ) log.trace("Cached: " + key); + LOG.cached(key); return true; } else { - if ( log.isTraceEnabled() ) { - if ( lockable.isLock() ) { - log.trace("Item was locked: " + key); - } - else { - log.trace("Item was already cached: " + key); - } - } + if (lockable.isLock()) LOG.locked(key); + else LOG.exists(key); return false; } } @@ -217,7 +187,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * simultaneous lock). */ public synchronized void release(Object key, SoftLock clientLock) throws CacheException { - if ( log.isTraceEnabled() ) log.trace("Releasing: " + key); + LOG.releasing(key); try { cache.lock(key); @@ -236,7 +206,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { } void handleLockExpiry(Object key) throws CacheException { - log.warn("An item was expired by the cache while it was locked (increase your cache timeout): " + key); + LOG.expired(key); long ts = cache.nextTimestamp() + cache.getTimeout(); // create new lock that times out immediately Lock lock = new Lock( ts, nextLockId(), null ); @@ -257,7 +227,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { cache.destroy(); } catch (Exception e) { - log.warn("could not destroy cache", e); + LOG.unableToDestroyCache(e.getMessage()); } } @@ -265,10 +235,10 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * Re-cache the updated state, if and only if there there are * no other concurrent soft locks. Release our lock. */ - public synchronized boolean afterUpdate(Object key, Object value, Object version, SoftLock clientLock) + public synchronized boolean afterUpdate(Object key, Object value, Object version, SoftLock clientLock) throws CacheException { - - if ( log.isTraceEnabled() ) log.trace("Updating: " + key); + + LOG.updating(key); try { cache.lock(key); @@ -285,7 +255,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { else { //recache the updated state cache.update( key, new Item( value, version, cache.nextTimestamp() ) ); - if ( log.isTraceEnabled() ) log.trace("Updated: " + key); + LOG.updated(key); return true; } } @@ -304,17 +274,17 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { * Add the new item to the cache, checking that no other transaction has * accessed the item. */ - public synchronized boolean afterInsert(Object key, Object value, Object version) + public synchronized boolean afterInsert(Object key, Object value, Object version) throws CacheException { - - if ( log.isTraceEnabled() ) log.trace("Inserting: " + key); + + LOG.inserting(key); try { cache.lock(key); Lockable lockable = (Lockable) cache.get(key); if (lockable==null) { cache.update( key, new Item( value, version, cache.nextTimestamp() ) ); - if ( log.isTraceEnabled() ) log.trace("Inserted: " + key); + LOG.inserted(key); return true; } else { @@ -426,7 +396,8 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { return version!=null && comparator.compare(version, newVersion) < 0; } - public String toString() { + @Override + public String toString() { return "Item{version=" + version + ",freshTimestamp=" + freshTimestamp; } @@ -482,7 +453,7 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { public boolean isPuttable(long txTimestamp, Object newVersion, Comparator comparator) { if (timeout < txTimestamp) return true; if (multiplicity>0) return false; - return version==null ? + return version==null ? unlockTimestamp < txTimestamp : comparator.compare(version, newVersion) < 0; //by requiring <, we rely on lock timeout in the case of an unsuccessful update! } @@ -509,7 +480,8 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { public int getId() { return id; } - public String toString() { + @Override + public String toString() { return "Lock{id=" + id + ",version=" + version + ",multiplicity=" + multiplicity + @@ -518,7 +490,8 @@ public class ReadWriteCache implements CacheConcurrencyStrategy { } - public String toString() { + @Override + public String toString() { return cache + "(read-write)"; } 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 429718b353..e8ea924b95 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/StandardQueryCache.java @@ -28,12 +28,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Set; - import javax.persistence.EntityNotFoundException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.UnresolvableObjectException; import org.hibernate.cfg.Settings; @@ -52,7 +47,7 @@ import org.hibernate.type.TypeHelper; */ public class StandardQueryCache implements QueryCache { - private static final Logger log = LoggerFactory.getLogger( StandardQueryCache.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private QueryResultsRegion cacheRegion; private UpdateTimestampsCache updateTimestampsCache; @@ -73,7 +68,7 @@ public class StandardQueryCache implements QueryCache { if ( prefix != null ) { regionName = prefix + '.' + regionName; } - log.info( "starting query cache at region: " + regionName ); + LOG.startingQueryCache(regionName); this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionName, props ); this.updateTimestampsCache = updateTimestampsCache; @@ -92,14 +87,10 @@ public class StandardQueryCache implements QueryCache { else { Long ts = new Long( session.getFactory().getSettings().getRegionFactory().nextTimestamp()); - if ( log.isDebugEnabled() ) { - log.debug( "caching query results in region: " + cacheRegion.getName() + "; timestamp=" + ts ); - } + LOG.cachingQueryResults(cacheRegion.getName(), ts); List cacheable = new ArrayList( result.size() + 1 ); - if ( log.isTraceEnabled() ) { - logCachedResultDetails( key, null, returnTypes, cacheable ); - } + logCachedResultDetails(key, null, returnTypes, cacheable); cacheable.add( ts ); for ( Object aResult : result ) { if ( returnTypes.length == 1 ) { @@ -110,9 +101,7 @@ public class StandardQueryCache implements QueryCache { TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ) ); } - if ( log.isTraceEnabled() ) { - logCachedResultRowDetails( returnTypes, aResult ); - } + logCachedResultRowDetails(returnTypes, aResult); } cacheRegion.put( key, cacheable ); @@ -127,27 +116,23 @@ public class StandardQueryCache implements QueryCache { boolean isNaturalKeyLookup, Set spaces, SessionImplementor session) throws HibernateException { - if ( log.isDebugEnabled() ) { - log.debug( "checking cached query results in region: " + cacheRegion.getName() ); - } + LOG.checkingQueryResults(cacheRegion.getName()); List cacheable = ( List ) cacheRegion.get( key ); - if ( log.isTraceEnabled() ) { - logCachedResultDetails( key, spaces, returnTypes, cacheable ); - } + logCachedResultDetails(key, spaces, returnTypes, cacheable); if ( cacheable == null ) { - log.debug( "query results were not found in cache" ); + LOG.queryResultsNotFound(); return null; } Long timestamp = ( Long ) cacheable.get( 0 ); if ( !isNaturalKeyLookup && !isUpToDate( spaces, timestamp ) ) { - log.debug( "cached query results were not up to date" ); + LOG.queryResultsNotUpToDate(); return null; } - log.debug( "returning cached query results" ); + LOG.returningQueryResults(); for ( int i = 1; i < cacheable.size(); i++ ) { if ( returnTypes.length == 1 ) { returnTypes[0].beforeAssemble( ( Serializable ) cacheable.get( i ), session ); @@ -167,9 +152,7 @@ public class StandardQueryCache implements QueryCache { TypeHelper.assemble( ( Serializable[] ) cacheable.get( i ), returnTypes, session, null ) ); } - if ( log.isTraceEnabled() ) { - logCachedResultRowDetails( returnTypes, result.get( i - 1 )); - } + logCachedResultRowDetails(returnTypes, result.get(i - 1)); } catch ( RuntimeException ex ) { if ( isNaturalKeyLookup && @@ -179,7 +162,7 @@ public class StandardQueryCache implements QueryCache { // the uoe could occur while resolving // associations, leaving the PC in an // inconsistent state - log.debug( "could not reassemble cached result set" ); + LOG.unableToReassembleResultSet(); cacheRegion.evict( key ); return null; } @@ -192,9 +175,7 @@ public class StandardQueryCache implements QueryCache { } protected boolean isUpToDate(Set spaces, Long timestamp) { - if ( log.isDebugEnabled() ) { - log.debug( "Checking query spaces for up-to-dateness: " + spaces ); - } + LOG.checkingQuerySpacesUpToDate(spaces); return updateTimestampsCache.isUpToDate( spaces, timestamp ); } @@ -203,7 +184,7 @@ public class StandardQueryCache implements QueryCache { cacheRegion.destroy(); } catch ( Exception e ) { - log.warn( "could not destroy query cache: " + cacheRegion.getName(), e ); + LOG.unableToDestroyQueryCache(cacheRegion.getName(), e.getMessage()); } } @@ -211,19 +192,18 @@ public class StandardQueryCache implements QueryCache { return cacheRegion; } - public String toString() { + @Override + public String toString() { return "StandardQueryCache(" + cacheRegion.getName() + ')'; } private static void logCachedResultDetails(QueryKey key, Set querySpaces, Type[] returnTypes, List result) { - if ( ! log.isTraceEnabled() ) { - return; - } - log.trace( "key.hashCode="+key.hashCode() ); - log.trace( "querySpaces="+querySpaces ); + if (!LOG.isTraceEnabled()) return; + LOG.key(key.hashCode()); + LOG.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() ) ); + LOG.unexpectedReturnTypes(returnTypes == null ? "null" : "empty", + result == null ? " is null" : ".size()=" + result.size()); } else { StringBuffer returnTypeInfo = new StringBuffer(); @@ -233,14 +213,12 @@ public class StandardQueryCache implements QueryCache { .append(" class=" ) .append( returnTypes[ i ].getReturnedClass().getName() ).append(' '); } - log.trace( " returnTypeInfo="+returnTypeInfo ); + LOG.returnTypeInfo(returnTypeInfo.toString()); } } private static void logCachedResultRowDetails(Type[] returnTypes, Object result) { - if ( ! log.isTraceEnabled() ) { - return; - } + if (!LOG.isTraceEnabled()) return; logCachedResultRowDetails( returnTypes, ( result instanceof Object[] ? ( Object[] ) result : new Object[] { result } ) @@ -248,37 +226,19 @@ public class StandardQueryCache implements QueryCache { } private static void logCachedResultRowDetails(Type[] returnTypes, Object[] tuple) { - if ( ! log.isTraceEnabled() ) { - return; - } + if (!LOG.isTraceEnabled()) return; if ( tuple == null ) { - 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+"]!" ); - } + LOG.nullTuple(returnTypes == null ? "null" : "Type[" + returnTypes.length + "]"); + if (returnTypes != null && returnTypes.length > 1) LOG.unexpectedNullTupleResult(returnTypes.length); } else { - if ( returnTypes == null || returnTypes.length == 0 ) { - log.trace( "unexpected result tuple! "+ - "tuple is non-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.trace( "unexpected tuple value type! transformer="+ - " expected="+returnTypes[ j ].getReturnedClass().getName()+ - " got="+tuple[ j ].getClass().getName() ); - } - } - } + 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); + 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()); + } } } } 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 923ff37a9a..e0b6b01a5e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/TransactionalCache.java @@ -25,10 +25,6 @@ package org.hibernate.cache; import java.util.Comparator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cache.access.SoftLock; /** @@ -41,7 +37,7 @@ import org.hibernate.cache.access.SoftLock; */ public class TransactionalCache implements CacheConcurrencyStrategy { - private static final Logger log = LoggerFactory.getLogger( TransactionalCache.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private Cache cache; @@ -50,13 +46,10 @@ public class TransactionalCache implements CacheConcurrencyStrategy { } public Object get(Object key, long txTimestamp) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "cache lookup: " + key ); - } + LOG.lookup(key); Object result = cache.read( key ); - if ( log.isDebugEnabled() ) { - log.debug( result == null ? "cache miss" : "cache hit" ); - } + if (result == null) LOG.miss(key); + else LOG.hit(key); return result; } @@ -68,14 +61,10 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Comparator versionComparator, boolean minimalPut) throws CacheException { if ( minimalPut && cache.read( key ) != null ) { - if ( log.isDebugEnabled() ) { - log.debug( "item already cached: " + key ); - } + LOG.exists(key); return false; } - if ( log.isDebugEnabled() ) { - log.debug( "caching: " + key ); - } + LOG.caching(key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeLoad( key, value, version ); } @@ -105,9 +94,7 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Object value, Object currentVersion, Object previousVersion) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "updating: " + key ); - } + LOG.updating(key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeUpdate( key, value, currentVersion, previousVersion ); } @@ -121,9 +108,7 @@ public class TransactionalCache implements CacheConcurrencyStrategy { Object key, Object value, Object currentVersion) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "inserting: " + key ); - } + LOG.inserting(key); if ( cache instanceof OptimisticCache ) { ( ( OptimisticCache ) cache ).writeInsert( key, value, currentVersion ); } @@ -138,14 +123,12 @@ public class TransactionalCache implements CacheConcurrencyStrategy { } public void remove(Object key) throws CacheException { - if ( log.isDebugEnabled() ) { - log.debug( "removing: " + key ); - } + LOG.removing(key); cache.remove( key ); } public void clear() throws CacheException { - log.debug( "clearing" ); + LOG.clearing(); cache.clear(); } @@ -154,7 +137,7 @@ public class TransactionalCache implements CacheConcurrencyStrategy { cache.destroy(); } catch ( Exception e ) { - log.warn( "could not destroy cache", e ); + LOG.unableToDestroyCache(e.getMessage()); } } @@ -187,7 +170,8 @@ public class TransactionalCache implements CacheConcurrencyStrategy { return false; } - public String toString() { + @Override + public String toString() { return cache + "(transactional)"; } 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 fa1169517e..34c5790463 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/UpdateTimestampsCache.java @@ -28,10 +28,6 @@ import java.io.Serializable; import java.util.Iterator; import java.util.Properties; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.cfg.Settings; @@ -47,14 +43,14 @@ import org.hibernate.cfg.Settings; */ public class UpdateTimestampsCache { public static final String REGION_NAME = UpdateTimestampsCache.class.getName(); - private static final Logger log = LoggerFactory.getLogger( UpdateTimestampsCache.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private final TimestampsRegion region; public UpdateTimestampsCache(Settings settings, Properties props) throws HibernateException { String prefix = settings.getCacheRegionPrefix(); String regionName = prefix == null ? REGION_NAME : prefix + '.' + REGION_NAME; - log.info( "starting update timestamps cache at region: " + regionName ); + LOG.startingUpdateTimestampsCache(regionName); this.region = settings.getRegionFactory().buildTimestampsRegion( regionName, props ); } @@ -62,9 +58,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; } @@ -118,15 +108,16 @@ public class UpdateTimestampsCache { region.destroy(); } catch (Exception e) { - log.warn("could not destroy UpdateTimestamps cache", e); + LOG.unableToDestroyUpdateTimestampsCache(region.getName(), e.getMessage()); } } public TimestampsRegion getRegion() { return region; } - - public String toString() { + + @Override + public String toString() { return "UpdateTimestampeCache"; } 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 d1a155aabb..8ce4ad7e9d 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,21 +24,18 @@ */ package org.hibernate.cache.impl.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.Cache; -import org.hibernate.cache.CacheDataDescription; -import org.hibernate.cache.OptimisticCache; -import org.hibernate.cache.CacheException; import org.hibernate.cache.CacheConcurrencyStrategy; -import org.hibernate.cache.TransactionalCache; -import org.hibernate.cache.ReadWriteCache; +import org.hibernate.cache.CacheDataDescription; +import org.hibernate.cache.CacheException; +import org.hibernate.cache.CollectionRegion; import org.hibernate.cache.NonstrictReadWriteCache; +import org.hibernate.cache.OptimisticCache; import org.hibernate.cache.ReadOnlyCache; -import org.hibernate.cache.access.CollectionRegionAccessStrategy; +import org.hibernate.cache.ReadWriteCache; +import org.hibernate.cache.TransactionalCache; import org.hibernate.cache.access.AccessType; +import org.hibernate.cache.access.CollectionRegionAccessStrategy; import org.hibernate.cfg.Settings; /** @@ -47,7 +44,8 @@ import org.hibernate.cfg.Settings; * @author Steve Ebersole */ public class CollectionRegionAdapter extends BaseTransactionalDataRegionAdapter implements CollectionRegion { - private static final Logger log = LoggerFactory.getLogger( CollectionRegionAdapter.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public CollectionRegionAdapter(Cache underlyingCache, Settings settings, CacheDataDescription metadata) { super( underlyingCache, settings, metadata ); @@ -59,9 +57,7 @@ public class CollectionRegionAdapter extends BaseTransactionalDataRegionAdapter public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { CacheConcurrencyStrategy ccs; if ( AccessType.READ_ONLY.equals( accessType ) ) { - if ( metadata.isMutable() ) { - log.warn( "read-only cache configured for mutable collection [" + getName() + "]" ); - } + if (metadata.isMutable()) LOG.readOnlyCacheConfiguredForMutableCollection(getName()); ccs = new ReadOnlyCache(); } else if ( AccessType.READ_WRITE.equals( accessType ) ) { 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 b7a6f1f5d0..4396f15522 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,21 +24,18 @@ */ package org.hibernate.cache.impl.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.cache.EntityRegion; import org.hibernate.cache.Cache; -import org.hibernate.cache.CacheDataDescription; -import org.hibernate.cache.OptimisticCache; -import org.hibernate.cache.CacheException; import org.hibernate.cache.CacheConcurrencyStrategy; +import org.hibernate.cache.CacheDataDescription; +import org.hibernate.cache.CacheException; +import org.hibernate.cache.EntityRegion; +import org.hibernate.cache.NonstrictReadWriteCache; +import org.hibernate.cache.OptimisticCache; import org.hibernate.cache.ReadOnlyCache; import org.hibernate.cache.ReadWriteCache; -import org.hibernate.cache.NonstrictReadWriteCache; import org.hibernate.cache.TransactionalCache; -import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cache.access.AccessType; +import org.hibernate.cache.access.EntityRegionAccessStrategy; import org.hibernate.cfg.Settings; /** @@ -47,7 +44,8 @@ import org.hibernate.cfg.Settings; * @author Steve Ebersole */ public class EntityRegionAdapter extends BaseTransactionalDataRegionAdapter implements EntityRegion { - private static final Logger log = LoggerFactory.getLogger( EntityRegionAdapter.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); public EntityRegionAdapter(Cache underlyingCache, Settings settings, CacheDataDescription metadata) { super( underlyingCache, settings, metadata ); @@ -59,9 +57,7 @@ public class EntityRegionAdapter extends BaseTransactionalDataRegionAdapter impl public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { CacheConcurrencyStrategy ccs; if ( AccessType.READ_ONLY.equals( accessType ) ) { - if ( metadata.isMutable() ) { - log.warn( "read-only cache configured for mutable entity [" + getName() + "]" ); - } + if (metadata.isMutable()) LOG.readOnlyCacheConfiguredForMutableCollection(getName()); ccs = new ReadOnlyCache(); } else if ( AccessType.READ_WRITE.equals( accessType ) ) { @@ -79,5 +75,4 @@ public class EntityRegionAdapter extends BaseTransactionalDataRegionAdapter impl ccs.setCache( underlyingCache ); return new EntityAccessStrategyAdapter( this, ccs, settings ); } - } 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 d87a65f2c8..f0d4b48d51 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,24 +24,20 @@ package org.hibernate.cache.impl.bridge; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.cache.RegionFactory; -import org.hibernate.cache.CacheProvider; -import org.hibernate.cache.CacheException; -import org.hibernate.cache.EntityRegion; -import org.hibernate.cache.CollectionRegion; -import org.hibernate.cache.QueryResultsRegion; -import org.hibernate.cache.NoCacheProvider; -import org.hibernate.cache.TimestampsRegion; import org.hibernate.cache.CacheDataDescription; +import org.hibernate.cache.CacheException; +import org.hibernate.cache.CacheProvider; +import org.hibernate.cache.CollectionRegion; +import org.hibernate.cache.EntityRegion; +import org.hibernate.cache.NoCacheProvider; +import org.hibernate.cache.QueryResultsRegion; +import org.hibernate.cache.RegionFactory; +import org.hibernate.cache.TimestampsRegion; import org.hibernate.cache.access.AccessType; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.util.ReflectHelper; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; +import org.hibernate.internal.util.config.ConfigurationHelper; +import org.hibernate.util.ReflectHelper; /** * Acts as a bridge between the {@link RegionFactory} contract and the older @@ -51,14 +47,15 @@ import org.hibernate.cfg.Settings; */ public class RegionFactoryCacheProviderBridge implements RegionFactory { public static final String DEF_PROVIDER = NoCacheProvider.class.getName(); - private static final Logger log = LoggerFactory.getLogger( RegionFactoryCacheProviderBridge.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Logger.class.getPackage().getName()); private CacheProvider cacheProvider; private Settings settings; public RegionFactoryCacheProviderBridge(Properties properties) { String providerClassName = ConfigurationHelper.getString( Environment.CACHE_PROVIDER, properties, DEF_PROVIDER ); - log.info( "Cache provider: " + providerClassName ); + LOG.cacheProvider(providerClassName); try { cacheProvider = ( CacheProvider ) ReflectHelper.classForName( providerClassName ).newInstance(); } 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 517cac3393..b0459a8eaa 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -23,6 +23,10 @@ */ 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; @@ -79,10 +83,6 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.UniqueConstraint; import javax.persistence.Version; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; @@ -173,6 +173,10 @@ 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 @@ -185,25 +189,26 @@ import org.hibernate.persister.entity.UnionSubclassEntityPersister; @SuppressWarnings("unchecked") public final class AnnotationBinder { - /* - * Some design description - * I tried to remove any link to annotation except from the 2 first level of - * method call. - * It'll enable to: - * - facilitate annotation overriding - * - mutualize one day xml and annotation binder (probably a dream though) - * - split this huge class in smaller mapping oriented classes - * - * bindSomething usually create the mapping container and is accessed by one of the 2 first level method - * makeSomething usually create the mapping container and is accessed by bindSomething[else] - * fillSomething take the container into parameter and fill it. - */ + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AnnotationBinder.class.getPackage().getName()); + + /* + * Some design description + * I tried to remove any link to annotation except from the 2 first level of + * method call. + * It'll enable to: + * - facilitate annotation overriding + * - mutualize one day xml and annotation binder (probably a dream though) + * - split this huge class in smaller mapping oriented classes + * + * bindSomething usually create the mapping container and is accessed by one of the 2 first level method + * makeSomething usually create the mapping container and is accessed by bindSomething[else] + * fillSomething take the container into parameter and fill it. + */ private AnnotationBinder() { } - private static final Logger log = LoggerFactory.getLogger( AnnotationBinder.class ); - public static void bindDefaults(Mappings mappings) { Map defaults = mappings.getReflectionManager().getDefaults(); { @@ -260,14 +265,14 @@ public final class AnnotationBinder { pckg = mappings.getReflectionManager().packageForName( packageName ); } catch ( ClassNotFoundException cnf ) { - log.warn( "Package not found or wo package-info.java: {}", packageName ); + LOG.packageNotFound(packageName); return; } if ( pckg.isAnnotationPresent( SequenceGenerator.class ) ) { SequenceGenerator ann = pckg.getAnnotation( SequenceGenerator.class ); IdGenerator idGen = buildIdGenerator( ann, mappings ); mappings.addGenerator( idGen ); - log.trace( "Add sequence generator with name: {}", idGen.getName() ); + LOG.addSequenceGenerator(idGen.getName()); } if ( pckg.isAnnotationPresent( TableGenerator.class ) ) { TableGenerator ann = pckg.getAnnotation( TableGenerator.class ); @@ -376,10 +381,10 @@ public final class AnnotationBinder { idGen.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" ); if ( !BinderHelper.isEmptyAnnotationValue( tabGen.catalog() ) ) { - idGen.addParam( org.hibernate.id.enhanced.TableGenerator.CATALOG, tabGen.catalog() ); + idGen.addParam( PersistentIdentifierGenerator.CATALOG, tabGen.catalog() ); } if ( !BinderHelper.isEmptyAnnotationValue( tabGen.schema() ) ) { - idGen.addParam( org.hibernate.id.enhanced.TableGenerator.SCHEMA, tabGen.schema() ); + idGen.addParam( PersistentIdentifierGenerator.SCHEMA, tabGen.schema() ); } if ( !BinderHelper.isEmptyAnnotationValue( tabGen.table() ) ) { idGen.addParam( org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM, tabGen.table() ); @@ -408,9 +413,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.warn( "Ignoring unique constraints specified on table generator [{}]", tabGen.name() ); - } + if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.tableGenerator(tabGen.name()); } else { idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() ); @@ -419,15 +422,13 @@ public final class AnnotationBinder { idGen.addParam( MultipleHiLoPerTableGenerator.ID_TABLE, tabGen.table() ); } if ( !BinderHelper.isEmptyAnnotationValue( tabGen.catalog() ) ) { - idGen.addParam( MultipleHiLoPerTableGenerator.CATALOG, tabGen.catalog() ); + idGen.addParam( PersistentIdentifierGenerator.CATALOG, tabGen.catalog() ); } if ( !BinderHelper.isEmptyAnnotationValue( tabGen.schema() ) ) { - idGen.addParam( MultipleHiLoPerTableGenerator.SCHEMA, tabGen.schema() ); + idGen.addParam( PersistentIdentifierGenerator.SCHEMA, tabGen.schema() ); } //FIXME implement uniqueconstrains - if ( tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0 ) { - log.warn( "Ignoring unique constraints specified on table generator [{}]", tabGen.name() ); - } + if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.ignoringTableGeneratorConstraints(tabGen.name()); if ( !BinderHelper.isEmptyAnnotationValue( tabGen.pkColumnName() ) ) { idGen.addParam( MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, tabGen.pkColumnName() ); @@ -440,7 +441,7 @@ public final class AnnotationBinder { } idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) ); } - log.trace( "Add table generator with name: {}", idGen.getName() ); + LOG.addTableGenerator(idGen.getName()); } else if ( ann instanceof SequenceGenerator ) { SequenceGenerator seqGen = ( SequenceGenerator ) ann; @@ -449,10 +450,10 @@ public final class AnnotationBinder { idGen.setIdentifierGeneratorStrategy( SequenceStyleGenerator.class.getName() ); if ( !BinderHelper.isEmptyAnnotationValue( seqGen.catalog() ) ) { - idGen.addParam( SequenceStyleGenerator.CATALOG, seqGen.catalog() ); + idGen.addParam( PersistentIdentifierGenerator.CATALOG, seqGen.catalog() ); } if ( !BinderHelper.isEmptyAnnotationValue( seqGen.schema() ) ) { - idGen.addParam( SequenceStyleGenerator.SCHEMA, seqGen.schema() ); + idGen.addParam( PersistentIdentifierGenerator.SCHEMA, seqGen.schema() ); } if ( !BinderHelper.isEmptyAnnotationValue( seqGen.sequenceName() ) ) { idGen.addParam( SequenceStyleGenerator.SEQUENCE_PARAM, seqGen.sequenceName() ); @@ -468,14 +469,9 @@ public final class AnnotationBinder { } //FIXME: work on initialValue() through SequenceGenerator.PARAMETERS // steve : or just use o.h.id.enhanced.SequenceStyleGenerator - if ( seqGen.initialValue() != 1 ) { - log.warn( - "Hibernate does not support SequenceGenerator.initialValue() unless '{}' set", - Configuration.USE_NEW_ID_GENERATOR_MAPPINGS - ); - } + if (seqGen.initialValue() != 1) LOG.unsupportedInitialValue(Configuration.USE_NEW_ID_GENERATOR_MAPPINGS); idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) ); - log.trace( "Add sequence generator with name: {}", idGen.getName() ); + LOG.addSequenceGenerator(idGen.getName()); } } else if ( ann instanceof GenericGenerator ) { @@ -486,7 +482,7 @@ public final class AnnotationBinder { for ( Parameter parameter : params ) { idGen.addParam( parameter.name(), parameter.value() ); } - log.trace( "Add generic generator with name: {}", idGen.getName() ); + LOG.addGenericGenerator(idGen.getName()); } else { throw new AssertionFailure( "Unknown Generator annotation: " + ann ); @@ -508,7 +504,7 @@ public final class AnnotationBinder { Map inheritanceStatePerClass, Mappings mappings) throws MappingException { //@Entity and @MappedSuperclass on the same class leads to a NPE down the road - if ( clazzToProcess.isAnnotationPresent( Entity.class ) + if ( clazzToProcess.isAnnotationPresent( Entity.class ) && clazzToProcess.isAnnotationPresent( MappedSuperclass.class ) ) { throw new AnnotationException( "An entity cannot be annotated with both @Entity and @MappedSuperclass: " + clazzToProcess.getName() ); @@ -529,7 +525,7 @@ public final class AnnotationBinder { return; } - log.info( "Binding entity from annotated class: {}", clazzToProcess.getName() ); + LOG.bindingEntityFromClass(clazzToProcess.getName()); PersistentClass superEntity = getSuperEntity( clazzToProcess, inheritanceStatePerClass, mappings, inheritanceState @@ -596,15 +592,8 @@ public final class AnnotationBinder { superEntity.getTable() : null ); - } - else { - if ( clazzToProcess.isAnnotationPresent( Table.class ) ) { - log.warn( - "Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: " + clazzToProcess - .getName() - ); - } - } + } else if (clazzToProcess.isAnnotationPresent(Table.class)) LOG.invalidTableAnnotation(clazzToProcess.getName()); + PropertyHolder propertyHolder = PropertyHolderBuilder.buildPropertyHolder( clazzToProcess, @@ -673,11 +662,7 @@ public final class AnnotationBinder { } } } - if ( onDeleteAnn != null && !onDeleteAppropriate ) { - log.warn( - "Inapropriate use of @OnDelete on entity, annotation ignored: {}", propertyHolder.getEntityName() - ); - } + if (onDeleteAnn != null && !onDeleteAppropriate) LOG.invalidOnDeleteAnnotation(propertyHolder.getEntityName()); // try to find class level generators HashMap classGenerators = buildLocalGenerators( clazzToProcess, mappings ); @@ -753,12 +738,7 @@ public final class AnnotationBinder { discriminatorType, discAnn, discFormulaAnn, mappings ); } - if ( discAnn != null && inheritanceState.hasParents() ) { - log.warn( - "Discriminator column has to be defined in the root entity, it will be ignored in subclass: {}", - clazzToProcess.getName() - ); - } + if (discAnn != null && inheritanceState.hasParents()) LOG.invalidDescriminatorAnnotation(clazzToProcess.getName()); String discrimValue = clazzToProcess.isAnnotationPresent( DiscriminatorValue.class ) ? clazzToProcess.getAnnotation( DiscriminatorValue.class ).value() : @@ -766,7 +746,7 @@ public final class AnnotationBinder { entityBinder.setDiscriminatorValue( discrimValue ); if ( clazzToProcess.isAnnotationPresent( ForceDiscriminator.class ) ) { - log.warn( "@ForceDiscriminator is deprecated use @DiscriminatorOptions instead." ); + LOG.deprecatedForceDescriminatorAnnotation(); entityBinder.setForceDiscriminator( true ); } @@ -1016,7 +996,7 @@ public final class AnnotationBinder { SharedCacheMode mode; final Object value = mappings.getConfigurationProperties().get( "javax.persistence.sharedCache.mode" ); if ( value == null ) { - log.debug( "no value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED" ); + LOG.sharedCacheModeNotFound(); mode = SharedCacheMode.UNSPECIFIED; } else { @@ -1028,10 +1008,7 @@ public final class AnnotationBinder { mode = SharedCacheMode.valueOf( value.toString() ); } catch ( Exception e ) { - log.debug( - "Unable to resolve given mode name [" + value.toString() - + "]; using UNSPECIFIED : " + e.toString() - ); + LOG.invalidSharedCacheMode(value, e); mode = SharedCacheMode.UNSPECIFIED; } } @@ -1047,24 +1024,24 @@ public final class AnnotationBinder { static void prepareDefaultCacheConcurrencyStrategy(Properties properties) { if ( DEFAULT_CACHE_CONCURRENCY_STRATEGY != null ) { - log.trace( "Default cache concurrency strategy already defined" ); + LOG.defaultCacheConcurrencyStrategyAlreadyDefined(); return; } if ( !properties.containsKey( Configuration.DEFAULT_CACHE_CONCURRENCY_STRATEGY ) ) { - log.trace( "Given properties did not contain any default cache concurrency strategy setting" ); + LOG.defaultCacheConcurrencyStrategyNotFound(); return; } final String strategyName = properties.getProperty( Configuration.DEFAULT_CACHE_CONCURRENCY_STRATEGY ); - log.trace( "Discovered default cache concurrency strategy via config [" + strategyName + "]" ); + LOG.defaultCacheConcurrencyStrategyDiscovered(strategyName); CacheConcurrencyStrategy strategy = CacheConcurrencyStrategy.parse( strategyName ); if ( strategy == null ) { - log.trace( "Discovered default cache concurrency strategy specified nothing" ); + LOG.defaultCacheConcurrencyStrategySpecifiedNothing(); return; } - log.debug( "Setting default cache concurrency strategy via config [" + strategy.name() + "]" ); + LOG.defaultCacheConcurrencyStrategy(strategy.name()); DEFAULT_CACHE_CONCURRENCY_STRATEGY = strategy; } @@ -1159,13 +1136,11 @@ public final class AnnotationBinder { ( Map ) null, ( PropertyHolder ) null, mappings ); } - log.trace( "Subclass joined column(s) created" ); + LOG.subclassJoinedColumnsCreated(); } else { - if ( clazzToProcess.isAnnotationPresent( PrimaryKeyJoinColumns.class ) - || clazzToProcess.isAnnotationPresent( PrimaryKeyJoinColumn.class ) ) { - log.warn( "Root entity should not hold an PrimaryKeyJoinColum(s), will be ignored" ); - } + if (clazzToProcess.isAnnotationPresent(PrimaryKeyJoinColumns.class) + || clazzToProcess.isAnnotationPresent(PrimaryKeyJoinColumn.class)) LOG.invalidPrimaryKeyJoinColumnAnnotation(); } return inheritanceJoinedColumns; } @@ -1196,13 +1171,9 @@ public final class AnnotationBinder { || AnnotatedClassType.NONE.equals( classType ) //to be ignored || AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration ) { - if ( AnnotatedClassType.NONE.equals( classType ) - && clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) { - log.warn( - "Class annotated @org.hibernate.annotations.Entity but not javax.persistence.Entity " - + "(most likely a user error): {}", clazzToProcess.getName() - ); - } + if (AnnotatedClassType.NONE.equals(classType) + && clazzToProcess.isAnnotationPresent(org.hibernate.annotations.Entity.class)) + LOG.missingEntityAnnotation(clazzToProcess.getName()); return false; } @@ -1271,7 +1242,7 @@ public final class AnnotationBinder { params.put( param.name(), mappings.getTypeResolver().heuristicType( param.type() ) ); } FilterDefinition def = new FilterDefinition( defAnn.name(), defAnn.defaultCondition(), params ); - log.info( "Binding filter definition: {}", def.getFilterName() ); + LOG.bindingFilterDefinition(def.getFilterName()); mappings.addFilterDefinition( def ); } @@ -1327,11 +1298,11 @@ public final class AnnotationBinder { } if ( !BinderHelper.isEmptyAnnotationValue( defAnn.name() ) ) { - log.info( "Binding type definition: {}", defAnn.name() ); + LOG.bindingTypeDefinition(defAnn.name()); mappings.addTypeDef( defAnn.name(), defAnn.typeClass().getName(), params ); } if ( !defAnn.defaultForType().equals( void.class ) ) { - log.info( "Binding type definition: {}", defAnn.defaultForType().getName() ); + LOG.bindingTypeDefinition(defAnn.defaultForType().getName()); mappings.addTypeDef( defAnn.defaultForType().getName(), defAnn.typeClass().getName(), params ); } @@ -1355,7 +1326,7 @@ public final class AnnotationBinder { discriminatorColumn.linkWithValue( discrim ); discrim.setTypeName( discriminatorColumn.getDiscriminatorTypeName() ); rootClass.setPolymorphic( true ); - log.trace( "Setting discriminator for entity {}", rootClass.getEntityName() ); + LOG.settingDiscriminator(rootClass.getEntityName()); } } @@ -1474,9 +1445,7 @@ public final class AnnotationBinder { * ordering does not matter */ - log.trace( - "Processing annotations of {}.{}", propertyHolder.getEntityName(), inferredData.getPropertyName() - ); + LOG.processingAnnotations(propertyHolder.getEntityName(), inferredData.getPropertyName()); final XProperty property = inferredData.getProperty(); if ( property.isAnnotationPresent( Parent.class ) ) { @@ -1540,7 +1509,7 @@ public final class AnnotationBinder { + propertyHolder.getEntityName() ); } - log.trace( "{} is a version property", inferredData.getPropertyName() ); + LOG.versionProperty(inferredData.getPropertyName()); RootClass rootClass = ( RootClass ) propertyHolder.getPersistentClass(); propertyBinder.setColumns( columns ); Property prop = propertyBinder.makePropertyValueAndBind(); @@ -1564,10 +1533,7 @@ public final class AnnotationBinder { SimpleValue simpleValue = ( SimpleValue ) prop.getValue(); simpleValue.setNullValue( "undefined" ); rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION ); - log.trace( - "Version name: {}, unsavedValue: {}", rootClass.getVersion().getName(), - ( ( SimpleValue ) rootClass.getVersion().getValue() ).getNullValue() - ); + LOG.version(rootClass.getVersion().getName(), ((SimpleValue)rootClass.getVersion().getValue()).getNullValue()); } else { final boolean forcePersist = property.isAnnotationPresent( MapsId.class ) @@ -2132,7 +2098,7 @@ public final class AnnotationBinder { } private static void setVersionInformation(XProperty property, PropertyBinder propertyBinder) { - propertyBinder.getSimpleValueBinder().setVersion( true ); + propertyBinder.getSimpleValueBinder().setVersion( true ); if(property.isAnnotationPresent( Source.class )) { Source source = property.getAnnotation( Source.class ); propertyBinder.getSimpleValueBinder().setTimestampVersionType( source.value().typeName() ); @@ -2175,9 +2141,7 @@ public final class AnnotationBinder { } //a component must not have any generator BinderHelper.makeIdGenerator( idValue, generatorType, generatorName, mappings, localGenerators ); - log.trace( - "Bind {} on {}", ( isComponent ? "@EmbeddedId" : "@Id" ), inferredData.getPropertyName() - ); + LOG.bindAnnotationToProperty((isComponent ? "@EmbeddedId" : "@Id"), inferredData.getPropertyName()); } //TODO move that to collection binder? @@ -2359,7 +2323,7 @@ public final class AnnotationBinder { */ Component comp = createComponent( propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper, mappings ); String subpath = BinderHelper.getPath( propertyHolder, inferredData ); - log.trace( "Binding component with path: {}", subpath ); + LOG.bindingComponent(subpath); PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder( comp, subpath, inferredData, propertyHolder, mappings @@ -2788,7 +2752,7 @@ public final class AnnotationBinder { Mappings mappings) { //column.getTable() => persistentClass.getTable() final String propertyName = inferredData.getPropertyName(); - log.trace( "Fetching {} with {}", propertyName, fetchMode ); + LOG.fetching(propertyName, fetchMode); boolean mapToPK = true; if ( !trueOneToOne ) { //try to find a hidden true one to one (FK == PK columns) @@ -3076,12 +3040,7 @@ public final class AnnotationBinder { if ( superclassState.getType() != null ) { final boolean mixingStrategy = state.getType() != null && !state.getType() .equals( superclassState.getType() ); - if ( nonDefault && mixingStrategy ) { - log.warn( - "Mixing inheritance strategy in a entity hierarchy is not allowed, ignoring sub strategy in: {}", - clazz.getName() - ); - } + if (nonDefault && mixingStrategy) LOG.invalidSubStrategy(clazz.getName()); state.setType( superclassState.getType() ); } } @@ -3117,4 +3076,143 @@ 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/AnnotationConfiguration.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java index 534c52e218..f9dd2fb433 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java @@ -26,36 +26,11 @@ package org.hibernate.cfg; import java.io.File; import java.io.InputStream; import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.Properties; -import javax.persistence.Embeddable; -import javax.persistence.Entity; -import javax.persistence.MappedSuperclass; -import javax.persistence.MapsId; - import org.dom4j.Document; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.AnnotationException; -import org.hibernate.DuplicateMappingException; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.MappingException; -import org.hibernate.annotations.AnyMetaDef; -import org.hibernate.annotations.common.reflection.ReflectionManager; -import org.hibernate.annotations.common.reflection.XClass; -import org.hibernate.engine.NamedQueryDefinition; -import org.hibernate.engine.NamedSQLQueryDefinition; -import org.hibernate.engine.ResultSetMappingDefinition; -import org.hibernate.mapping.IdGenerator; -import org.hibernate.mapping.Join; -import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Table; -import org.hibernate.util.CollectionHelper; /** * Similar to the {@link Configuration} object but handles EJB3 and Hibernate @@ -68,7 +43,6 @@ import org.hibernate.util.CollectionHelper; */ @Deprecated public class AnnotationConfiguration extends Configuration { - private Logger log = LoggerFactory.getLogger( AnnotationConfiguration.class ); public AnnotationConfiguration() { super(); 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 7578ac516a..6f2cd9cc60 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java @@ -23,6 +23,7 @@ */ package org.hibernate.cfg; +import static org.jboss.logging.Logger.Level.INFO; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -33,7 +34,6 @@ import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.MappingException; @@ -54,6 +54,7 @@ import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.IdGenerator; import org.hibernate.mapping.Join; +import org.hibernate.mapping.MappedSuperclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.SimpleValue; @@ -61,10 +62,11 @@ import org.hibernate.mapping.SyntheticProperty; import org.hibernate.mapping.Table; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; -import org.hibernate.mapping.MappedSuperclass; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard @@ -72,7 +74,9 @@ import org.slf4j.LoggerFactory; public class BinderHelper { public static final String ANNOTATION_STRING_DEFAULT = ""; - private static Logger log = LoggerFactory.getLogger( BinderHelper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BinderHelper.class.getPackage().getName()); private BinderHelper() { } @@ -590,7 +594,7 @@ public class BinderHelper { Ejb3Column[] metaColumns = Ejb3Column.buildColumnFromAnnotation( new javax.persistence.Column[] { metaColumn }, null, - nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), mappings + nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), mappings ); //set metaColumn to the right table for (Ejb3Column column : metaColumns) { @@ -638,7 +642,7 @@ public class BinderHelper { private static void bindAnyMetaDef(AnyMetaDef defAnn, Mappings mappings) { if ( isEmptyAnnotationValue( defAnn.name() ) ) return; //don't map not named definitions - log.info( "Binding Any Meta definition: {}", defAnn.name() ); + LOG.bindingAnyMetaDefinition(defAnn.name()); mappings.addAnyMetaDef( defAnn ); } @@ -692,4 +696,15 @@ public class BinderHelper { 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 115353f569..e69472162a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/CollectionSecondPass.java @@ -23,18 +23,20 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; 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 @@ -42,7 +44,10 @@ import org.hibernate.mapping.Value; * @author Emmanuel Bernard */ public abstract class CollectionSecondPass implements SecondPass { - private static Logger log = LoggerFactory.getLogger( CollectionSecondPass.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionSecondPass.class.getPackage().getName()); + Mappings mappings; Collection collection; private Map localInheritedMetas; @@ -59,13 +64,12 @@ public abstract class CollectionSecondPass implements SecondPass { public void doSecondPass(java.util.Map persistentClasses) throws MappingException { - if ( log.isDebugEnabled() ) - log.debug( "Second pass for collection: " + collection.getRole() ); + LOG.secondPass(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(); - if ( log.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { String msg = "Mapped collection key: " + columns( collection.getKey() ); if ( collection.isIndexed() ) msg += ", index: " + columns( ( (IndexedCollection) collection ).getIndex() ); @@ -76,7 +80,7 @@ public abstract class CollectionSecondPass implements SecondPass { else { msg += ", element: " + columns( collection.getElement() ); } - log.debug( msg ); + LOG.mappedCollection(msg); } } @@ -92,4 +96,19 @@ 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 da55a6c0ee..72505b8f27 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -23,6 +23,11 @@ */ 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; @@ -58,16 +63,10 @@ import java.util.zip.ZipEntry; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.MapsId; - import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; 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.AnnotationException; import org.hibernate.DuplicateMappingException; import org.hibernate.EmptyInterceptor; @@ -153,7 +152,6 @@ import org.hibernate.mapping.UniqueKey; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.JACCConfiguration; import org.hibernate.service.spi.ServicesRegistry; -import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.tool.hbm2ddl.DatabaseMetadata; import org.hibernate.tool.hbm2ddl.IndexMetadata; import org.hibernate.tool.hbm2ddl.TableMetadata; @@ -177,6 +175,12 @@ 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; /** * An instance of Configuration allows the application @@ -196,7 +200,9 @@ import org.hibernate.util.xml.XmlDocumentImpl; * @see org.hibernate.SessionFactory */ public class Configuration implements Serializable { - private static Logger log = LoggerFactory.getLogger( Configuration.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Configuration.class.getPackage().getName()); /** * Setting used to give the name of the default {@link org.hibernate.annotations.CacheConcurrencyStrategy} @@ -492,7 +498,7 @@ public class Configuration implements Serializable { * have indicated a problem parsing the XML document, but that is now delayed until after {@link #buildMappings} */ public Configuration addFile(final File xmlFile) throws MappingException { - log.info( "Reading mappings from file: " + xmlFile.getPath() ); + LOG.readingMappingsFromFile(xmlFile.getPath()); final String name = xmlFile.getAbsolutePath(); final InputSource inputSource; try { @@ -561,10 +567,10 @@ public class Configuration implements Serializable { return addCacheableFileStrictly( xmlFile ); } catch ( SerializationException e ) { - log.warn( "Could not deserialize cache file: " + cachedFile.getPath() + " : " + e ); + LOG.unableToDeserializeCache(cachedFile.getPath(), e); } catch ( FileNotFoundException e ) { - log.warn( "I/O reported cached file could not be found : " + cachedFile.getPath() + " : " + e ); + LOG.cachedFileNotFound(cachedFile.getPath(), e); } final String name = xmlFile.getAbsolutePath(); @@ -576,18 +582,14 @@ public class Configuration implements Serializable { throw new MappingNotFoundException( "file", xmlFile.toString() ); } - log.info( "Reading mappings from file: " + xmlFile ); + LOG.readingMappingsFromFile(xmlFile.getPath()); XmlDocument metadataXml = add( inputSource, "file", name ); try { - log.debug( "Writing cache file for: " + xmlFile + " to: " + cachedFile ); + LOG.writingCacheFile(xmlFile, cachedFile); SerializationHelper.serialize( ( Serializable ) metadataXml.getDocumentTree(), new FileOutputStream( cachedFile ) ); - } - catch ( SerializationException e ) { - log.warn( "Could not write cached file: " + cachedFile, e ); - } - catch ( FileNotFoundException e ) { - log.warn( "I/O reported error writing cached file : " + cachedFile.getPath(), e ); + } catch (Exception e) { + LOG.unableToWriteCachedFile(cachedFile.getPath(), e.getMessage()); } return this; @@ -621,7 +623,7 @@ public class Configuration implements Serializable { throw new FileNotFoundException( "Cached file could not be found or could not be used" ); } - log.info( "Reading mappings from cache file: " + cachedFile ); + LOG.readingCachedMappings(cachedFile); Document document = ( Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) ); add( new XmlDocumentImpl( document, "file", xmlFile.getAbsolutePath() ) ); return this; @@ -651,9 +653,7 @@ public class Configuration implements Serializable { * given XML string */ public Configuration addXML(String xml) throws MappingException { - if ( log.isDebugEnabled() ) { - log.debug( "Mapping XML:\n" + xml ); - } + LOG.mappingXml(xml); final InputSource inputSource = new InputSource( new StringReader( xml ) ); add( inputSource, "string", "XML String" ); return this; @@ -670,9 +670,7 @@ public class Configuration implements Serializable { public Configuration addURL(URL url) throws MappingException { final String urlExternalForm = url.toExternalForm(); - if ( log.isDebugEnabled() ) { - log.debug( "Reading mapping document from URL : {}", urlExternalForm ); - } + LOG.readingMappingDocument(urlExternalForm); try { add( url.openStream(), "URL", urlExternalForm ); @@ -693,7 +691,7 @@ public class Configuration implements Serializable { inputStream.close(); } catch ( IOException ignore ) { - log.trace( "Was unable to close input stream" ); + LOG.unableToCloseInputStream(); } } } @@ -707,9 +705,7 @@ public class Configuration implements Serializable { * the mapping document. */ public Configuration addDocument(org.w3c.dom.Document doc) throws MappingException { - if ( log.isDebugEnabled() ) { - log.debug( "Mapping document:\n" + doc ); - } + LOG.mappingDocument(doc); final Document document = xmlHelper.createDOMReader().read( doc ); add( new XmlDocumentImpl( document, "unknown", null ) ); @@ -740,7 +736,7 @@ public class Configuration implements Serializable { * processing the contained mapping document. */ public Configuration addResource(String resourceName, ClassLoader classLoader) throws MappingException { - log.info( "Reading mappings from resource: " + resourceName ); + LOG.readingMappingsFromResource(resourceName); InputStream resourceInputStream = classLoader.getResourceAsStream( resourceName ); if ( resourceInputStream == null ) { throw new MappingNotFoundException( "resource", resourceName ); @@ -759,7 +755,7 @@ public class Configuration implements Serializable { * processing the contained mapping document. */ public Configuration addResource(String resourceName) throws MappingException { - log.info( "Reading mappings from resource : " + resourceName ); + LOG.readingMappingsFromResource(resourceName); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceInputStream = null; if ( contextClassLoader != null ) { @@ -787,7 +783,7 @@ public class Configuration implements Serializable { */ public Configuration addClass(Class persistentClass) throws MappingException { String mappingResourceName = persistentClass.getName().replace( '.', '/' ) + ".hbm.xml"; - log.info( "Reading mappings from resource: " + mappingResourceName ); + LOG.readingMappingsFromResource(mappingResourceName); return addResource( mappingResourceName, persistentClass.getClassLoader() ); } @@ -815,13 +811,13 @@ public class Configuration implements Serializable { * @throws MappingException in case there is an error in the mapping data */ public Configuration addPackage(String packageName) throws MappingException { - log.info( "Mapping package {}", packageName ); + LOG.mappingPackage(packageName); try { AnnotationBinder.bindPackage( packageName, createMappings() ); return this; } catch ( MappingException me ) { - log.error( "Could not parse the package-level metadata [" + packageName + "]" ); + LOG.unableToParseMetadata(packageName); throw me; } } @@ -837,7 +833,7 @@ public class Configuration implements Serializable { * processing the contained mapping documents. */ public Configuration addJar(File jar) throws MappingException { - log.info( "Searching for mapping documents in jar: " + jar.getName() ); + LOG.searchingForMappingDocuments(jar.getName()); JarFile jarFile = null; try { try { @@ -853,7 +849,7 @@ public class Configuration implements Serializable { while ( jarEntries.hasMoreElements() ) { ZipEntry ze = (ZipEntry) jarEntries.nextElement(); if ( ze.getName().endsWith( ".hbm.xml" ) ) { - log.info( "Found mapping document in jar: " + ze.getName() ); + LOG.foundMappingDocument(ze.getName()); try { addInputStream( jarFile.getInputStream( ze ) ); } @@ -875,7 +871,7 @@ public class Configuration implements Serializable { } } catch (IOException ioe) { - log.error("could not close jar", ioe); + LOG.unableToCloseJar(ioe.getMessage()); } } @@ -1171,7 +1167,7 @@ public class Configuration implements Serializable { while ( iter.hasNext() ) { Table table = (Table) iter.next(); if ( table.isPhysicalTable() ) { - + TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), ( table.getSchema() == null ) ? defaultSchema : table.getSchema(), @@ -1297,12 +1293,12 @@ public class Configuration implements Serializable { String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG ); String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA ); - + Iterator iter = getTableMappings(); while ( iter.hasNext() ) { Table table = (Table) iter.next(); if ( table.isPhysicalTable() ) { - + TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), @@ -1349,7 +1345,7 @@ public class Configuration implements Serializable { } protected void secondPassCompile() throws MappingException { - log.trace( "Starting secondPassCompile() processing" ); + LOG.startingSecondPassCompile(); //process default values first { @@ -1436,7 +1432,7 @@ public class Configuration implements Serializable { * an entity having a PK made of a ManyToOne ...). */ private void processFkSecondPassInOrder() { - log.debug( "processing fk mappings (*ToOne and JoinedSubclass)" ); + LOG.processingForeignKeyMappings(); List fkSecondPasses = getFKSecondPassesOnly(); if ( fkSecondPasses.size() == 0 ) { @@ -1645,9 +1641,7 @@ public class Configuration implements Serializable { applyMethod = classValidator.getMethod( "apply", PersistentClass.class ); } catch ( ClassNotFoundException e ) { - if ( !isValidatorNotPresentLogged ) { - log.info( "Hibernate Validator not found: ignoring" ); - } + if (!isValidatorNotPresentLogged) LOG.validatorNotFound(); isValidatorNotPresentLogged = true; } catch ( NoSuchMethodException e ) { @@ -1665,7 +1659,7 @@ public class Configuration implements Serializable { applyMethod.invoke( validator, persistentClazz ); } catch ( Exception e ) { - log.warn( "Unable to apply constraints on DDL for " + className, e ); + LOG.unableToApplyConstraints(className, e.getMessage()); } } } @@ -1678,10 +1672,10 @@ public class Configuration implements Serializable { } private void originalSecondPassCompile() throws MappingException { - log.debug( "processing extends queue" ); + LOG.processingExtendsQueue(); processExtendsQueue(); - log.debug( "processing collection mappings" ); + LOG.processingCollectionMappings(); Iterator itr = secondPasses.iterator(); while ( itr.hasNext() ) { SecondPass sp = (SecondPass) itr.next(); @@ -1691,7 +1685,7 @@ public class Configuration implements Serializable { } } - log.debug( "processing native query and ResultSetMapping mappings" ); + LOG.processingNativeQuery(); itr = secondPasses.iterator(); while ( itr.hasNext() ) { SecondPass sp = (SecondPass) itr.next(); @@ -1699,7 +1693,7 @@ public class Configuration implements Serializable { itr.remove(); } - log.debug( "processing association property references" ); + LOG.processingAssociationPropertyReferences(); itr = propertyReferences.iterator(); while ( itr.hasNext() ) { @@ -1721,7 +1715,7 @@ public class Configuration implements Serializable { //TODO: Somehow add the newly created foreign keys to the internal collection - log.debug( "processing foreign key constraints" ); + LOG.processingForeignKeyConstraints(); itr = getTableMappings(); Set done = new HashSet(); @@ -1732,7 +1726,7 @@ public class Configuration implements Serializable { } private int processExtendsQueue() { - log.debug( "processing extends queue" ); + LOG.processingExtendsQueue(); int added = 0; ExtendsQueueEntry extendsQueueEntry = findPossibleExtends(); while ( extendsQueueEntry != null ) { @@ -1789,9 +1783,7 @@ public class Configuration implements Serializable { " does not specify the referenced entity" ); } - if ( log.isDebugEnabled() ) { - log.debug( "resolving reference to class: " + referencedEntityName ); - } + LOG.resolvingReference(referencedEntityName); PersistentClass referencedClass = classes.get( referencedEntityName ); if ( referencedClass == null ) { throw new MappingException( @@ -1824,12 +1816,10 @@ public class Configuration implements Serializable { * @throws HibernateException usually indicates an invalid configuration or invalid mapping information */ public SessionFactory buildSessionFactory(ServicesRegistry serviceRegistry) throws HibernateException { - log.debug( "Preparing to build session factory with filters : " + filterDefinitions ); + LOG.debug("Preparing to build session factory with filters : " + filterDefinitions); secondPassCompile(); - if ( ! metadataSourceQueue.isEmpty() ) { - log.warn( "mapping metadata cache was not completely processed" ); - } + if (!metadataSourceQueue.isEmpty()) LOG.incompleteMappingMetadataCacheProcessing(); enableLegacyHibernateValidator(); enableBeanValidation(); @@ -1867,7 +1857,7 @@ public class Configuration implements Serializable { } catch ( ClassNotFoundException e ) { //validator is not present - log.debug( "Legacy Validator not present in classpath, ignoring event listener registration" ); + LOG.legacyValidatorNotFound(); } if ( enableValidatorListeners && validateEventListenerClass != null ) { //TODO so much duplication @@ -1950,7 +1940,7 @@ public class Configuration implements Serializable { searchStartupClass = ReflectHelper.classForName( SEARCH_EVENT_LISTENER_REGISTERER_CLASS, getClass() ); } catch ( ClassNotFoundException cnfe ) { - log.debug( "Search not present in classpath, ignoring event listener registration." ); + LOG.searchNotFound(); return; } } @@ -1966,16 +1956,16 @@ public class Configuration implements Serializable { enableSearchMethod.invoke( searchStartupInstance, getEventListeners(), getProperties() ); } catch ( InstantiationException e ) { - log.debug( "Unable to instantiate {}, ignoring event listener registration.", SEARCH_STARTUP_CLASS ); + LOG.unableToInstantiate(SEARCH_STARTUP_CLASS); } catch ( IllegalAccessException e ) { - log.debug( "Unable to instantiate {}, ignoring event listener registration.", SEARCH_STARTUP_CLASS ); + LOG.unableToInstantiate(SEARCH_STARTUP_CLASS); } catch ( NoSuchMethodException e ) { - log.debug( "Method enableHibernateSearch() not found in {}.", SEARCH_STARTUP_CLASS ); + LOG.methodNotFound(SEARCH_STARTUP_METHOD, SEARCH_STARTUP_CLASS); } catch ( InvocationTargetException e ) { - log.debug( "Unable to execute {}, ignoring event listener registration.", SEARCH_STARTUP_METHOD ); + LOG.unableToExecute(SEARCH_STARTUP_METHOD); } } @@ -2089,7 +2079,7 @@ public class Configuration implements Serializable { Element node = (Element) itr.next(); String name = node.attributeValue( "name" ); String value = node.getText().trim(); - log.debug( name + "=" + value ); + LOG.attribute(name, value); properties.setProperty( name, value ); if ( !name.startsWith( "hibernate" ) ) { properties.setProperty( "hibernate." + name, value ); @@ -2127,7 +2117,7 @@ public class Configuration implements Serializable { * @see #doConfigure(java.io.InputStream, String) */ public Configuration configure(String resource) throws HibernateException { - log.info( "configuring from resource: " + resource ); + LOG.configuringFromResource(resource); InputStream stream = getConfigurationInputStream( resource ); return doConfigure( stream, resource ); } @@ -2146,7 +2136,7 @@ public class Configuration implements Serializable { * @throws HibernateException Generally indicates we cannot find the named resource */ protected InputStream getConfigurationInputStream(String resource) throws HibernateException { - log.info( "Configuration resource: " + resource ); + LOG.configurationResource(resource); return ConfigHelper.getResourceAsStream( resource ); } @@ -2163,7 +2153,7 @@ public class Configuration implements Serializable { * @see #doConfigure(java.io.InputStream, String) */ public Configuration configure(URL url) throws HibernateException { - log.info( "configuring from url: " + url.toString() ); + LOG.configuringFromUrl(url); try { return doConfigure( url.openStream(), url.toString() ); } @@ -2185,7 +2175,7 @@ public class Configuration implements Serializable { * @see #doConfigure(java.io.InputStream, String) */ public Configuration configure(File configFile) throws HibernateException { - log.info( "configuring from file: " + configFile.getName() ); + LOG.configuringFromFile(configFile.getName()); try { return doConfigure( new FileInputStream( configFile ), configFile.toString() ); } @@ -2224,7 +2214,7 @@ public class Configuration implements Serializable { stream.close(); } catch (IOException ioe) { - log.warn( "could not close input stream for: " + resourceName, ioe ); + LOG.unableToCloseInputStream(resourceName, ioe.getMessage()); } } return this; @@ -2240,7 +2230,7 @@ public class Configuration implements Serializable { * @throws HibernateException if there is problem in accessing the file. */ public Configuration configure(org.w3c.dom.Document document) throws HibernateException { - log.info( "configuring from XML document" ); + LOG.configuringFromXmlDocument(); return doConfigure( xmlHelper.createDOMReader().read( document ) ); } @@ -2268,8 +2258,8 @@ public class Configuration implements Serializable { parseSecurity( secNode ); } - log.info( "Configured SessionFactory: " + name ); - log.debug( "properties: " + properties ); + LOG.configuredSessionFactory(name); + LOG.properties(properties); return this; } @@ -2314,27 +2304,27 @@ public class Configuration implements Serializable { if ( resourceAttribute != null ) { final String resourceName = resourceAttribute.getValue(); - log.debug( "session-factory config [{}] named resource [{}] for mapping", name, resourceName ); + LOG.sessionFactoryConfigResourceForMapping(name, resourceName); addResource( resourceName ); } else if ( fileAttribute != null ) { final String fileName = fileAttribute.getValue(); - log.debug( "session-factory config [{}] named file [{}] for mapping", name, fileName ); + LOG.sessionFactoryConfigFileForMapping(name, fileName); addFile( fileName ); } else if ( jarAttribute != null ) { final String jarFileName = jarAttribute.getValue(); - log.debug( "session-factory config [{}] named jar file [{}] for mapping", name, jarFileName ); + LOG.sessionFactoryConfigJarForMapping(name, jarFileName); addJar( new File( jarFileName ) ); } else if ( packageAttribute != null ) { final String packageName = packageAttribute.getValue(); - log.debug( "session-factory config [{}] named package [{}] for mapping", name, packageName ); + LOG.sessionFactoryConfigPackageForMapping(name, packageName); addPackage( packageName ); } else if ( classAttribute != null ) { final String className = classAttribute.getValue(); - log.debug( "session-factory config [{}] named class [{}] for mapping", name, className ); + LOG.sessionFactoryConfigClassForMapping(name, className); try { addAnnotatedClass( ReflectHelper.classForName( className ) ); @@ -2353,8 +2343,8 @@ public class Configuration implements Serializable { private void parseSecurity(Element secNode) { String contextId = secNode.attributeValue( "context" ); - setProperty(Environment.JACC_CONTEXTID, contextId); - log.info( "JACC contextID: " + contextId ); + setProperty(Environment.JACC_CONTEXTID, contextId); + LOG.jaccContextId(contextId); JACCConfiguration jcfg = new JACCConfiguration( contextId ); Iterator grantElements = secNode.elementIterator(); while ( grantElements.hasNext() ) { @@ -2377,7 +2367,7 @@ public class Configuration implements Serializable { for ( int i = 0; i < listeners.size() ; i++ ) { listenerClasses[i] = ( (Element) listeners.get( i ) ).attributeValue( "class" ); } - log.debug( "Event listeners: " + type + "=" + StringHelper.toString( listenerClasses ) ); + LOG.eventListeners(type, StringHelper.toString(listenerClasses)); setListeners( type, listenerClasses ); } @@ -2387,7 +2377,7 @@ public class Configuration implements Serializable { throw new MappingException( "No type specified for listener" ); } String impl = element.attributeValue( "class" ); - log.debug( "Event listener: " + type + "=" + impl ); + LOG.eventListener(type, impl); setListeners( type, new String[]{impl} ); } @@ -3129,17 +3119,9 @@ public class Configuration implements Serializable { public void addImport(String entityName, String rename) throws DuplicateMappingException { String existing = imports.put( rename, entityName ); if ( existing != null ) { - if ( existing.equals( entityName ) ) { - log.info( "duplicate import: {} -> {}", entityName, rename ); - } - else { - throw new DuplicateMappingException( - "duplicate import: " + rename + " refers to both " + entityName + - " and " + existing + " (try using auto-import=\"false\")", - "import", - rename - ); - } + if (existing.equals(entityName)) LOG.duplicateImport(entityName, rename); + else throw new DuplicateMappingException("duplicate import: " + rename + " refers to both " + entityName + " and " + + existing + " (try using auto-import=\"false\")", "import", rename); } } @@ -3308,7 +3290,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.debug( "Added " + typeName + " with class " + typeClass ); + LOG.addedType(typeName, typeClass); } public Map getFilterDefinitions() { @@ -3470,7 +3452,7 @@ public class Configuration implements Serializable { } binding.addBinding( logicalName, physicalColumn ); } - + public String getPhysicalColumnName(String logicalName, Table table) throws MappingException { logicalName = logicalName.toLowerCase(); String finalName = null; @@ -3654,17 +3636,13 @@ public class Configuration implements Serializable { public void addGenerator(IdGenerator generator) { if ( !defaultNamedGenerators.contains( generator.getName() ) ) { IdGenerator old = namedGenerators.put( generator.getName(), generator ); - if ( old != null ) { - log.warn( "duplicate generator name {}", old.getName() ); - } + if (old != null) LOG.duplicateGeneratorName(old.getName()); } } public void addGeneratorTable(String name, Properties params) { Object old = generatorTables.put( name, params ); - if ( old != null ) { - log.warn( "duplicate generator table: {}", name ); - } + if (old != null) LOG.duplicateGeneratorTable(name); } public Properties getGeneratorTableProperties(String name, Map localGeneratorTables) { @@ -3683,9 +3661,7 @@ public class Configuration implements Serializable { public void addJoins(PersistentClass persistentClass, Map joins) { Object old = Configuration.this.joins.put( persistentClass.getEntityName(), joins ); - if ( old != null ) { - log.warn( "duplicate joins for class: {}", persistentClass.getEntityName() ); - } + if (old != null) LOG.duplicateJoins(persistentClass.getEntityName()); } public AnnotatedClassType getClassType(XClass clazz) { @@ -3938,7 +3914,7 @@ public class Configuration implements Serializable { } private void processHbmXmlQueue() { - log.debug( "Processing hbm.xml files" ); + LOG.processingHbmFiles(); for ( Map.Entry> entry : hbmMetadataToEntityNamesMap.entrySet() ) { // Unfortunately we have to create a Mappings instance for each iteration here processHbmXml( entry.getKey(), entry.getValue() ); @@ -3954,7 +3930,7 @@ public class Configuration implements Serializable { catch ( MappingException me ) { throw new InvalidMappingException( metadataXml.getOrigin().getType(), - metadataXml.getOrigin().getName(), + metadataXml.getOrigin().getName(), me ); } @@ -3968,7 +3944,7 @@ public class Configuration implements Serializable { } private void processAnnotatedClassesQueue() { - log.debug( "Process annotated classes" ); + LOG.processAnnotatedClasses(); //bind classes in the correct order calculating some inheritance state List orderedClasses = orderAndFillHierarchy( annotatedClasses ); Mappings mappings = createMappings(); @@ -4091,4 +4067,256 @@ 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 90ec6ae0c4..cee5d98352 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,15 @@ */ package org.hibernate.cfg; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.InputStream; - 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Resolve JPA xsd files locally @@ -39,7 +41,8 @@ import org.slf4j.LoggerFactory; public class EJB3DTDEntityResolver extends DTDEntityResolver { public static final EntityResolver INSTANCE = new EJB3DTDEntityResolver(); - private final Logger log = LoggerFactory.getLogger( EJB3DTDEntityResolver.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + EJB3DTDEntityResolver.class.getPackage().getName()); boolean resolved = false; @@ -51,8 +54,9 @@ public class EJB3DTDEntityResolver extends DTDEntityResolver { return resolved; } - public InputSource resolveEntity(String publicId, String systemId) { - log.trace("Resolving XML entity {} : {}", publicId, systemId); + @Override + public InputSource resolveEntity(String publicId, String systemId) { + LOG.resolvingXmlEntity(publicId, systemId); InputSource is = super.resolveEntity( publicId, systemId ); if ( is == null ) { if ( systemId != null ) { @@ -88,25 +92,45 @@ public class EJB3DTDEntityResolver extends DTDEntityResolver { private InputSource buildInputSource(String publicId, String systemId, InputStream dtdStream, boolean resolved) { if ( dtdStream == null ) { - log.trace( "unable to locate [{}] on classpath", systemId ); + LOG.unableToLocate(systemId); return null; } - else { - log.trace( "located [{}] in classpath", systemId ); - InputSource source = new InputSource( dtdStream ); - source.setPublicId( publicId ); - source.setSystemId( systemId ); - this.resolved = resolved; - return source; - } + LOG.located(systemId); + InputSource source = new InputSource(dtdStream); + source.setPublicId(publicId); + source.setSystemId(systemId); + this.resolved = resolved; + return source; } private InputStream getStreamFromClasspath(String fileName) { - log.trace( - "recognized JPA ORM namespace; attempting to resolve on classpath under org/hibernate/ejb" - ); + LOG.resolvingFileName(); 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 9ec7e7da86..161666bcc2 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java @@ -23,8 +23,8 @@ */ 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.annotations.ColumnTransformer; @@ -38,8 +38,10 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; import org.hibernate.util.StringHelper; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; +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 @@ -48,7 +50,10 @@ import org.slf4j.Logger; * @author Emmanuel Bernard */ public class Ejb3Column { - private static final Logger log = LoggerFactory.getLogger( Ejb3Column.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Ejb3Column.class.getPackage().getName()); + private Column mappingColumn; private boolean insertable = true; private boolean updatable = true; @@ -103,7 +108,7 @@ public class Ejb3Column { public boolean isFormula() { return StringHelper.isNotEmpty( formulaString ); } - + public String getFormulaString() { return formulaString; } @@ -181,7 +186,7 @@ public class Ejb3Column { public void bind() { if ( StringHelper.isNotEmpty( formulaString ) ) { - log.debug( "binding formula {}", formulaString ); + LOG.bindingFormula(formulaString); formula = new Formula(); formula.setFormula( formulaString ); } @@ -189,7 +194,7 @@ public class Ejb3Column { initMappingColumn( logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true ); - log.debug( "Binding column: " + toString()); + LOG.bindingColumn(toString()); } } @@ -218,7 +223,7 @@ public class Ejb3Column { this.mappingColumn.setNullable( nullable ); this.mappingColumn.setSqlType( sqlType ); this.mappingColumn.setUnique( unique ); - + if(writeExpression != null && !writeExpression.matches("[^?]*\\?[^?]*")) { throw new AnnotationException( "@WriteExpression must contain exactly one value placeholder ('?') character: property [" @@ -420,7 +425,7 @@ public class Ejb3Column { throw new AnnotationException( "AttributeOverride.column() should override all columns for now" ); } actualCols = overriddenCols.length == 0 ? null : overriddenCols; - log.debug( "Column(s) overridden for property {}", inferredData.getPropertyName() ); + LOG.columnsOverridden(inferredData.getPropertyName()); } if ( actualCols == null ) { columns = buildImplicitColumn( @@ -495,7 +500,7 @@ public class Ejb3Column { } private void processExpression(ColumnTransformer annotation) { - String nonNullLogicalColumnName = logicalColumnName != null ? logicalColumnName : ""; //use the default for annotations + String nonNullLogicalColumnName = logicalColumnName != null ? logicalColumnName : ""; //use the default for annotations if ( annotation != null && ( StringHelper.isEmpty( annotation.forColumn() ) || annotation.forColumn().equals( nonNullLogicalColumnName ) ) ) { @@ -551,14 +556,14 @@ public class Ejb3Column { public static void checkPropertyConsistency(Ejb3Column[] columns, String propertyName) { int nbrOfColumns = columns.length; - + if ( nbrOfColumns > 1 ) { for (int currentIndex = 1; currentIndex < nbrOfColumns; currentIndex++) { - + if (columns[currentIndex].isFormula() || columns[currentIndex - 1].isFormula()) { continue; } - + if ( columns[currentIndex].isInsertable() != columns[currentIndex - 1].isInsertable() ) { throw new AnnotationException( "Mixing insertable and non insertable columns in a property is not allowed: " + propertyName @@ -581,7 +586,7 @@ public class Ejb3Column { } } } - + } public void addIndex(Index index, boolean inSecondPass) { @@ -626,4 +631,23 @@ 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 28006cf688..f6a8bb82fb 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -23,6 +23,9 @@ */ 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; @@ -32,15 +35,15 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; 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; /** @@ -532,7 +535,7 @@ public final class Environment { public static final String JPAQL_STRICT_COMPLIANCE= "hibernate.query.jpaql_strict_compliance"; /** - * When using pooled {@link org.hibernate.id.enhanced.Optimizer optimizers}, prefer interpreting the + * When using pooled {@link org.hibernate.id.enhanced.Optimizer optimizers}, prefer interpreting the * database value as the lower (lo) boundary. The default is to interpret it as the high boundary. */ public static final String PREFER_POOLED_VALUES_LO = "hibernate.id.optimizer.pooled.prefer_lo"; @@ -566,7 +569,8 @@ public final class Environment { private static final Map OBSOLETE_PROPERTIES = new HashMap(); private static final Map RENAMED_PROPERTIES = new HashMap(); - private static final Logger log = LoggerFactory.getLogger(Environment.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Environment.class.getPackage().getName()); /** * Issues warnings to the user when any obsolete or renamed property names are used. @@ -579,12 +583,10 @@ public final class Environment { while ( iter.hasNext() ) { final Object propertyName = iter.next(); Object newPropertyName = OBSOLETE_PROPERTIES.get( propertyName ); - if ( newPropertyName != null ) { - log.warn( "Usage of obsolete property: " + propertyName + " no longer supported, use: " + newPropertyName ); - } + if (newPropertyName != null) LOG.unsupportedProperty(propertyName, newPropertyName); newPropertyName = RENAMED_PROPERTIES.get( propertyName ); if ( newPropertyName != null ) { - log.warn( "Property [" + propertyName + "] has been renamed to [" + newPropertyName + "]; update your properties appropriately" ); + LOG.renamedProperty(propertyName, newPropertyName); if ( ! props.containsKey( newPropertyName ) ) { propertiesToAdd.put( newPropertyName, props.get( propertyName ) ); } @@ -595,7 +597,7 @@ public final class Environment { static { - log.info( "Hibernate " + Version.getVersionString() ); + LOG.version(Version.getVersionString()); RENAMED_PROPERTIES.put( "hibernate.cglib.use_reflection_optimizer", USE_REFLECTION_OPTIMIZER ); @@ -613,29 +615,29 @@ public final class Environment { InputStream stream = ConfigHelper.getResourceAsStream("/hibernate.properties"); try { GLOBAL_PROPERTIES.load(stream); - log.info( "loaded properties from resource hibernate.properties: " + ConfigurationHelper.maskOut(GLOBAL_PROPERTIES, PASS) ); + LOG.propertiesLoaded(ConfigurationHelper.maskOut(GLOBAL_PROPERTIES, PASS)); } catch (Exception e) { - log.error("problem loading properties from hibernate.properties"); + LOG.unableToloadProperties(); } finally { try{ stream.close(); } catch (IOException ioe){ - log.error("could not close stream on hibernate.properties", ioe); + LOG.unableToCloseStream(ioe); } } } catch (HibernateException he) { - log.info("hibernate.properties not found"); + LOG.propertiesNotFound(); } try { GLOBAL_PROPERTIES.putAll( System.getProperties() ); } catch (SecurityException se) { - log.warn("could not copy system properties, system properties will be ignored"); + LOG.unableToCopySystemProperties(); } verifyProperties(GLOBAL_PROPERTIES); @@ -643,12 +645,8 @@ public final class Environment { ENABLE_BINARY_STREAMS = ConfigurationHelper.getBoolean(USE_STREAMS_FOR_BINARY, GLOBAL_PROPERTIES); ENABLE_REFLECTION_OPTIMIZER = ConfigurationHelper.getBoolean(USE_REFLECTION_OPTIMIZER, GLOBAL_PROPERTIES); - if (ENABLE_BINARY_STREAMS) { - log.info("using java.io streams to persist binary types"); - } - if (ENABLE_REFLECTION_OPTIMIZER) { - log.info("using bytecode reflection optimizer"); - } + if (ENABLE_BINARY_STREAMS) LOG.usingStreams(); + if (ENABLE_REFLECTION_OPTIMIZER) LOG.usingReflectionOptimizer(); BYTECODE_PROVIDER_INSTANCE = buildBytecodeProvider( GLOBAL_PROPERTIES ); boolean getGeneratedKeysSupport; @@ -660,9 +658,7 @@ public final class Environment { getGeneratedKeysSupport = false; } JVM_SUPPORTS_GET_GENERATED_KEYS = getGeneratedKeysSupport; - if (!JVM_SUPPORTS_GET_GENERATED_KEYS) { - log.info("JVM does not support Statement.getGeneratedKeys()"); - } + if (!JVM_SUPPORTS_GET_GENERATED_KEYS) LOG.generatedKeysNotSupported(); boolean linkedHashSupport; try { @@ -673,25 +669,17 @@ public final class Environment { linkedHashSupport = false; } JVM_SUPPORTS_LINKED_HASH_COLLECTIONS = linkedHashSupport; - if (!JVM_SUPPORTS_LINKED_HASH_COLLECTIONS) { - log.info("JVM does not support LinkedHasMap, LinkedHashSet - ordered maps and sets disabled"); - } + if (!JVM_SUPPORTS_LINKED_HASH_COLLECTIONS) LOG.linkedMapsAndSetsNotSupported(); long x = 123456789; JVM_HAS_TIMESTAMP_BUG = new Timestamp(x).getTime() != x; - if (JVM_HAS_TIMESTAMP_BUG) { - log.info("using workaround for JVM bug in java.sql.Timestamp"); - } + if (JVM_HAS_TIMESTAMP_BUG) LOG.usingTimestampWorkaround(); Timestamp t = new Timestamp(0); t.setNanos(5 * 1000000); JVM_HAS_JDK14_TIMESTAMP = t.getTime() == 5; - if (JVM_HAS_JDK14_TIMESTAMP) { - log.info("using JDK 1.4 java.sql.Timestamp handling"); - } - else { - log.info("using pre JDK 1.4 java.sql.Timestamp handling"); - } + if (JVM_HAS_JDK14_TIMESTAMP) LOG.usingJdk14TimestampHandling(); + else LOG.usingPreJdk14TimestampHandling(); } public static BytecodeProvider getBytecodeProvider() { @@ -718,7 +706,8 @@ public final class Environment { * * @deprecated Starting with 3.3 Hibernate requires JDK 1.4 or higher */ - public static boolean jvmHasJDK14Timestamp() { + @Deprecated + public static boolean jvmHasJDK14Timestamp() { return JVM_HAS_JDK14_TIMESTAMP; } @@ -733,7 +722,8 @@ public final class Environment { * @see java.util.LinkedHashSet * @see java.util.LinkedHashMap */ - public static boolean jvmSupportsLinkedHashCollections() { + @Deprecated + public static boolean jvmSupportsLinkedHashCollections() { return JVM_SUPPORTS_LINKED_HASH_COLLECTIONS; } @@ -747,7 +737,8 @@ public final class Environment { * @see Statement * @deprecated Starting with 3.3 Hibernate requires JDK 1.4 or higher */ - public static boolean jvmSupportsGetGeneratedKeys() { + @Deprecated + public static boolean jvmSupportsGetGeneratedKeys() { return JVM_SUPPORTS_GET_GENERATED_KEYS; } @@ -806,7 +797,7 @@ public final class Environment { public static BytecodeProvider buildBytecodeProvider(Properties properties) { String provider = ConfigurationHelper.getString( BYTECODE_PROVIDER, properties, "javassist" ); - log.info( "Bytecode provider name : " + provider ); + LOG.bytecodeProvider(provider); return buildBytecodeProvider( provider ); } @@ -818,8 +809,84 @@ public final class Environment { return new org.hibernate.bytecode.cglib.BytecodeProviderImpl(); } - log.warn( "unrecognized bytecode provider [" + providerName + "], using javassist by default" ); + 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 e93dd0e60c..b644df502d 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java @@ -23,13 +23,15 @@ */ 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; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; - import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; @@ -52,6 +54,7 @@ import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.DependantValue; +import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.Fetchable; import org.hibernate.mapping.Filterable; import org.hibernate.mapping.Formula; @@ -86,7 +89,6 @@ import org.hibernate.mapping.TypeDef; import org.hibernate.mapping.UnionSubclass; import org.hibernate.mapping.UniqueKey; import org.hibernate.mapping.Value; -import org.hibernate.mapping.FetchProfile; import org.hibernate.persister.entity.JoinedSubclassEntityPersister; import org.hibernate.persister.entity.SingleTableEntityPersister; import org.hibernate.persister.entity.UnionSubclassEntityPersister; @@ -97,9 +99,10 @@ import org.hibernate.util.JoinedIterator; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; import org.hibernate.util.xml.XmlDocument; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -109,7 +112,8 @@ import org.slf4j.LoggerFactory; */ public final class HbmBinder { - private static final Logger log = LoggerFactory.getLogger( HbmBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HbmBinder.class.getPackage().getName()); /** * Private constructor to disallow instantiation. @@ -230,7 +234,7 @@ public final class HbmBinder { String rename = ( renameNode == null ) ? StringHelper.unqualify( className ) : renameNode.getValue(); - log.debug( "Import: " + rename + " -> " + className ); + LOG.bindImport( rename, className ); mappings.addImport( className, rename ); } @@ -347,10 +351,7 @@ public final class HbmBinder { entity.setTable( table ); bindComment(table, node); - log.info( - "Mapping class: " + entity.getEntityName() + - " -> " + entity.getTable().getName() - ); + LOG.mappingClass(entity.getEntityName(), entity.getTable().getName()); // MUTABLE Attribute mutableNode = node.attribute( "mutable" ); @@ -846,10 +847,7 @@ public final class HbmBinder { ); unionSubclass.setTable( mytable ); - log.info( - "Mapping union-subclass: " + unionSubclass.getEntityName() + - " -> " + unionSubclass.getTable().getName() - ); + LOG.mappingUnionSubclass(unionSubclass.getEntityName(), unionSubclass.getTable().getName()); createClassProperties( node, unionSubclass, mappings, inheritedMetas ); @@ -866,10 +864,7 @@ public final class HbmBinder { .setEntityPersisterClass( SingleTableEntityPersister.class ); } - log.info( - "Mapping subclass: " + subclass.getEntityName() + - " -> " + subclass.getTable().getName() - ); + LOG.mappingSubclass(subclass.getEntityName(), subclass.getTable().getName()); // properties createClassProperties( node, subclass, mappings, inheritedMetas ); @@ -925,10 +920,7 @@ public final class HbmBinder { joinedSubclass.setTable( mytable ); bindComment(mytable, node); - log.info( - "Mapping joined-subclass: " + joinedSubclass.getEntityName() + - " -> " + joinedSubclass.getTable().getName() - ); + LOG.mappingJoinedSubclass(joinedSubclass.getEntityName(), joinedSubclass.getTable().getName()); // KEY Element keyNode = node.element( "key" ); @@ -990,10 +982,8 @@ public final class HbmBinder { join.setOptional( "true".equals( nullNode.getValue() ) ); } - log.info( - "Mapping class join: " + persistentClass.getEntityName() + - " -> " + join.getTable().getName() - ); + + LOG.mappingClassJoin(persistentClass.getEntityName(), join.getTable().getName()); // KEY Element keyNode = node.element( "key" ); @@ -1302,7 +1292,7 @@ public final class HbmBinder { // properties generated on update can never be updateable... if ( property.isUpdateable() && generation == PropertyGeneration.ALWAYS ) { if ( updateNode == null ) { - // updateable only because the user did not specify + // updateable only because the user did not specify // anything; just override it property.setUpdateable( false ); } @@ -1328,13 +1318,13 @@ public final class HbmBinder { property.setLazy( lazyNode != null && "true".equals( lazyNode.getValue() ) ); } - if ( log.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { String msg = "Mapped property: " + property.getName(); String columns = columns( property.getValue() ); 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.debug( msg ); + LOG.mappedProperty(msg); } property.setMetaAttributes( getMetas( node, inheritedMetas ) ); @@ -1378,9 +1368,7 @@ public final class HbmBinder { if ( Environment.jvmSupportsLinkedHashCollections() || ( collection instanceof Bag ) ) { collection.setOrderBy( orderNode.getValue() ); } - else { - log.warn( "Attribute \"order-by\" ignored in JDK1.3 or less" ); - } + else LOG.attributeIgnored(); } Attribute whereNode = node.attribute( "where" ); if ( whereNode != null ) { @@ -1489,10 +1477,7 @@ public final class HbmBinder { collection.setCollectionTable( table ); bindComment(table, node); - log.info( - "Mapping collection: " + collection.getRole() + - " -> " + collection.getCollectionTable().getName() - ); + LOG.mappingCollection(collection.getRole(), collection.getCollectionTable().getName()); } // SORT @@ -1755,7 +1740,7 @@ public final class HbmBinder { } column.setCustomWrite( customWrite ); column.setCustomRead( node.attributeValue( "read" ) ); - + Element comment = node.element("comment"); if (comment!=null) column.setComment( comment.getTextTrim() ); @@ -2080,7 +2065,7 @@ public final class HbmBinder { if ( mappings.getSchemaName() != null ) { params.setProperty( PersistentIdentifierGenerator.SCHEMA, - mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( mappings.getSchemaName() ) + mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( mappings.getSchemaName() ) ); } if ( mappings.getCatalogName() != null ) { @@ -2475,10 +2460,7 @@ public final class HbmBinder { oneToMany.setAssociatedClass( persistentClass ); collection.setCollectionTable( persistentClass.getTable() ); - log.info( - "Mapping collection: " + collection.getRole() + - " -> " + collection.getCollectionTable().getName() - ); + LOG.mappingCollection(collection.getRole(), collection.getCollectionTable().getName()); } // CHECK @@ -2624,11 +2606,7 @@ public final class HbmBinder { if ( condition==null) { throw new MappingException("no filter condition found for filter: " + name); } - log.debug( - "Applying many-to-many filter [" + name + - "] as [" + condition + - "] to role [" + collection.getRole() + "]" - ); + LOG.applyingManyToManyFilter(name, condition, collection.getRole()); collection.addManyToManyFilter( name, condition ); } } @@ -2661,7 +2639,7 @@ public final class HbmBinder { String queryName = queryElem.attributeValue( "name" ); if (path!=null) queryName = path + '.' + queryName; String query = queryElem.getText(); - log.debug( "Named query: " + queryName + " -> " + query ); + LOG.namedQuery(queryName, query); boolean cacheable = "true".equals( queryElem.attributeValue( "cacheable" ) ); String region = queryElem.attributeValue( "cache-region" ); @@ -2771,7 +2749,7 @@ public final class HbmBinder { (IdentifierCollection) collection, persistentClasses, mappings, - inheritedMetas + inheritedMetas ); } @@ -2789,7 +2767,7 @@ public final class HbmBinder { (Map) collection, persistentClasses, mappings, - inheritedMetas + inheritedMetas ); } @@ -2808,7 +2786,7 @@ public final class HbmBinder { } } - + static class ListSecondPass extends CollectionSecondPass { ListSecondPass(Element node, Mappings mappings, List collection, java.util.Map inheritedMetas) { super( node, mappings, collection, inheritedMetas ); @@ -2821,7 +2799,7 @@ public final class HbmBinder { (List) collection, persistentClasses, mappings, - inheritedMetas + inheritedMetas ); } @@ -2961,10 +2939,10 @@ public final class HbmBinder { if ( meta == null ) { meta = new MetaAttribute( name ); map.put( name, meta ); - } else if (meta == inheritedAttribute) { // overriding inherited meta attribute. HBX-621 & HBX-793 - meta = new MetaAttribute( name ); - map.put( name, meta ); - } + } else if (meta == inheritedAttribute) { // overriding inherited meta attribute. HBX-621 & HBX-793 + meta = new MetaAttribute( name ); + map.put( name, meta ); + } meta.addValue( metaNode.getText() ); } return map; @@ -2994,7 +2972,7 @@ public final class HbmBinder { private static void parseFilterDef(Element element, Mappings mappings) { String name = element.attributeValue( "name" ); - log.debug( "Parsing filter-def [" + name + "]" ); + LOG.parsingFilterDefinition(name); String defaultCondition = element.getTextTrim(); if ( StringHelper.isEmpty( defaultCondition ) ) { defaultCondition = element.attributeValue( "condition" ); @@ -3005,12 +2983,12 @@ public final class HbmBinder { final Element param = (Element) params.next(); final String paramName = param.attributeValue( "name" ); final String paramType = param.attributeValue( "type" ); - log.debug( "adding filter parameter : " + paramName + " -> " + paramType ); + LOG.addingFilterParameter(paramName, paramType); final Type heuristicType = mappings.getTypeResolver().heuristicType( paramType ); - log.debug( "parameter heuristic type : " + heuristicType ); + LOG.parameterHeuristicType(heuristicType); paramMappings.put( paramName, heuristicType ); } - log.debug( "Parsed filter-def [" + name + "]" ); + LOG.parsedFilterDefinition(name); FilterDefinition def = new FilterDefinition( name, defaultCondition, paramMappings ); mappings.addFilterDefinition( def ); } @@ -3033,7 +3011,7 @@ public final class HbmBinder { if ( condition==null) { throw new MappingException("no filter condition found for filter: " + name); } - log.debug( "Applying filter [" + name + "] as [" + condition + "]" ); + LOG.applyingFilter(name, condition); filterable.addFilter( name, condition ); } @@ -3169,4 +3147,87 @@ 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 0b65b241d0..632bda748e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/NamedSQLQuerySecondPass.java @@ -23,24 +23,29 @@ */ package org.hibernate.cfg; -import java.util.Map; +import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.Iterator; - -import org.hibernate.MappingException; -import org.hibernate.util.StringHelper; -import org.hibernate.engine.NamedSQLQueryDefinition; -import org.hibernate.engine.ResultSetMappingDefinition; +import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 */ public class NamedSQLQuerySecondPass extends ResultSetMappingBinder implements QuerySecondPass { - private static Logger log = LoggerFactory.getLogger( NamedSQLQuerySecondPass.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NamedSQLQuerySecondPass.class.getPackage().getName()); + private Element queryElem; private String path; private Mappings mappings; @@ -115,7 +120,19 @@ public class NamedSQLQuerySecondPass extends ResultSetMappingBinder implements Q ); } - log.debug( "Named SQL query: " + queryName + " -> " + namedQuery.getQueryString() ); + LOG.namedSqlQuery(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 e82d66b09d..3b9f07763b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/PropertyContainer.java @@ -26,6 +26,7 @@ package org.hibernate.cfg; +import static org.jboss.logging.Logger.Level.WARN; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -37,10 +38,6 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Transient; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.MappingException; import org.hibernate.annotations.ManyToAny; @@ -49,6 +46,10 @@ 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. @@ -57,7 +58,12 @@ import org.hibernate.util.StringHelper; */ class PropertyContainer { - private static final Logger log = LoggerFactory.getLogger( AnnotationBinder.class ); + static { + System.setProperty("jboss.i18n.generate-proxies", "true"); + } + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PropertyContainer.class.getPackage().getName()); private final AccessType explicitClassDefinedAccessType; @@ -149,12 +155,8 @@ class PropertyContainer { // the access type for this property is explicitly set to AccessType.FIELD, hence we have to // use field access for this property even if the default access type for the class is AccessType.PROPERTY AccessType accessType = AccessType.getAccessStrategy( access.value() ); - if ( accessType == AccessType.FIELD ) { - propertyAccessMap.put( property.getName(), property ); - } - else { // AccessType.PROPERTY - log.warn( "Placing @Access(AccessType.PROPERTY) on a field does not have any effect." ); - } + if (accessType == AccessType.FIELD) propertyAccessMap.put(property.getName(), property); + else LOG.annotationHasNoEffect(AccessType.FIELD); } for ( XProperty property : propertyAccessMap.values() ) { @@ -168,12 +170,8 @@ class PropertyContainer { // see "2.3.2 Explicit Access Type" of JPA 2 spec // the access type for this property is explicitly set to AccessType.PROPERTY, hence we have to // return use method access even if the default class access type is AccessType.FIELD - if ( accessType == AccessType.PROPERTY ) { - fieldAccessMap.put( property.getName(), property ); - } - else { // AccessType.FIELD - log.warn( "Placing @Access(AccessType.FIELD) on a property does not have any effect." ); - } + if (accessType == AccessType.PROPERTY) fieldAccessMap.put(property.getName(), property); + else LOG.annotationHasNoEffect(AccessType.PROPERTY); } } @@ -280,6 +278,17 @@ 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 ca2a34f396..c8b97dfacc 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java @@ -23,22 +23,22 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.ConnectionReleaseMode; import org.hibernate.EntityMode; import org.hibernate.HibernateException; -import org.hibernate.engine.jdbc.JdbcSupport; import org.hibernate.bytecode.BytecodeProvider; import org.hibernate.cache.QueryCacheFactory; import org.hibernate.cache.RegionFactory; import org.hibernate.cache.impl.NoCachingRegionFactory; import org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge; +import org.hibernate.engine.jdbc.JdbcSupport; import org.hibernate.engine.jdbc.batch.internal.BatchBuilder; import org.hibernate.engine.jdbc.spi.ExtractedDatabaseMetaData; import org.hibernate.engine.jdbc.spi.JdbcServices; @@ -51,6 +51,10 @@ 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. @@ -58,8 +62,11 @@ import org.hibernate.util.StringHelper; * @author Gavin King */ public class SettingsFactory implements Serializable { - private static final Logger log = LoggerFactory.getLogger( SettingsFactory.class ); - private static final long serialVersionUID = -1194386144994524825L; + + private static final long serialVersionUID = -1194386144994524825L; + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SettingsFactory.class.getPackage().getName()); public static final String DEF_CACHE_REG_FACTORY = NoCachingRegionFactory.class.getName(); @@ -96,42 +103,42 @@ public class SettingsFactory implements Serializable { settings.setTransactionManagerLookup( createTransactionManagerLookup(properties) ); boolean flushBeforeCompletion = ConfigurationHelper.getBoolean(Environment.FLUSH_BEFORE_COMPLETION, properties); - log.info("Automatic flush during beforeCompletion(): " + enabledDisabled(flushBeforeCompletion) ); + LOG.autoFlush(enabledDisabled(flushBeforeCompletion)); settings.setFlushBeforeCompletionEnabled(flushBeforeCompletion); boolean autoCloseSession = ConfigurationHelper.getBoolean(Environment.AUTO_CLOSE_SESSION, properties); - log.info("Automatic session close at end of transaction: " + enabledDisabled(autoCloseSession) ); + LOG.autoSessionClose(enabledDisabled(autoCloseSession)); settings.setAutoCloseSessionEnabled(autoCloseSession); //JDBC and connection settings: int batchSize = ConfigurationHelper.getInt(Environment.STATEMENT_BATCH_SIZE, properties, 0); if ( !meta.supportsBatchUpdates() ) batchSize = 0; - if (batchSize>0) log.info("JDBC batch size: " + batchSize); + if (batchSize>0) LOG.jdbcBatchSize(batchSize); settings.setJdbcBatchSize(batchSize); boolean jdbcBatchVersionedData = ConfigurationHelper.getBoolean(Environment.BATCH_VERSIONED_DATA, properties, false); - if (batchSize>0) log.info("JDBC batch updates for versioned data: " + enabledDisabled(jdbcBatchVersionedData) ); + if (batchSize > 0) LOG.jdbcBatchUpdates(enabledDisabled(jdbcBatchVersionedData)); settings.setJdbcBatchVersionedData(jdbcBatchVersionedData); settings.setBatcherBuilder( createBatchBuilder(properties, batchSize) ); boolean useScrollableResultSets = ConfigurationHelper.getBoolean(Environment.USE_SCROLLABLE_RESULTSET, properties, meta.supportsScrollableResults()); - log.info("Scrollable result sets: " + enabledDisabled(useScrollableResultSets) ); + LOG.scrollabelResultSets(enabledDisabled(useScrollableResultSets)); settings.setScrollableResultSetsEnabled(useScrollableResultSets); boolean wrapResultSets = ConfigurationHelper.getBoolean(Environment.WRAP_RESULT_SETS, properties, false); - log.debug( "Wrap result sets: " + enabledDisabled(wrapResultSets) ); + LOG.wrapResultSets(enabledDisabled(wrapResultSets)); settings.setWrapResultSetsEnabled(wrapResultSets); boolean useGetGeneratedKeys = ConfigurationHelper.getBoolean(Environment.USE_GET_GENERATED_KEYS, properties, meta.supportsGetGeneratedKeys()); - log.info("JDBC3 getGeneratedKeys(): " + enabledDisabled(useGetGeneratedKeys) ); + LOG.jdbc3GeneratedKeys(enabledDisabled(useGetGeneratedKeys)); settings.setGetGeneratedKeysEnabled(useGetGeneratedKeys); Integer statementFetchSize = ConfigurationHelper.getInteger(Environment.STATEMENT_FETCH_SIZE, properties); - if (statementFetchSize!=null) log.info("JDBC result set fetch size: " + statementFetchSize); + if (statementFetchSize != null) LOG.jdbcResultSetFetchSize(statementFetchSize); settings.setJdbcFetchSize(statementFetchSize); String releaseModeName = ConfigurationHelper.getString( Environment.RELEASE_CONNECTIONS, properties, "auto" ); - log.info( "Connection release mode: " + releaseModeName ); + LOG.connectionReleaseMode(releaseModeName); ConnectionReleaseMode releaseMode; if ( "auto".equals(releaseModeName) ) { releaseMode = transactionFactory.getDefaultReleaseMode(); @@ -139,8 +146,8 @@ public class SettingsFactory implements Serializable { else { releaseMode = ConnectionReleaseMode.parse( releaseModeName ); if ( releaseMode == ConnectionReleaseMode.AFTER_STATEMENT && - ! jdbcServices.getConnectionProvider().supportsAggressiveRelease() ) { - log.warn( "Overriding release mode as connection provider does not support 'after_statement'" ); + ! jdbcServices.getConnectionProvider().supportsAggressiveRelease() ) { + LOG.unsupportedAfterStatement(); releaseMode = ConnectionReleaseMode.AFTER_TRANSACTION; } } @@ -150,50 +157,50 @@ public class SettingsFactory implements Serializable { String defaultSchema = properties.getProperty(Environment.DEFAULT_SCHEMA); String defaultCatalog = properties.getProperty(Environment.DEFAULT_CATALOG); - if (defaultSchema!=null) log.info("Default schema: " + defaultSchema); - if (defaultCatalog!=null) log.info("Default catalog: " + defaultCatalog); + if (defaultSchema != null) LOG.defaultSchema(defaultSchema); + if (defaultCatalog != null) LOG.defaultCatalog(defaultCatalog); settings.setDefaultSchemaName(defaultSchema); settings.setDefaultCatalogName(defaultCatalog); Integer maxFetchDepth = ConfigurationHelper.getInteger(Environment.MAX_FETCH_DEPTH, properties); - if (maxFetchDepth!=null) log.info("Maximum outer join fetch depth: " + maxFetchDepth); + if (maxFetchDepth != null) LOG.maxOuterJoinFetchDepth(maxFetchDepth); settings.setMaximumFetchDepth(maxFetchDepth); int batchFetchSize = ConfigurationHelper.getInt(Environment.DEFAULT_BATCH_FETCH_SIZE, properties, 1); - log.info("Default batch fetch size: " + batchFetchSize); + LOG.defaultBatchFetchSize(batchFetchSize); settings.setDefaultBatchFetchSize(batchFetchSize); boolean comments = ConfigurationHelper.getBoolean(Environment.USE_SQL_COMMENTS, properties); - log.info( "Generate SQL with comments: " + enabledDisabled(comments) ); + LOG.generateSqlWithComments(enabledDisabled(comments)); settings.setCommentsEnabled(comments); boolean orderUpdates = ConfigurationHelper.getBoolean(Environment.ORDER_UPDATES, properties); - log.info( "Order SQL updates by primary key: " + enabledDisabled(orderUpdates) ); + LOG.orderSqlUpdatesByPrimaryKey(enabledDisabled(orderUpdates)); settings.setOrderUpdatesEnabled(orderUpdates); boolean orderInserts = ConfigurationHelper.getBoolean(Environment.ORDER_INSERTS, properties); - log.info( "Order SQL inserts for batching: " + enabledDisabled( orderInserts ) ); + LOG.orderSqlInsertsForBatching(enabledDisabled(orderInserts)); settings.setOrderInsertsEnabled( orderInserts ); //Query parser settings: settings.setQueryTranslatorFactory( createQueryTranslatorFactory(properties) ); - Map querySubstitutions = ConfigurationHelper.toMap(Environment.QUERY_SUBSTITUTIONS, " ,=;:\n\t\r\f", properties); - log.info("Query language substitutions: " + querySubstitutions); + Map querySubstitutions = ConfigurationHelper.toMap(Environment.QUERY_SUBSTITUTIONS, " ,=;:\n\t\r\f", properties); + LOG.queryLanguageSubstitutions(querySubstitutions); settings.setQuerySubstitutions(querySubstitutions); boolean jpaqlCompliance = ConfigurationHelper.getBoolean( Environment.JPAQL_STRICT_COMPLIANCE, properties, false ); settings.setStrictJPAQLCompliance( jpaqlCompliance ); - log.info( "JPA-QL strict compliance: " + enabledDisabled( jpaqlCompliance ) ); + LOG.jpaQlStrictCompliance(enabledDisabled(jpaqlCompliance)); // Second-level / query cache: boolean useSecondLevelCache = ConfigurationHelper.getBoolean(Environment.USE_SECOND_LEVEL_CACHE, properties, true); - log.info( "Second-level cache: " + enabledDisabled(useSecondLevelCache) ); + LOG.secondLevelCache(enabledDisabled(useSecondLevelCache)); settings.setSecondLevelCacheEnabled(useSecondLevelCache); boolean useQueryCache = ConfigurationHelper.getBoolean(Environment.USE_QUERY_CACHE, properties); - log.info( "Query cache: " + enabledDisabled(useQueryCache) ); + LOG.queryCache(enabledDisabled(useQueryCache)); settings.setQueryCacheEnabled(useQueryCache); // The cache provider is needed when we either have second-level cache enabled @@ -203,16 +210,16 @@ public class SettingsFactory implements Serializable { boolean useMinimalPuts = ConfigurationHelper.getBoolean( Environment.USE_MINIMAL_PUTS, properties, settings.getRegionFactory().isMinimalPutsEnabledByDefault() ); - log.info( "Optimize cache for minimal puts: " + enabledDisabled(useMinimalPuts) ); + LOG.optimizeCacheForMinimalInputs(enabledDisabled(useMinimalPuts)); settings.setMinimalPutsEnabled(useMinimalPuts); String prefix = properties.getProperty(Environment.CACHE_REGION_PREFIX); if ( StringHelper.isEmpty(prefix) ) prefix=null; - if (prefix!=null) log.info("Cache region prefix: "+ prefix); + if (prefix != null) LOG.cacheRegionPrefix(prefix); settings.setCacheRegionPrefix(prefix); boolean useStructuredCacheEntries = ConfigurationHelper.getBoolean(Environment.USE_STRUCTURED_CACHE, properties, false); - log.info( "Structured second-level cache entries: " + enabledDisabled(useStructuredCacheEntries) ); + LOG.structuredSecondLevelCacheEntries(enabledDisabled(useStructuredCacheEntries)); settings.setStructuredCacheEntriesEnabled(useStructuredCacheEntries); if (useQueryCache) settings.setQueryCacheFactory( createQueryCacheFactory(properties) ); @@ -220,7 +227,7 @@ public class SettingsFactory implements Serializable { //Statistics and logging: boolean showSql = ConfigurationHelper.getBoolean(Environment.SHOW_SQL, properties); - if (showSql) log.info("Echoing all SQL to stdout"); + if (showSql) LOG.echoingSql(); // settings.setShowSqlEnabled(showSql); boolean formatSql = ConfigurationHelper.getBoolean(Environment.FORMAT_SQL, properties); @@ -229,11 +236,11 @@ public class SettingsFactory implements Serializable { settings.setSqlStatementLogger( new SQLStatementLogger( showSql, formatSql ) ); boolean useStatistics = ConfigurationHelper.getBoolean(Environment.GENERATE_STATISTICS, properties); - log.info( "Statistics: " + enabledDisabled(useStatistics) ); + LOG.statistics( enabledDisabled(useStatistics) ); settings.setStatisticsEnabled(useStatistics); boolean useIdentifierRollback = ConfigurationHelper.getBoolean(Environment.USE_IDENTIFIER_ROLLBACK, properties); - log.info( "Deleted entity synthetic identifier rollback: " + enabledDisabled(useIdentifierRollback) ); + LOG.deletedEntitySyntheticIdentifierRollback(enabledDisabled(useIdentifierRollback)); settings.setIdentifierRollbackEnabled(useIdentifierRollback); //Schema export: @@ -249,15 +256,15 @@ public class SettingsFactory implements Serializable { settings.setImportFiles( properties.getProperty( Environment.HBM2DDL_IMPORT_FILES ) ); EntityMode defaultEntityMode = EntityMode.parse( properties.getProperty( Environment.DEFAULT_ENTITY_MODE ) ); - log.info( "Default entity-mode: " + defaultEntityMode ); + LOG.defaultEntityMode(defaultEntityMode); settings.setDefaultEntityMode( defaultEntityMode ); boolean namedQueryChecking = ConfigurationHelper.getBoolean( Environment.QUERY_STARTUP_CHECKING, properties, true ); - log.info( "Named query checking : " + enabledDisabled( namedQueryChecking ) ); + LOG.namedQueryChecking(enabledDisabled(namedQueryChecking)); settings.setNamedQueryStartupCheckingEnabled( namedQueryChecking ); boolean checkNullability = ConfigurationHelper.getBoolean(Environment.CHECK_NULLABILITY, properties, true); - log.info( "Check Nullability in Core (should be disabled when Bean Validation is on): " + enabledDisabled(checkNullability) ); + LOG.checkNullability(enabledDisabled(checkNullability)); settings.setCheckNullability(checkNullability); @@ -278,7 +285,7 @@ public class SettingsFactory implements Serializable { return new org.hibernate.bytecode.cglib.BytecodeProviderImpl(); } else { - log.debug( "using javassist as bytecode provider by default" ); + LOG.usingJavassist(); return new org.hibernate.bytecode.javassist.BytecodeProviderImpl(); } } @@ -291,7 +298,7 @@ public class SettingsFactory implements Serializable { String queryCacheFactoryClassName = ConfigurationHelper.getString( Environment.QUERY_CACHE_FACTORY, properties, "org.hibernate.cache.StandardQueryCacheFactory" ); - log.info("Query cache factory: " + queryCacheFactoryClassName); + LOG.queryCacheFactory(queryCacheFactoryClassName); try { return (QueryCacheFactory) ReflectHelper.classForName(queryCacheFactoryClassName).newInstance(); } @@ -312,7 +319,7 @@ public class SettingsFactory implements Serializable { if ( regionFactoryClassName == null ) { regionFactoryClassName = DEF_CACHE_REG_FACTORY; } - log.info( "Cache region factory : " + regionFactoryClassName ); + LOG.cacheRegionFactory(regionFactoryClassName); try { try { return (RegionFactory) ReflectHelper.classForName( regionFactoryClassName ) @@ -321,10 +328,7 @@ public class SettingsFactory implements Serializable { } catch ( NoSuchMethodException nsme ) { // no constructor accepting Properties found, try no arg constructor - log.debug( - regionFactoryClassName + " did not provide constructor accepting java.util.Properties; " + - "attempting no-arg constructor." - ); + LOG.constructorWithPropertiesNotFound(regionFactoryClassName); return (RegionFactory) ReflectHelper.classForName( regionFactoryClassName ).newInstance(); } } @@ -337,7 +341,7 @@ public class SettingsFactory implements Serializable { String className = ConfigurationHelper.getString( Environment.QUERY_TRANSLATOR, properties, "org.hibernate.hql.ast.ASTQueryTranslatorFactory" ); - log.info("Query translator: " + className); + LOG.queryTranslator(className); try { return (QueryTranslatorFactory) ReflectHelper.classForName(className).newInstance(); } @@ -355,7 +359,7 @@ public class SettingsFactory implements Serializable { : new BatchBuilder(); } else { - log.info("Batch factory: " + batchBuilderClass); + LOG.batcherFactory(batchBuilderClass); try { batchBuilder = (BatchBuilder) ReflectHelper.classForName(batchBuilderClass).newInstance(); } @@ -375,4 +379,192 @@ public class SettingsFactory implements Serializable { 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 c41a17f88d..87f627425d 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,6 +23,8 @@ */ 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; @@ -42,10 +44,6 @@ import javax.persistence.ManyToMany; import javax.persistence.MapKey; import javax.persistence.MapKeyColumn; import javax.persistence.OneToMany; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.FetchMode; import org.hibernate.MappingException; @@ -112,6 +110,10 @@ 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. @@ -121,7 +123,8 @@ import org.hibernate.util.StringHelper; */ @SuppressWarnings({"unchecked", "serial"}) public abstract class CollectionBinder { - private Logger log = LoggerFactory.getLogger( CollectionBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionBinder.class.getPackage().getName()); protected Collection collection; protected String propertyName; @@ -372,8 +375,9 @@ public abstract class CollectionBinder { public void bind() { this.collection = createCollection( propertyHolder.getPersistentClass() ); - log.debug( "Collection role: {}", StringHelper.qualify( propertyHolder.getPath(), propertyName ) ); - collection.setRole( StringHelper.qualify( propertyHolder.getPath(), propertyName ) ); + String role = StringHelper.qualify(propertyHolder.getPath(), propertyName); + LOG.collectionRole(role); + collection.setRole(role); collection.setNodeName( propertyName ); if ( (property.isAnnotationPresent( org.hibernate.annotations.MapKey.class ) @@ -624,7 +628,8 @@ public abstract class CollectionBinder { final TableBinder assocTableBinder, final Mappings mappings) { return new CollectionSecondPass( mappings, collection ) { - public void secondPass(java.util.Map persistentClasses, java.util.Map inheritedMetas) throws MappingException { + @Override + public void secondPass(java.util.Map persistentClasses, java.util.Map inheritedMetas) throws MappingException { bindStarToManySecondPass( persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings @@ -715,7 +720,7 @@ public abstract class CollectionBinder { String hqlOrderBy, Mappings mappings, Map inheritanceStatePerClass) { - log.debug("Binding a OneToMany: {}.{} through a foreign key", propertyHolder.getEntityName(), propertyName); + LOG.bindingOneToMany(propertyHolder.getEntityName(), propertyName); org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany( mappings, collection.getOwner() ); collection.setElement( oneToMany ); oneToMany.setReferencedEntityName( collectionType.getName() ); @@ -742,9 +747,7 @@ public abstract class CollectionBinder { column.setJoins( joins ); collection.setCollectionTable( column.getTable() ); } - log.info( - "Mapping collection: " + collection.getRole() + " -> " + collection.getCollectionTable().getName() - ); + LOG.mappingCollection(collection.getRole(), collection.getCollectionTable().getName()); bindFilters( false ); bindCollectionSecondPass( collection, null, fkJoinColumns, cascadeDeleteEnabled, property, mappings ); if ( !collection.isInverse() @@ -972,7 +975,7 @@ public abstract class CollectionBinder { //TODO check whether @ManyToOne @JoinTable in @IdClass used for @OrderBy works: doh! table = ""; } - + else if (pc == associatedClass || (associatedClass instanceof SingleTableSubclass && pc .getMappedClass().isAssignableFrom( @@ -981,7 +984,7 @@ public abstract class CollectionBinder { } else { table = pc.getTable().getQuotedName() + "."; } - + Iterator propertyColumns = p.getColumnIterator(); while ( propertyColumns.hasNext() ) { Selectable column = (Selectable) propertyColumns.next(); @@ -1146,20 +1149,12 @@ public abstract class CollectionBinder { PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() ); boolean isCollectionOfEntities = collectionEntity != null; ManyToAny anyAnn = property.getAnnotation( ManyToAny.class ); - if ( log.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName(); - if ( isCollectionOfEntities && unique ) { - log.debug( "Binding a OneToMany: {} through an association table", path ); - } - 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 ); - } + if (isCollectionOfEntities && unique) LOG.bindingOneToMany(path); + else if (isCollectionOfEntities) LOG.bindingManyToMany(path); + else if (anyAnn != null) LOG.bindingManyToAny(path); + else LOG.bindingCollection(path); } //check for user error if ( !isCollectionOfEntities ) { @@ -1273,7 +1268,7 @@ public abstract class CollectionBinder { element.setFetchMode( FetchMode.JOIN ); element.setLazy( false ); element.setIgnoreNotFound( ignoreNotFound ); - // as per 11.1.38 of JPA-2 spec, default to primary key if no column is specified by @OrderBy. + // as per 11.1.38 of JPA-2 spec, default to primary key if no column is specified by @OrderBy. if ( hqlOrderBy != null ) { collValue.setManyToManyOrdering( buildOrderByClauseFromHql( hqlOrderBy, collectionEntity, collValue.getRole() ) @@ -1546,4 +1541,41 @@ 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 1f73de8b40..568d4acdee 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,6 +23,9 @@ */ 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; @@ -34,7 +37,6 @@ import javax.persistence.JoinTable; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.SecondaryTables; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; @@ -67,10 +69,10 @@ import org.hibernate.cfg.BinderHelper; import org.hibernate.cfg.Ejb3JoinColumn; import org.hibernate.cfg.InheritanceState; import org.hibernate.cfg.Mappings; -import org.hibernate.cfg.PropertyHolder; -import org.hibernate.cfg.ObjectNameSource; import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.ObjectNameNormalizer; +import org.hibernate.cfg.ObjectNameSource; +import org.hibernate.cfg.PropertyHolder; import org.hibernate.cfg.UniqueConstraintHolder; import org.hibernate.engine.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.FilterDefinition; @@ -85,9 +87,10 @@ import org.hibernate.mapping.TableOwner; import org.hibernate.mapping.Value; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -95,11 +98,13 @@ import org.slf4j.LoggerFactory; * @author Emmanuel Bernard */ public class EntityBinder { + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + EntityBinder.class.getPackage().getName()); + private String name; private XClass annotatedClass; private PersistentClass persistentClass; private Mappings mappings; - private Logger log = LoggerFactory.getLogger( EntityBinder.class ); private String discriminatorValue = ""; private Boolean forceDiscriminator; private Boolean insertableDiscriminator; @@ -124,8 +129,8 @@ public class EntityBinder { private AccessType propertyAccessType = AccessType.DEFAULT; private boolean wrapIdsInEmbeddedComponents; private String subselect; - - + + public boolean wrapIdsInEmbeddedComponents() { return wrapIdsInEmbeddedComponents; } @@ -237,14 +242,8 @@ public class EntityBinder { } } else { - if ( explicitHibernateEntityAnnotation ) { - log.warn( "@org.hibernate.annotations.Entity used on a non root entity: ignored for {}", - annotatedClass.getName() ); - } - if ( annotatedClass.isAnnotationPresent( Immutable.class ) ) { - log.warn( "@Immutable used on a non root entity: ignored for {}", - annotatedClass.getName() ); - } + if (explicitHibernateEntityAnnotation) LOG.entityAnnotationOnNonRoot(annotatedClass.getName()); + if (annotatedClass.isAnnotationPresent(Immutable.class)) LOG.immutableAnnotationOnNonRoot(annotatedClass.getName()); } persistentClass.setOptimisticLockMode( getVersioning( optimisticLockType ) ); persistentClass.setSelectBeforeUpdate( selectBeforeUpdate ); @@ -277,7 +276,7 @@ public class EntityBinder { SQLDelete sqlDelete = annotatedClass.getAnnotation( SQLDelete.class ); SQLDeleteAll sqlDeleteAll = annotatedClass.getAnnotation( SQLDeleteAll.class ); Loader loader = annotatedClass.getAnnotation( Loader.class ); - + if ( sqlInsert != null ) { persistentClass.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(), ExecuteUpdateResultCheckStyle.parse( sqlInsert.check().toString().toLowerCase() ) @@ -305,18 +304,18 @@ public class EntityBinder { if ( annotatedClass.isAnnotationPresent( Synchronize.class )) { Synchronize synchronizedWith = annotatedClass.getAnnotation(Synchronize.class); - + String [] tables = synchronizedWith.value(); for (String table : tables) { persistentClass.addSynchronizedTable(table); } } - + if ( annotatedClass.isAnnotationPresent(Subselect.class )) { Subselect subselect = annotatedClass.getAnnotation(Subselect.class); this.subselect = subselect.value(); - } - + } + //tuplizers if ( annotatedClass.isAnnotationPresent( Tuplizers.class ) ) { for (Tuplizer tuplizer : annotatedClass.getAnnotation( Tuplizers.class ).value()) { @@ -345,13 +344,8 @@ public class EntityBinder { } persistentClass.addFilter( filterName, cond ); } - } - else { - if ( filters.size() > 0 ) { - log.warn( "@Filter not allowed on subclasses (ignored): {}", persistentClass.getEntityName() ); - } - } - log.debug( "Import with entity name {}", name ); + } else if (filters.size() > 0) LOG.filterAnnotationOnSubclass(persistentClass.getEntityName()); + LOG.importWithEntityName(name); try { mappings.addImport( persistentClass.getEntityName(), name ); String entityName = persistentClass.getEntityName(); @@ -517,7 +511,7 @@ public class EntityBinder { ); if ( persistentClass instanceof TableOwner ) { - log.info( "Bind entity {} on table {}", persistentClass.getEntityName(), table.getName() ); + LOG.bindEntityOnTable(persistentClass.getEntityName(), table.getName()); ( (TableOwner) persistentClass ).setTable( table ); } else { @@ -747,9 +741,7 @@ public class EntityBinder { //somehow keep joins() for later. //Has to do the work later because it needs persistentClass id! - log.info( - "Adding secondary table to entity {} -> {}", persistentClass.getEntityName(), join.getTable().getName() - ); + LOG.addingSecondaryTableToEntity(persistentClass.getEntityName(), join.getTable().getName()); org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join ); if ( matchingTable != null ) { join.setSequentialSelect( FetchMode.JOIN != matchingTable.fetch() ); @@ -930,4 +922,37 @@ 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 c88a8ce96f..3a87e544cf 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,11 +23,8 @@ */ package org.hibernate.cfg.annotations; +import static org.jboss.logging.Logger.Level.WARN; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.MappingException; import org.hibernate.annotations.OrderBy; @@ -48,6 +45,10 @@ 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 @@ -57,21 +58,25 @@ import org.hibernate.util.StringHelper; */ @SuppressWarnings({"unchecked", "serial"}) public class ListBinder extends CollectionBinder { - private Logger log = LoggerFactory.getLogger( ListBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ListBinder.class.getPackage().getName()); public ListBinder() { } - protected Collection createCollection(PersistentClass persistentClass) { + @Override + protected Collection createCollection(PersistentClass persistentClass) { return new org.hibernate.mapping.List( getMappings(), persistentClass ); } - public void setSqlOrderBy(OrderBy orderByAnn) { - if ( orderByAnn != null ) log.warn( "@OrderBy not allowed for a indexed collection, annotation ignored." ); + @Override + public void setSqlOrderBy(OrderBy orderByAnn) { + if (orderByAnn != null) LOG.orderByAnnotationIndexedCollection(); } - public void setSort(Sort sortAnn) { - if ( sortAnn != null ) log.warn( "@Sort not allowed for a indexed collection, annotation ignored." ); + @Override + public void setSort(Sort sortAnn) { + if (sortAnn != null) LOG.sortAnnotationIndexedCollection(); } @Override @@ -90,7 +95,8 @@ public class ListBinder extends CollectionBinder { final TableBinder assocTableBinder, final Mappings mappings) { return new CollectionSecondPass( mappings, ListBinder.this.collection ) { - public void secondPass(Map persistentClasses, Map inheritedMetas) + @Override + public void secondPass(Map persistentClasses, Map inheritedMetas) throws MappingException { bindStarToManySecondPass( persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, @@ -141,4 +147,19 @@ 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 662246eba3..c46975f806 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,13 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; @@ -55,12 +53,18 @@ 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 */ public class PropertyBinder { - private Logger log = LoggerFactory.getLogger( PropertyBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PropertyBinder.class.getPackage().getName()); + private String name; private String returnedClassName; private boolean lazy; @@ -172,7 +176,7 @@ public class PropertyBinder { private Property makePropertyAndValue() { validateBind(); - log.debug( "binding property {} with lazy={}", name, lazy ); + LOG.bindingPropertyWithLazy(name, lazy); String containerClassName = holder == null ? null : holder.getClassName(); @@ -252,7 +256,7 @@ public class PropertyBinder { //used when the value is provided and the binding is done elsewhere public Property makeProperty() { validateMake(); - log.debug( "Building property " + name ); + LOG.buildingProperty(name); Property prop = new Property(); prop.setName( name ); prop.setNodeName( name ); @@ -309,7 +313,7 @@ public class PropertyBinder { ); } } - log.trace( "Cascading " + name + " with " + cascade ); + LOG.cascadingProperty(name, cascade); this.mappingProperty = prop; return prop; } @@ -337,4 +341,25 @@ 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 f9ca0bcf40..f11e74a6e0 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,6 +23,7 @@ */ 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; @@ -31,7 +32,6 @@ import javax.persistence.NamedQuery; import javax.persistence.QueryHint; import javax.persistence.SqlResultSetMapping; import javax.persistence.SqlResultSetMappings; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.CacheMode; @@ -46,8 +46,10 @@ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Query binder @@ -55,7 +57,8 @@ import org.slf4j.LoggerFactory; * @author Emmanuel Bernard */ public abstract class QueryBinder { - private static final Logger log = LoggerFactory.getLogger( QueryBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryBinder.class.getPackage().getName()); public static void bindQuery(NamedQuery queryAnn, Mappings mappings, boolean isDefault) { if ( queryAnn == null ) return; @@ -83,7 +86,7 @@ public abstract class QueryBinder { else { mappings.addQuery( queryAnn.name(), query ); } - log.info( "Binding Named query: {} => {}", queryAnn.name(), queryAnn.query() ); + LOG.bindingNamedQuery(queryAnn.name(), queryAnn.query()); } @@ -145,7 +148,7 @@ public abstract class QueryBinder { else { mappings.addSQLQuery( queryAnn.name(), query ); } - log.info( "Binding named native query: {} => {}", queryAnn.name(), queryAnn.query() ); + LOG.bindingNamedNativeQuery(queryAnn.name(), queryAnn.query()); } public static void bindNativeQuery(org.hibernate.annotations.NamedNativeQuery queryAnn, Mappings mappings) { @@ -199,7 +202,7 @@ public abstract class QueryBinder { throw new NotYetImplementedException( "Pure native scalar queries are not yet supported" ); } mappings.addSQLQuery( queryAnn.name(), query ); - log.info( "Binding named native query: {} => {}", queryAnn.name(), queryAnn.query() ); + LOG.bindingNamedNativeQuery(queryAnn.name(), queryAnn.query()); } public static void bindQueries(NamedQueries queriesAnn, Mappings mappings, boolean isDefault) { @@ -248,7 +251,7 @@ public abstract class QueryBinder { ); mappings.addQuery( queryAnn.name(), query ); - if ( log.isInfoEnabled() ) log.info( "Binding named query: " + queryAnn.name() + " => " + queryAnn.query() ); + LOG.bindingNamedQuery(queryAnn.name(), queryAnn.query()); } private static FlushMode getFlushMode(FlushModeType flushModeType) { @@ -421,4 +424,21 @@ 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 a3da7f4210..49c0656371 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,6 +23,7 @@ */ 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; @@ -34,7 +35,6 @@ import javax.persistence.ColumnResult; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.SqlResultSetMapping; - import org.hibernate.LockMode; import org.hibernate.MappingException; import org.hibernate.cfg.BinderHelper; @@ -49,14 +49,18 @@ import org.hibernate.mapping.Property; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard */ public class ResultsetMappingSecondPass implements QuerySecondPass { - private Logger log = LoggerFactory.getLogger( ResultsetMappingSecondPass.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ResultsetMappingSecondPass.class.getPackage().getName()); + private SqlResultSetMapping ann; private Mappings mappings; private boolean isDefault; @@ -71,7 +75,7 @@ public class ResultsetMappingSecondPass implements QuerySecondPass { //TODO add parameters checkings if ( ann == null ) return; ResultSetMappingDefinition definition = new ResultSetMappingDefinition( ann.name() ); - log.info( "Binding resultset mapping: {}", definition.getName() ); + LOG.bindingResultSetMapping(definition.getName()); int entityAliasIndex = 0; @@ -265,4 +269,15 @@ 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 0f2e5af841..13e97b1419 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,12 +23,15 @@ */ package org.hibernate.cfg.annotations; +import static org.jboss.logging.Logger.Level.WARN; import org.hibernate.annotations.OrderBy; import org.hibernate.cfg.Environment; import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Bind a set. @@ -36,7 +39,8 @@ import org.slf4j.LoggerFactory; * @author Matthew Inger */ public class SetBinder extends CollectionBinder { - private final Logger log = LoggerFactory.getLogger( SetBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SetBinder.class.getPackage().getName()); public SetBinder() { } @@ -45,19 +49,28 @@ public class SetBinder extends CollectionBinder { super( sorted ); } - protected Collection createCollection(PersistentClass persistentClass) { + @Override + protected Collection createCollection(PersistentClass persistentClass) { return new org.hibernate.mapping.Set( getMappings(), persistentClass ); } - public void setSqlOrderBy(OrderBy orderByAnn) { + @Override + public void setSqlOrderBy(OrderBy orderByAnn) { // *annotation* binder, jdk 1.5, ... am i missing something? if ( orderByAnn != null ) { - if ( Environment.jvmSupportsLinkedHashCollections() ) { - super.setSqlOrderBy( orderByAnn ); - } - else { - log.warn( "Attribute \"order-by\" ignored in JDK1.3 or less" ); - } + if (Environment.jvmSupportsLinkedHashCollections()) super.setSqlOrderBy(orderByAnn); + 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 801f2a4cef..96d426ce36 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,6 +23,7 @@ */ 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; @@ -34,10 +35,6 @@ import javax.persistence.MapKeyEnumerated; import javax.persistence.MapKeyTemporal; import javax.persistence.Temporal; import javax.persistence.TemporalType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.Hibernate; @@ -60,12 +57,18 @@ 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 */ public class SimpleValueBinder { - private Logger log = LoggerFactory.getLogger( SimpleValueBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SimpleValueBinder.class.getPackage().getName()); + private String propertyName; private String returnedClassName; private Ejb3Column[] columns; @@ -300,7 +303,7 @@ public class SimpleValueBinder { public SimpleValue make() { validate(); - log.debug( "building SimpleValue for {}", propertyName ); + LOG.buildingSimpleValue(propertyName); if ( table == null ) { table = columns[0].getTable(); } @@ -338,7 +341,7 @@ public class SimpleValueBinder { public void fillSimpleValue() { - log.debug( "Setting SimpleValue typeName for {}", propertyName ); + LOG.settingSimpleValueTypeName(propertyName); String type = BinderHelper.isEmptyAnnotationValue( explicitType ) ? returnedClassName : explicitType; org.hibernate.mapping.TypeDef typeDef = mappings.getTypeDef( type ); @@ -368,4 +371,19 @@ 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 cea596b795..5e4ab1c7a4 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,23 +23,21 @@ */ 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.annotations.Index; -import org.hibernate.cfg.Mappings; -import org.hibernate.util.StringHelper; -import org.hibernate.util.CollectionHelper; import org.hibernate.cfg.BinderHelper; import org.hibernate.cfg.Ejb3JoinColumn; import org.hibernate.cfg.IndexOrUniqueKeySecondPass; +import org.hibernate.cfg.Mappings; +import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.cfg.ObjectNameSource; -import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.UniqueConstraintHolder; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; @@ -51,8 +49,12 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -62,7 +64,9 @@ import org.slf4j.LoggerFactory; @SuppressWarnings("unchecked") public class TableBinder { //TODO move it to a getter/setter strategy - private static Logger log = LoggerFactory.getLogger( TableBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TableBinder.class.getPackage().getName()); + private String schema; private String catalog; private String name; @@ -147,7 +151,7 @@ public class TableBinder { // ownerEntity can be null when the table name is explicitly set final String ownerObjectName = isJPA2ElementCollection && ownerEntity != null ? StringHelper.unqualify( ownerEntity ) : unquotedOwnerTable; - final ObjectNameSource nameSource = buildNameContext( + final ObjectNameSource nameSource = buildNameContext( ownerObjectName, unquotedAssocTable ); @@ -201,7 +205,7 @@ public class TableBinder { return new AssociationTableNameSource( name, logicalName ); } - + public static Table buildAndFillTable( String schema, String catalog, @@ -228,7 +232,7 @@ public class TableBinder { catalog, realTableName, isAbstract, - subselect, + subselect, denormalizedSuperTable ); } @@ -237,7 +241,7 @@ public class TableBinder { schema, catalog, realTableName, - subselect, + subselect, isAbstract ); } @@ -271,7 +275,8 @@ public class TableBinder { * * @deprecated Use {@link #buildAndFillTable} instead. */ - @SuppressWarnings({ "JavaDoc" }) + @Deprecated + @SuppressWarnings({ "JavaDoc" }) public static Table fillTable( String schema, String catalog, @@ -338,7 +343,7 @@ public class TableBinder { * Get the columns of the mapped-by property * copy them and link the copy to the actual value */ - log.debug("Retrieving property {}.{}", associatedClass.getEntityName(), mappedByProperty); + LOG.retreivingProperty(associatedClass.getEntityName(), mappedByProperty); final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() ); Iterator mappedByColumns; @@ -445,7 +450,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.debug( "No column in the identifier!" ); + if (!idColItr.hasNext()) LOG.noColumnInIdentifier(); while ( idColItr.hasNext() ) { boolean match = false; //for each PK column, find the associated FK column. @@ -491,7 +496,7 @@ public class TableBinder { Ejb3JoinColumn[] columns, SimpleValue value) { for (Ejb3JoinColumn joinCol : columns) { - Column synthCol = (Column) columnIterator.next(); + Column synthCol = (Column) columnIterator.next(); if ( joinCol.isNameDeferred() ) { //this has to be the default value joinCol.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value ); @@ -524,7 +529,8 @@ public class TableBinder { /** * @deprecated Use {@link #buildUniqueConstraintHolders} instead */ - @SuppressWarnings({ "JavaDoc" }) + @Deprecated + @SuppressWarnings({ "JavaDoc" }) public static List buildUniqueConstraints(UniqueConstraint[] constraintsArray) { List result = new ArrayList(); if ( constraintsArray.length != 0 ) { @@ -572,4 +578,20 @@ 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 b1bba92c48..99a4c2d919 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,6 +24,7 @@ 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; @@ -115,12 +116,8 @@ import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; - import org.dom4j.Attribute; import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AnnotationException; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CollectionOfElements; @@ -132,6 +129,10 @@ 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. @@ -143,7 +144,8 @@ import org.hibernate.util.StringHelper; */ @SuppressWarnings("unchecked") public class JPAOverridenAnnotationReader implements AnnotationReader { - private Logger log = LoggerFactory.getLogger( JPAOverridenAnnotationReader.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JPAOverridenAnnotationReader.class.getPackage().getName()); private static final Map annotationToXml; private static final String SCHEMA_VALIDATION = "Activate schema validation for more information"; private static final Filter FILTER = new Filter() { @@ -441,13 +443,7 @@ public class JPAOverridenAnnotationReader implements AnnotationReader { } for ( Element subelement : (List) element.elements() ) { String propertyName = subelement.attributeValue( "name" ); - if ( !properties.contains( propertyName ) ) { - log.warn( - "Property {} not found in class" - + " but described in (possible typo error)", - StringHelper.qualify( className, propertyName ) - ); - } + if (!properties.contains(propertyName)) LOG.propertyNotFound(StringHelper.qualify(className, propertyName)); } } } @@ -2508,4 +2504,15 @@ 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 5e0d809403..3bc571d7e4 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,28 +26,30 @@ 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; import java.util.List; import java.util.Map; - import javax.persistence.AccessType; - import org.dom4j.Document; import org.dom4j.Element; - import org.hibernate.AnnotationException; import org.hibernate.util.StringHelper; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * @author Emmanuel Bernard */ public class XMLContext implements Serializable { - private Logger log = LoggerFactory.getLogger( XMLContext.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + XMLContext.class.getPackage().getName()); private Default globalDefaults; private Map classOverriding = new HashMap(); private Map defaultsOverriding = new HashMap(); @@ -90,7 +92,7 @@ public class XMLContext implements Serializable { } } else { - log.warn( "Found more than one , subsequent ignored" ); + LOG.duplicateMetadata(); } } @@ -107,13 +109,13 @@ public class XMLContext implements Serializable { setAccess( unitElement, entityMappingDefault ); defaultElements.add( root ); - List entities = (List) root.elements( "entity" ); + List entities = root.elements( "entity" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); - entities = (List) root.elements( "mapped-superclass" ); + entities = root.elements( "mapped-superclass" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); - entities = (List) root.elements( "embeddable" ); + entities = root.elements( "embeddable" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); return addedClasses; } @@ -157,7 +159,7 @@ public class XMLContext implements Serializable { setAccess( access, localDefault ); defaultsOverriding.put( className, localDefault ); - log.debug( "Adding XML overriding information for {}", className ); + LOG.addingOverridingInformation(className); addEntityListenerClasses( element, packageName, addedClasses ); } } @@ -167,16 +169,13 @@ public class XMLContext implements Serializable { Element listeners = element.element( "entity-listeners" ); if ( listeners != null ) { @SuppressWarnings( "unchecked" ) - List elements = (List) listeners.elements( "entity-listener" ); + List elements = listeners.elements( "entity-listener" ); for (Element listener : elements) { String listenerClassName = buildSafeClassName( listener.attributeValue( "class" ), packageName ); if ( classOverriding.containsKey( listenerClassName ) ) { //maybe switch it to warn? if ( "entity-listener".equals( classOverriding.get( listenerClassName ).getName() ) ) { - log.info( - "entity-listener duplication, first event definition will be used: {}", - listenerClassName - ); + LOG.duplicateListener(listenerClassName); continue; } else { @@ -187,7 +186,7 @@ public class XMLContext implements Serializable { classOverriding.put( listenerClassName, listener ); } } - log.debug( "Adding XML overriding information for listener: {}", localAddedClasses ); + LOG.addingListenerOverridingInformation(localAddedClasses); addedClasses.addAll( localAddedClasses ); return localAddedClasses; } @@ -313,4 +312,27 @@ 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 8b20eb9931..0e1ec5459d 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,6 +23,7 @@ */ 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; @@ -33,10 +34,6 @@ import javax.validation.TraversableResolver; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; import org.hibernate.cfg.Configuration; import org.hibernate.engine.SessionFactoryImplementor; @@ -48,6 +45,10 @@ 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. @@ -59,7 +60,9 @@ import org.hibernate.persister.entity.EntityPersister; public class BeanValidationEventListener implements PreInsertEventListener, PreUpdateEventListener, PreDeleteEventListener, Initializable { - private static final Logger log = LoggerFactory.getLogger( BeanValidationEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BeanValidationEventListener.class.getPackage().getName()); + private ValidatorFactory factory; private ConcurrentHashMap> associationsPerEntityPersister = new ConcurrentHashMap>(); @@ -139,9 +142,7 @@ public class BeanValidationEventListener implements new HashSet>( constraintViolations.size() ); Set classNames = new HashSet(); for ( ConstraintViolation violation : constraintViolations ) { - if ( log.isTraceEnabled() ) { - log.trace( violation.toString() ); - } + LOG.violation(violation); propagatedViolations.add( violation ); classNames.add( violation.getLeafBean().getClass().getName() ); } @@ -173,4 +174,15 @@ 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 336af8ad28..e487330c9c 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,6 +23,7 @@ */ 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; @@ -42,10 +43,6 @@ import javax.validation.constraints.Size; import javax.validation.metadata.BeanDescriptor; import javax.validation.metadata.ConstraintDescriptor; import javax.validation.metadata.PropertyDescriptor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.MappingException; @@ -60,6 +57,10 @@ 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 @@ -67,7 +68,8 @@ import org.hibernate.util.StringHelper; */ class TypeSafeActivator { - private static final Logger logger = LoggerFactory.getLogger( TypeSafeActivator.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TypeSafeActivator.class.getPackage().getName()); private static final String FACTORY_PROPERTY = "javax.persistence.validation.factory"; @@ -127,8 +129,8 @@ class TypeSafeActivator { try { applyDDL( "", persistentClass, clazz, factory, groups, true ); } - catch ( Exception e ) { - logger.warn( "Unable to apply constraints on DDL for " + className, e ); + catch (Exception e) { + LOG.unableToApplyConstraints(className, e.getMessage()); } } } @@ -245,8 +247,8 @@ class TypeSafeActivator { if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) { //single table should not be forced to null if ( !property.isComposite() ) { //composite should not add not-null on all columns - @SuppressWarnings("unchecked") - Iterator iter = (Iterator) property.getColumnIterator(); + @SuppressWarnings( "unchecked" ) + Iterator iter = property.getColumnIterator(); while ( iter.hasNext() ) { iter.next().setNullable( false ); hasNotNull = true; @@ -386,4 +388,15 @@ 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 71f26ccfb7..077a8e74b8 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,8 +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.event.EventListeners; import org.hibernate.event.PostCollectionRecreateEventListener; @@ -34,20 +35,23 @@ import org.hibernate.event.PostDeleteEventListener; import org.hibernate.event.PostInsertEventListener; import org.hibernate.event.PostUpdateEventListener; import org.hibernate.util.ReflectHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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. - * + * * @deprecated as of release 3.4.0.CR2, replaced by Hibernate Search's {@link org.hibernate.search.cfg.EventListenerRegister} * @author Emmanuel Bernard * @author Hardy Ferentschik */ -@Deprecated +@Deprecated public class HibernateSearchEventListenerRegister { - private static final Logger log = LoggerFactory.getLogger(HibernateSearchEventListenerRegister.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HibernateSearchEventListenerRegister.class.getPackage().getName()); /** * Class name of the class needed to enable Search. @@ -58,27 +62,26 @@ public class HibernateSearchEventListenerRegister { * @deprecated as of release 3.4.0.CR2, replaced by Hibernate Search's {@link org.hibernate.search.cfg.EventListenerRegister#enableHibernateSearch(EventListeners, Properties)} */ @SuppressWarnings("unchecked") - @Deprecated + @Deprecated public static void enableHibernateSearch(EventListeners eventListeners, Properties properties) { // check whether search is explicitly enabled - if so there is nothing // to do String enableSearchListeners = properties.getProperty( "hibernate.search.autoregister_listeners" ); if("false".equalsIgnoreCase(enableSearchListeners )) { - log.info("Property hibernate.search.autoregister_listeners is set to false." + - " No attempt will be made to register Hibernate Search event listeners."); + LOG.willNotRegisterListeners(); return; } - + // add search events if the jar is available and class can be loaded Class searchEventListenerClass = attemptToLoadSearchEventListener(); if ( searchEventListenerClass == null ) { - log.info("Unable to find {} on the classpath. Hibernate Search is not enabled.", FULL_TEXT_INDEX_EVENT_LISTENER_CLASS); + LOG.unableToFindListenerClass(FULL_TEXT_INDEX_EVENT_LISTENER_CLASS); return; } - + Object searchEventListener = instantiateEventListener(searchEventListenerClass); - - //TODO Generalize this. Pretty much the same code all the time. Reflecetion? + + // TODO Generalize this. Pretty much the same code all the time. Reflection? { boolean present = false; PostInsertEventListener[] listeners = eventListeners @@ -147,7 +150,7 @@ public class HibernateSearchEventListenerRegister { eventListeners .setPostDeleteEventListeners(new PostDeleteEventListener[] { (PostDeleteEventListener) searchEventListener }); } - } + } { boolean present = false; PostCollectionRecreateEventListener[] listeners = eventListeners.getPostCollectionRecreateEventListeners(); @@ -213,12 +216,12 @@ public class HibernateSearchEventListenerRegister { new PostCollectionUpdateEventListener[] { (PostCollectionUpdateEventListener) searchEventListener } ); } - } + } } /** * Tries to load Hibernate Search event listener. - * + * * @return An event listener instance in case the jar was available. */ private static Class attemptToLoadSearchEventListener() { @@ -228,7 +231,7 @@ public class HibernateSearchEventListenerRegister { FULL_TEXT_INDEX_EVENT_LISTENER_CLASS, HibernateSearchEventListenerRegister.class); } catch (ClassNotFoundException e) { - log.debug("Search not present in classpath, ignoring event listener registration."); + LOG.unableToFindListenerClass(); } return searchEventListenerClass; } @@ -243,4 +246,23 @@ 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 87d97fb77d..e4e4c95cf1 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/PersistentArrayHolder.java @@ -24,6 +24,7 @@ */ 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; @@ -31,15 +32,16 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.EntityMode; import org.hibernate.HibernateException; -import org.hibernate.loader.CollectionAliases; 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 @@ -51,7 +53,8 @@ import org.hibernate.type.Type; public class PersistentArrayHolder extends AbstractPersistentCollection { protected Object array; - private static final Logger log = LoggerFactory.getLogger(PersistentArrayHolder.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PersistentArrayHolder.class.getPackage().getName()); //just to help out during the load (ugly, i know) private transient Class elementClass; @@ -73,7 +76,7 @@ public class PersistentArrayHolder extends AbstractPersistentCollection { Array.set( result, i, persister.getElementType().deepCopy(elt, entityMode, persister.getFactory()) ); } catch (IllegalArgumentException iae) { - log.error("Array element type error", iae); + LOG.invalidArrayElementType(iae.getMessage()); throw new HibernateException( "Array element type error", iae ); } } @@ -84,7 +87,8 @@ public class PersistentArrayHolder extends AbstractPersistentCollection { return Array.getLength( snapshot ) == 0; } - public Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException { + @Override + public Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException { Object[] sn = (Object[]) snapshot; Object[] arr = (Object[]) array; ArrayList result = new ArrayList(); @@ -126,7 +130,8 @@ public class PersistentArrayHolder extends AbstractPersistentCollection { } return list.iterator(); } - public boolean empty() { + @Override + public boolean empty() { return false; } @@ -146,11 +151,13 @@ public class PersistentArrayHolder extends AbstractPersistentCollection { return elements(); } - public void beginRead() { + @Override + public void beginRead() { super.beginRead(); tempList = new ArrayList(); } - public boolean endRead() { + @Override + public boolean endRead() { setInitialized(); array = Array.newInstance( elementClass, tempList.size() ); for ( int i=0; iSystem properties or + * a java.util.Properties instance. The ConnectionProviderFactory + * first attempts to find a name of a ConnectionProvider subclass in the + * property hibernate.connection.provider_class. If missing, heuristics are used + * to choose either DriverManagerConnectionProvider, + * DatasourceConnectionProvider, C3P0ConnectionProvider or + * DBCPConnectionProvider. + * + * @author Gavin King + * @see ConnectionProvider + */ + +public final class ConnectionProviderFactory { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ConnectionProviderFactory.class.getPackage().getName()); + + /** + * Instantiate a ConnectionProvider using System properties. + * + * @return The created connection provider. + * + * @throws HibernateException + */ + public static ConnectionProvider newConnectionProvider() throws HibernateException { + return newConnectionProvider( Environment.getProperties() ); + } + + /** + * Instantiate a ConnectionProvider using given properties. + * Method newConnectionProvider. + * + * @param properties hibernate SessionFactory properties + * + * @return ConnectionProvider + * + * @throws HibernateException + */ + public static ConnectionProvider newConnectionProvider(Properties properties) throws HibernateException { + return newConnectionProvider( properties, null ); + } + + /** + * Create a connection provider based on the given information. + * + * @param properties Properties being used to build the {@link org.hibernate.SessionFactory}. + * @param connectionProviderInjectionData Something to be injected in the connection provided + * + * @return The created connection provider + * + * @throws HibernateException + */ + public static ConnectionProvider newConnectionProvider(Properties properties, Map connectionProviderInjectionData) + throws HibernateException { + ConnectionProvider connections; + String providerClass = properties.getProperty( Environment.CONNECTION_PROVIDER ); + if ( providerClass != null ) { + connections = initializeConnectionProviderFromConfig( providerClass ); + } + else if ( c3p0ConfigDefined( properties ) && c3p0ProviderPresent() ) { + connections = initializeConnectionProviderFromConfig("org.hibernate.connection.C3P0ConnectionProvider"); + } + else if ( properties.getProperty( Environment.DATASOURCE ) != null ) { + connections = new DatasourceConnectionProvider(); + } + else if ( properties.getProperty( Environment.URL ) != null ) { + connections = new DriverManagerConnectionProvider(); + } + else { + connections = new UserSuppliedConnectionProvider(); + } + + if ( connectionProviderInjectionData != null && connectionProviderInjectionData.size() != 0 ) { + //inject the data + try { + BeanInfo info = Introspector.getBeanInfo( connections.getClass() ); + PropertyDescriptor[] descritors = info.getPropertyDescriptors(); + int size = descritors.length; + for ( int index = 0; index < size; index++ ) { + String propertyName = descritors[index].getName(); + if ( connectionProviderInjectionData.containsKey( propertyName ) ) { + Method method = descritors[index].getWriteMethod(); + method.invoke( + connections, new Object[] { connectionProviderInjectionData.get( propertyName ) } + ); + } + } + } + catch ( IntrospectionException e ) { + throw new HibernateException( "Unable to inject objects into the connection provider", e ); + } + catch ( IllegalAccessException e ) { + throw new HibernateException( "Unable to inject objects into the connection provider", e ); + } + catch ( InvocationTargetException e ) { + throw new HibernateException( "Unable to inject objects into the connection provider", e ); + } + } + connections.configure( properties ); + return connections; + } + + private static boolean c3p0ProviderPresent() { + try { + ReflectHelper.classForName( "org.hibernate.connection.C3P0ConnectionProvider" ); + } + catch ( ClassNotFoundException e ) { + LOG.c3p0PropertiesIgnored(); + return false; + } + return true; + } + + private static boolean c3p0ConfigDefined(Properties properties) { + Iterator iter = properties.keySet().iterator(); + while ( iter.hasNext() ) { + String property = (String) iter.next(); + if ( property.startsWith( "hibernate.c3p0" ) ) { + return true; + } + } + return false; + } + + private static ConnectionProvider initializeConnectionProviderFromConfig(String providerClass) { + ConnectionProvider connections; + try { + LOG.initializingConnectionProvider(providerClass); + connections = (ConnectionProvider) ReflectHelper.classForName( providerClass ).newInstance(); + } + catch ( Exception e ) { + LOG.unableToInstantiateConnectionProvider(e.getMessage()); + throw new HibernateException( "Could not instantiate connection provider: " + providerClass ); + } + return connections; + } + + // cannot be instantiated + + private ConnectionProviderFactory() { + throw new UnsupportedOperationException(); + } + + /** + * Transform JDBC connection properties. + * + * Passed in the form hibernate.connection.* to the + * format accepted by DriverManager by trimming the leading "hibernate.connection". + */ + public static Properties getConnectionProperties(Properties properties) { + + Iterator iter = properties.keySet().iterator(); + Properties result = new Properties(); + while ( iter.hasNext() ) { + String prop = (String) iter.next(); + if ( prop.startsWith( Environment.CONNECTION_PREFIX ) && !SPECIAL_PROPERTIES.contains( prop ) ) { + result.setProperty( + prop.substring( Environment.CONNECTION_PREFIX.length() + 1 ), + properties.getProperty( prop ) + ); + } + } + String userName = properties.getProperty( Environment.USER ); + if ( userName != null ) { + result.setProperty( "user", userName ); + } + return result; + } + + private static final Set SPECIAL_PROPERTIES; + + static { + SPECIAL_PROPERTIES = new HashSet(); + SPECIAL_PROPERTIES.add( Environment.DATASOURCE ); + SPECIAL_PROPERTIES.add( Environment.URL ); + SPECIAL_PROPERTIES.add( Environment.CONNECTION_PROVIDER ); + SPECIAL_PROPERTIES.add( Environment.POOL_SIZE ); + SPECIAL_PROPERTIES.add( Environment.ISOLATION ); + SPECIAL_PROPERTIES.add( Environment.DRIVER ); + SPECIAL_PROPERTIES.add( Environment.USER ); + + } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = WARN ) + @Message( value = "c3p0 properties is specified, but could not find org.hibernate.connection.C3P0ConnectionProvider from the classpath, these properties are going to be ignored." ) + void c3p0PropertiesIgnored(); + + @LogMessage( level = INFO ) + @Message( value = "Initializing connection provider: %s" ) + void initializingConnectionProvider( String providerClass ); + + @LogMessage( level = ERROR ) + @Message( value = "Could not instantiate connection provider\n%s" ) + void unableToInstantiateConnectionProvider( String message ); + } +} + + + + + + diff --git a/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java new file mode 100644 index 0000000000..d4184c6fca --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/connection/DatasourceConnectionProvider.java @@ -0,0 +1,130 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * indicated by the @author tags or express copyright attribution + * statements applied by the authors. All third-party contributions are + * distributed under license by Red Hat Middleware LLC. + * + * This copyrighted material is made available to anyone wishing to use, modify, + * copy, or redistribute it subject to the terms and conditions of the GNU + * Lesser General Public License, as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this distribution; if not, write to: + * Free Software Foundation, Inc. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA + * + */ +package org.hibernate.connection; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.INFO; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; +import javax.sql.DataSource; +import org.hibernate.HibernateException; +import org.hibernate.cfg.Environment; +import org.hibernate.internal.util.jndi.JndiHelper; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; + +/** + * A connection provider that uses a DataSource registered with JNDI. + * Hibernate will use this ConnectionProvider by default if the + * property hibernate.connection.datasource is set. + * @see ConnectionProvider + * @author Gavin King + */ +public class DatasourceConnectionProvider implements ConnectionProvider { + private DataSource ds; + private String user; + private String pass; + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DatasourceConnectionProvider.class.getPackage().getName()); + + public DataSource getDataSource() { + return ds; + } + + public void setDataSource(DataSource ds) { + this.ds = ds; + } + + public void configure(Properties props) throws HibernateException { + + String jndiName = props.getProperty( Environment.DATASOURCE ); + if ( jndiName == null ) { + String msg = "datasource JNDI name was not specified by property " + Environment.DATASOURCE; + LOG.unspecifiedJndiName(msg); + throw new HibernateException( msg ); + } + + user = props.getProperty( Environment.USER ); + pass = props.getProperty( Environment.PASS ); + + try { + ds = ( DataSource ) JndiHelper.getInitialContext( props ).lookup( jndiName ); + } + catch ( Exception e ) { + LOG.datasourceNotFound(jndiName, e.getMessage()); + throw new HibernateException( "Could not find datasource", e ); + } + if ( ds == null ) { + throw new HibernateException( "Could not find datasource: " + jndiName ); + } + LOG.usingDatasource(jndiName); + } + + public Connection getConnection() throws SQLException { + if (user != null || pass != null) { + return ds.getConnection(user, pass); + } + else { + return ds.getConnection(); + } + } + + public void closeConnection(Connection conn) throws SQLException { + conn.close(); + } + + public void close() {} + + /** + * @see ConnectionProvider#supportsAggressiveRelease() + */ + public boolean supportsAggressiveRelease() { + return true; + } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = ERROR ) + @Message( value = "Could not find datasource: %s\n%s" ) + void datasourceNotFound( String jndiName, + String message ); + + @LogMessage( level = ERROR ) + @Message( value = "%s" ) + void unspecifiedJndiName( String msg ); + + @LogMessage( level = INFO ) + @Message( value = "Using datasource: %s" ) + void usingDatasource( String jndiName ); + } +} \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java new file mode 100644 index 0000000000..dc015e3c8d --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/connection/DriverManagerConnectionProvider.java @@ -0,0 +1,275 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * indicated by the @author tags or express copyright attribution + * statements applied by the authors. All third-party contributions are + * distributed under license by Red Hat Middleware LLC. + * + * This copyrighted material is made available to anyone wishing to use, modify, + * copy, or redistribute it subject to the terms and conditions of the GNU + * Lesser General Public License, as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this distribution; if not, write to: + * Free Software Foundation, Inc. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA + * + */ +package org.hibernate.connection; + +import 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.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Properties; +import org.hibernate.HibernateException; +import org.hibernate.cfg.Environment; +import org.hibernate.internal.util.config.ConfigurationHelper; +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 connection provider that uses java.sql.DriverManager. This provider + * also implements a very rudimentary connection pool. + * @see ConnectionProvider + * @author Gavin King + */ +public class DriverManagerConnectionProvider implements ConnectionProvider { + + private String url; + private Properties connectionProps; + private Integer isolation; + private final ArrayList pool = new ArrayList(); + private int poolSize; + private int checkedOut = 0; + private boolean autocommit; + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DriverManagerConnectionProvider.class.getPackage().getName()); + + public void configure(Properties props) throws HibernateException { + + String driverClass = props.getProperty(Environment.DRIVER); + + poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, props, 20); //default pool size 20 + LOG.usingHibernateConnectionPool(); + LOG.hibernateConnectionPoolSize(poolSize); + + autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props); + LOG.autocommmitMode(autocommit); + + isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props); + if (isolation!=null) + LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation.intValue())); + + if (driverClass == null) LOG.unspecifiedJdbcDriver(Environment.DRIVER); + else { + try { + // trying via forName() first to be as close to DriverManager's semantics + Class.forName(driverClass); + } + catch (ClassNotFoundException cnfe) { + try { + ReflectHelper.classForName(driverClass); + } + catch (ClassNotFoundException e) { + String msg = "JDBC Driver class not found: " + driverClass; + LOG.jdbcDriverClassNotFound(msg, e.getMessage()); + throw new HibernateException(msg, e); + } + } + } + + url = props.getProperty( Environment.URL ); + if ( url == null ) { + String msg = "JDBC URL was not specified by property " + Environment.URL; + LOG.unspecifiedJdbcUrl(msg); + throw new HibernateException( msg ); + } + + connectionProps = ConnectionProviderFactory.getConnectionProperties( props ); + + LOG.usingDriver(driverClass, url); + // if debug level is enabled, then log the password, otherwise mask it + if (LOG.isDebugEnabled()) LOG.connectionProperties(connectionProps); + else LOG.connectionProperties(ConfigurationHelper.maskOut(connectionProps, "password")); + } + + public Connection getConnection() throws SQLException { + + LOG.checkedOutConnections(checkedOut); + + synchronized (pool) { + if ( !pool.isEmpty() ) { + int last = pool.size() - 1; + if (LOG.isTraceEnabled()) { + LOG.usingPooledJdbcConnection(last); + checkedOut++; + } + Connection pooled = (Connection) pool.remove(last); + if (isolation!=null) pooled.setTransactionIsolation( isolation.intValue() ); + if ( pooled.getAutoCommit()!=autocommit ) pooled.setAutoCommit(autocommit); + return pooled; + } + } + + LOG.openingNewJdbcConnection(); + Connection conn = DriverManager.getConnection(url, connectionProps); + if (isolation!=null) conn.setTransactionIsolation( isolation.intValue() ); + if ( conn.getAutoCommit()!=autocommit ) conn.setAutoCommit(autocommit); + + LOG.createdConnection(url, conn.getTransactionIsolation()); + if (LOG.isTraceEnabled()) checkedOut++; + + return conn; + } + + public void closeConnection(Connection conn) throws SQLException { + + if (LOG.isDebugEnabled()) checkedOut--; + + synchronized (pool) { + int currentSize = pool.size(); + if ( currentSize < poolSize ) { + LOG.returningConnectionToPool(currentSize + 1); + pool.add(conn); + return; + } + } + + LOG.closingJdbcConnection(); + + conn.close(); + + } + + @Override + protected void finalize() { + close(); + } + + public void close() { + + LOG.cleaningConnectionPool(url); + + Iterator iter = pool.iterator(); + while ( iter.hasNext() ) { + try { + ( (Connection) iter.next() ).close(); + } + catch (SQLException sqle) { + LOG.unableToClosePooledConnection(sqle.getMessage()); + } + } + pool.clear(); + + } + + /** + * @see ConnectionProvider#supportsAggressiveRelease() + */ + public boolean supportsAggressiveRelease() { + return false; + } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = INFO ) + @Message( value = "Autocommit mode: %s" ) + void autocommmitMode( boolean autocommit ); + + @LogMessage( level = TRACE ) + @Message( value = "Total checked-out connections: %d" ) + void checkedOutConnections( int checkedOut ); + + @LogMessage( level = INFO ) + @Message( value = "Cleaning up connection pool: %s" ) + void cleaningConnectionPool( String url ); + + @LogMessage( level = DEBUG ) + @Message( value = "Closing JDBC connection" ) + void closingJdbcConnection(); + + @LogMessage( level = INFO ) + @Message( value = "Connection properties: %s" ) + void connectionProperties( Properties connectionProps ); + + @LogMessage( level = DEBUG ) + @Message( value = "Created connection to: %s, Isolation Level: %d" ) + void createdConnection( String url, + int transactionIsolation ); + + @LogMessage( level = INFO ) + @Message( value = "Hibernate connection pool size: %s" ) + void hibernateConnectionPoolSize( int poolSize ); + + @LogMessage( level = ERROR ) + @Message( value = "%s\n%s" ) + void jdbcDriverClassNotFound( String message, + String errorMessage ); + + @LogMessage( level = INFO ) + @Message( value = "JDBC isolation level: %s" ) + void jdbcIsolationLevel( String isolationLevelToString ); + + @LogMessage( level = DEBUG ) + @Message( value = "Opening new JDBC connection" ) + void openingNewJdbcConnection(); + + @LogMessage( level = TRACE ) + @Message( value = "Returning connection to pool, pool size: %d" ) + void returningConnectionToPool( int i ); + + @LogMessage( level = WARN ) + @Message( value = "Problem closing pooled connection\n%s" ) + void unableToClosePooledConnection( String message ); + + @LogMessage( level = WARN ) + @Message( value = "No JDBC Driver class was specified by property %s" ) + void unspecifiedJdbcDriver( String driver ); + + @LogMessage( level = ERROR ) + @Message( value = "%s" ) + void unspecifiedJdbcUrl( String message ); + + @LogMessage( level = INFO ) + @Message( value = "Using driver: %s at URL: %s" ) + void usingDriver( String driverClass, + String url ); + + @LogMessage( level = INFO ) + @Message( value = "Using Hibernate built-in connection pool (not for production use!)" ) + void usingHibernateConnectionPool(); + + @LogMessage( level = TRACE ) + @Message( value = "Using pooled JDBC connection, pool size: %d" ) + void usingPooledJdbcConnection( int last ); + } +} + + + + + + + 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 7b7f7fc7e8..effe462cf4 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/JTASessionContext.java @@ -24,19 +24,21 @@ */ package org.hibernate.context; -import org.hibernate.HibernateException; +import static org.jboss.logging.Logger.Level.DEBUG; +import java.util.Hashtable; +import java.util.Map; +import javax.transaction.Synchronization; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; import org.hibernate.ConnectionReleaseMode; +import org.hibernate.HibernateException; import org.hibernate.classic.Session; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.JTAHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; -import javax.transaction.Synchronization; -import java.util.Map; -import java.util.Hashtable; +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 @@ -63,7 +65,8 @@ import java.util.Hashtable; */ public class JTASessionContext implements CurrentSessionContext { - private static final Logger log = LoggerFactory.getLogger( JTASessionContext.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JTASessionContext.class.getPackage().getName()); protected final SessionFactoryImplementor factory; private transient Map currentSessionMap = new Hashtable(); @@ -118,7 +121,7 @@ public class JTASessionContext implements CurrentSessionContext { currentSession.close(); } catch ( Throwable ignore ) { - log.debug( "Unable to release generated current-session on failed synch registration", ignore ); + LOG.unableToReleaseSession(ignore.getMessage()); } throw new HibernateException( "Unable to register cleanup Synchronization with TransactionManager" ); } @@ -209,4 +212,15 @@ 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 3e9e3f88ac..f5d707627f 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/ThreadLocalSessionContext.java @@ -24,6 +24,9 @@ */ 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; @@ -35,14 +38,15 @@ import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import javax.transaction.Synchronization; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; 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 @@ -72,7 +76,8 @@ import org.hibernate.engine.SessionFactoryImplementor; */ public class ThreadLocalSessionContext implements CurrentSessionContext { - private static final Logger log = LoggerFactory.getLogger( ThreadLocalSessionContext.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ThreadLocalSessionContext.class.getPackage().getName()); private static final Class[] SESS_PROXY_INTERFACES = new Class[] { org.hibernate.classic.Session.class, org.hibernate.engine.SessionImplementor.class, @@ -204,20 +209,20 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { private static void cleanupAnyOrphanedSession(SessionFactory factory) { Session orphan = doUnbind( factory, false ); if ( orphan != null ) { - log.warn( "Already session bound on call to bind(); make sure you clean up your sessions!" ); + LOG.alreadySessionBound(); try { if ( orphan.getTransaction() != null && orphan.getTransaction().isActive() ) { try { orphan.getTransaction().rollback(); } catch( Throwable t ) { - log.debug( "Unable to rollback transaction for orphaned session", t ); + LOG.unableToRollbackTransaction(t.getMessage()); } } orphan.close(); } catch( Throwable t ) { - log.debug( "Unable to close orphaned session", t ); + LOG.unableToCloseOrphanedSession(t.getMessage()); } } } @@ -330,7 +335,7 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { || "isTransactionInProgress".equals( method.getName() ) || "setFlushMode".equals( method.getName() ) || "getSessionFactory".equals( method.getName() ) ) { - log.trace( "allowing method [" + method.getName() + "] in non-transacted context" ); + LOG.allowingMethodInNonTransactedContext(method.getName()); } else if ( "reconnect".equals( method.getName() ) || "disconnect".equals( method.getName() ) ) { @@ -340,7 +345,7 @@ public class ThreadLocalSessionContext implements CurrentSessionContext { throw new HibernateException( method.getName() + " is not valid without active transaction" ); } } - log.trace( "allowing proxied method [" + method.getName() + "] to proceed to real session" ); + LOG.allowingProxiedMethodInSession(method.getName()); return method.invoke( realSession, args ); } catch ( InvocationTargetException e ) { @@ -384,4 +389,31 @@ 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 9fdcd6e73f..0f46568096 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java @@ -23,20 +23,21 @@ */ package org.hibernate.dialect; +import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.Method; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 + * Hibernate Dialect for Cloudscape 10 - aka Derby. This implements both an * override for the identity column generator as well as for the case statement * issue documented at: * http://www.jroller.com/comments/kenlars99/Weblog/cloudscape_soon_to_be_derby @@ -44,7 +45,9 @@ import org.hibernate.util.ReflectHelper; * @author Simon Johnston */ public class DerbyDialect extends DB2Dialect { - private static final Logger log = LoggerFactory.getLogger( DerbyDialect.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DerbyDialect.class.getPackage().getName()); private int driverVersionMajor; private int driverVersionMinor; @@ -67,7 +70,7 @@ public class DerbyDialect extends DB2Dialect { driverVersionMinor = ( (Integer) minorVersionGetter.invoke( null, ReflectHelper.NO_PARAMS ) ).intValue(); } catch ( Exception e ) { - log.warn( "Unable to load/access derby driver class sysinfo to check versions : " + e ); + LOG.unableToLoadDerbyDriver(e.getMessage()); driverVersionMajor = -1; driverVersionMinor = -1; } @@ -77,22 +80,26 @@ public class DerbyDialect extends DB2Dialect { return driverVersionMajor > 10 || ( driverVersionMajor == 10 && driverVersionMinor >= 5 ); } - public String getCrossJoinSeparator() { + @Override + public String getCrossJoinSeparator() { return ", "; } /** * Return the case statement modified for Cloudscape. */ - public CaseFragment createCaseFragment() { + @Override + public CaseFragment createCaseFragment() { return new DerbyCaseFragment(); } - public boolean dropConstraints() { + @Override + public boolean dropConstraints() { return true; } - public boolean supportsSequences() { + @Override + public boolean supportsSequences() { // technically sequence support was added in 10.6.1.0... // // The problem though is that I am not exactly sure how to differentiate 10.6.1.0 from any other 10.6.x release. @@ -116,31 +123,37 @@ public class DerbyDialect extends DB2Dialect { } } - public boolean supportsLimit() { + @Override + public boolean supportsLimit() { return isTenPointFiveReleaseOrNewer(); } - + //HHH-4531 - public boolean supportsCommentOn() { + @Override + public boolean supportsCommentOn() { return false; } - public boolean supportsLimitOffset() { + @Override + public boolean supportsLimitOffset() { return isTenPointFiveReleaseOrNewer(); } - public String getForUpdateString() { + @Override +public String getForUpdateString() { return " for update with rs"; } - public String getWriteLockString(int timeout) { + @Override + public String getWriteLockString(int timeout) { return " for update with rs"; } - public String getReadLockString(int timeout) { + @Override + public String getReadLockString(int timeout) { return " for read only with rs"; } - + /** * {@inheritDoc} @@ -155,7 +168,8 @@ public class DerbyDialect extends DB2Dialect { * [WITH {RR|RS|CS|UR}] * */ - public String getLimitString(String query, final int offset, final int limit) { + @Override + public String getLimitString(String query, final int offset, final int limit) { StringBuffer sb = new StringBuffer(query.length() + 50); final String normalizedSelect = query.toLowerCase().trim(); @@ -190,7 +204,8 @@ public class DerbyDialect extends DB2Dialect { return sb.toString(); } - public boolean supportsVariableLimit() { + @Override + public boolean supportsVariableLimit() { // we bind the limit and offset values directly into the sql... return false; } @@ -211,14 +226,27 @@ public class DerbyDialect extends DB2Dialect { return i; } - public String getQuerySequencesString() { + @Override + public String getQuerySequencesString() { return null ; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - public boolean supportsLobValueChangePropogation() { + @Override + 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 2a6023a362..627defd6ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -23,6 +23,7 @@ */ package org.hibernate.dialect; +import static org.jboss.logging.Logger.Level.INFO; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -32,10 +33,6 @@ import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; @@ -69,6 +66,10 @@ 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. @@ -83,7 +84,7 @@ import org.hibernate.util.StringHelper; */ public abstract class Dialect { - private static final Logger log = LoggerFactory.getLogger( Dialect.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Dialect.class.getPackage().getName()); public static final String DEFAULT_BATCH_SIZE = "15"; public static final String NO_BATCH = "0"; @@ -105,7 +106,7 @@ public abstract class Dialect { // constructors and factory methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ protected Dialect() { - log.info( "Using dialect: " + this ); + LOG.usingDialect(this); StandardAnsiSqlAggregationFunctions.primeFunctionMap( sqlFunctions ); // standard sql92 functions (can be overridden by subclasses) @@ -210,7 +211,8 @@ public abstract class Dialect { return properties; } - public String toString() { + @Override + public String toString() { return getClass().getName(); } @@ -577,7 +579,8 @@ public abstract class Dialect { * @throws MappingException If sequences are not supported. * @deprecated Use {@link #getCreateSequenceString(String, int, int)} instead */ - public String[] getCreateSequenceStrings(String sequenceName) throws MappingException { + @Deprecated + public String[] getCreateSequenceStrings(String sequenceName) throws MappingException { return new String[] { getCreateSequenceString( sequenceName ) }; } @@ -1012,7 +1015,7 @@ public abstract class Dialect { * dialect given the aliases of the columns to be write locked. * * @param aliases The columns to be write locked. - * @param lockOptions + * @param lockOptions * @return The appropriate FOR UPDATE OF column_list clause string. */ public String getForUpdateString(String aliases, LockOptions lockOptions) { @@ -1169,7 +1172,7 @@ public abstract class Dialect { *
  • null - defer to the JDBC driver response in regards to * {@link java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()}
  • * - * + * * @return see the result matrix above. */ public Boolean performTemporaryTableDDLInIsolation() { @@ -1925,13 +1928,24 @@ public abstract class Dialect { return false; } - /** - * Does this dialect support `count(distinct a,b)`? - * - * @return True if the database supports counting disintct tuples; false otherwise. - */ + /** + * 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 4a9133c23e..af21029165 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java @@ -23,12 +23,9 @@ */ package org.hibernate.dialect; +import static org.jboss.logging.Logger.Level.WARN; import java.sql.SQLException; import java.sql.Types; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.AvgWithArgumentCastFunction; import org.hibernate.dialect.function.NoArgSQLFunction; @@ -38,6 +35,10 @@ 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. @@ -45,7 +46,9 @@ import org.hibernate.util.ReflectHelper; * @author Thomas Mueller */ public class H2Dialect extends Dialect { - private static final Logger log = LoggerFactory.getLogger( H2Dialect.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + H2Dialect.class.getPackage().getName()); private String querySequenceString; @@ -62,13 +65,9 @@ public class H2Dialect extends Dialect { if ( buildId < 32 ) { querySequenceString = "select name from information_schema.sequences"; } - if ( !( majorVersion > 1 || minorVersion > 2 || buildId >= 139 ) ) { - log.warn( - "The {} version of H2 implements temporary table creation such that it commits " + - "current transaction; multi-table, bulk hql/jpaql will not work properly", - ( majorVersion + "." + minorVersion + "." + buildId ) - ); - } + if (!(majorVersion > 1 || minorVersion > 2 || buildId >= 139)) LOG.unsupportedMultiTableBulkHqlJpaql(majorVersion, + minorVersion, + buildId); } catch ( Exception e ) { // ignore (probably H2 not in the classpath) @@ -346,4 +345,17 @@ 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 beb2afad1c..d57e9a53a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java @@ -23,30 +23,37 @@ */ 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 java.io.Serializable; - +import org.hibernate.JDBCException; import org.hibernate.LockMode; import org.hibernate.StaleObjectStateException; -import org.hibernate.JDBCException; -import org.hibernate.engine.SessionImplementor; -import org.hibernate.persister.entity.Lockable; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.AvgWithArgumentCastFunction; -import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.NoArgSQLFunction; +import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.dialect.lock.*; +import org.hibernate.dialect.lock.LockingStrategy; +import org.hibernate.dialect.lock.OptimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.OptimisticLockingStrategy; +import org.hibernate.dialect.lock.PessimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.PessimisticReadSelectLockingStrategy; +import org.hibernate.dialect.lock.PessimisticWriteSelectLockingStrategy; +import org.hibernate.dialect.lock.SelectLockingStrategy; +import org.hibernate.engine.SessionImplementor; import org.hibernate.exception.JDBCExceptionHelper; import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.ViolatedConstraintNameExtracter; +import org.hibernate.persister.entity.Lockable; import org.hibernate.type.StandardBasicTypes; import org.hibernate.util.ReflectHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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). @@ -61,7 +68,9 @@ import org.slf4j.LoggerFactory; * @author Fred Toussi */ public class HSQLDialect extends Dialect { - private static final Logger log = LoggerFactory.getLogger( HSQLDialect.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HSQLDialect.class.getPackage().getName()); /** * version is 18 for 1.8 or 20 for 2.0 @@ -590,9 +599,7 @@ public class HSQLDialect extends Dialect { public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException { - if ( getLockMode().greaterThan( LockMode.READ ) ) { - log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" ); - } + if (getLockMode().greaterThan(LockMode.READ)) LOG.hsqldbSupportsOnlyReadCommittedIsolation(); super.lock( id, version, object, timeout, session ); } } @@ -659,4 +666,15 @@ 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 249a718b0b..cde2ec3459 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java @@ -23,15 +23,11 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.NoArgSQLFunction; @@ -44,6 +40,10 @@ 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). @@ -51,13 +51,15 @@ import org.hibernate.util.ReflectHelper; * @deprecated Use either Oracle9iDialect or Oracle10gDialect instead * @author Gavin King, David Channon */ +@Deprecated public class Oracle9Dialect extends Dialect { - private static final Logger log = LoggerFactory.getLogger( Oracle9Dialect.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Oracle9Dialect.class.getPackage().getName()); public Oracle9Dialect() { super(); - log.warn( "The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead" ); + LOG.deprecatedOracle9Dialect(); registerColumnType( Types.BIT, "number(1,0)" ); registerColumnType( Types.BIGINT, "number(19,0)" ); registerColumnType( Types.SMALLINT, "number(5,0)" ); @@ -124,7 +126,7 @@ public class Oracle9Dialect extends Dialect { registerFunction( "current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); registerFunction( "current_time", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIME, false) ); registerFunction( "current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); - + registerFunction( "last_day", new StandardSQLFunction("last_day", StandardBasicTypes.DATE) ); registerFunction( "sysdate", new NoArgSQLFunction("sysdate", StandardBasicTypes.DATE, false) ); registerFunction( "systimestamp", new NoArgSQLFunction("systimestamp", StandardBasicTypes.TIMESTAMP, false) ); @@ -211,14 +213,14 @@ public class Oracle9Dialect extends Dialect { } public String getLimitString(String sql, boolean hasOffset) { - + sql = sql.trim(); boolean isForUpdate = false; if ( sql.toLowerCase().endsWith(" for update") ) { sql = sql.substring( 0, sql.length()-11 ); isForUpdate = true; } - + StringBuffer pagingSelect = new StringBuffer( sql.length()+100 ); if (hasOffset) { pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); @@ -237,7 +239,7 @@ public class Oracle9Dialect extends Dialect { if ( isForUpdate ) { pagingSelect.append( " for update" ); } - + return pagingSelect.toString(); } @@ -256,7 +258,7 @@ public class Oracle9Dialect extends Dialect { public boolean useMaxForLimit() { return true; } - + public boolean forUpdateOfColumns() { return true; } @@ -268,7 +270,7 @@ public class Oracle9Dialect extends Dialect { public String getSelectGUIDString() { return "select rawtohex(sys_guid()) from dual"; } - + public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return EXTRACTER; } @@ -298,7 +300,7 @@ public class Oracle9Dialect extends Dialect { }; // not final-static to avoid possible classcast exceptions if using different oracle drivers. - int oracletypes_cursor_value = 0; + int oracletypes_cursor_value = 0; public int registerResultSetOutParameter(java.sql.CallableStatement statement,int col) throws SQLException { if(oracletypes_cursor_value==0) { try { @@ -306,14 +308,14 @@ public class Oracle9Dialect extends Dialect { oracletypes_cursor_value = types.getField("CURSOR").getInt(types.newInstance()); } catch (Exception se) { throw new HibernateException("Problem while trying to load or access OracleTypes.CURSOR value",se); - } + } } // register the type of the out param - an Oracle specific type statement.registerOutParameter(col, oracletypes_cursor_value); col++; return col; } - + public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); return ( ResultSet ) ps.getObject( 1 ); @@ -322,7 +324,7 @@ public class Oracle9Dialect extends Dialect { public boolean supportsUnionAll() { return true; } - + public boolean supportsCommentOn() { return true; } @@ -370,4 +372,15 @@ 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 4ca47f9a6e..830c7e1ff3 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java @@ -23,15 +23,16 @@ */ package org.hibernate.dialect; +import static org.jboss.logging.Logger.Level.WARN; import java.sql.Types; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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. @@ -39,13 +40,15 @@ import org.hibernate.sql.OracleJoinFragment; * @deprecated Use Oracle8iDialect instead. * @author Gavin King */ +@Deprecated public class OracleDialect extends Oracle9Dialect { - private static final Logger log = LoggerFactory.getLogger( OracleDialect.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OracleDialect.class.getPackage().getName()); public OracleDialect() { super(); - log.warn( "The OracleDialect dialect has been deprecated; use Oracle8iDialect instead" ); + LOG.deprecatedOracleDialect(); // Oracle8 and previous define only a "DATE" type which // is used to represent all aspects of date/time registerColumnType( Types.TIMESTAMP, "date" ); @@ -53,14 +56,17 @@ public class OracleDialect extends Oracle9Dialect { registerColumnType( Types.VARCHAR, 4000, "varchar2($l)" ); } - public JoinFragment createOuterJoinFragment() { + @Override + public JoinFragment createOuterJoinFragment() { return new OracleJoinFragment(); } - public CaseFragment createCaseFragment() { + @Override + public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } - public String getLimitString(String sql, boolean hasOffset) { + @Override + public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; @@ -68,7 +74,7 @@ public class OracleDialect extends Oracle9Dialect { sql = sql.substring( 0, sql.length()-11 ); isForUpdate = true; } - + StringBuffer pagingSelect = new StringBuffer( sql.length()+100 ); if (hasOffset) { pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); @@ -87,11 +93,12 @@ public class OracleDialect extends Oracle9Dialect { if ( isForUpdate ) { pagingSelect.append( " for update" ); } - + return pagingSelect.toString(); } - public String getSelectClauseNullString(int sqlType) { + @Override + public String getSelectClauseNullString(int sqlType) { switch(sqlType) { case Types.VARCHAR: case Types.CHAR: @@ -105,11 +112,24 @@ public class OracleDialect extends Oracle9Dialect { } } - public String getCurrentTimestampSelectString() { + @Override + public String getCurrentTimestampSelectString() { return "select sysdate from dual"; } - public String getCurrentTimestampSQLFunctionName() { + @Override + 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 2e95d282b0..17af1c83e2 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java @@ -23,21 +23,28 @@ */ package org.hibernate.dialect; -import org.hibernate.dialect.function.NoArgSQLFunction; -import org.hibernate.dialect.function.StandardSQLFunction; -import org.hibernate.dialect.function.SQLFunctionTemplate; -import org.hibernate.dialect.lock.*; - +import static org.jboss.logging.Logger.Level.INFO; import java.sql.Types; -import org.hibernate.Hibernate; import org.hibernate.LockMode; +import org.hibernate.dialect.function.NoArgSQLFunction; +import org.hibernate.dialect.function.SQLFunctionTemplate; +import org.hibernate.dialect.function.StandardSQLFunction; +import org.hibernate.dialect.lock.LockingStrategy; +import org.hibernate.dialect.lock.OptimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.OptimisticLockingStrategy; +import org.hibernate.dialect.lock.PessimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.PessimisticReadUpdateLockingStrategy; +import org.hibernate.dialect.lock.PessimisticWriteUpdateLockingStrategy; +import org.hibernate.dialect.lock.SelectLockingStrategy; +import org.hibernate.dialect.lock.UpdateLockingStrategy; import org.hibernate.persister.entity.Lockable; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.type.StandardBasicTypes; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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). @@ -52,12 +59,14 @@ import org.slf4j.LoggerFactory; * @author Ploski and Hanson */ public class RDMSOS2200Dialect extends Dialect { - private static Logger log = LoggerFactory.getLogger(RDMSOS2200Dialect.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + RDMSOS2200Dialect.class.getPackage().getName()); public RDMSOS2200Dialect() { super(); // Display the dialect version. - log.info("RDMSOS2200Dialect version: 1.0"); + LOG.rdmsOs2200Dialect(); /** * This section registers RDMS Biult-in Functions (BIFs) with Hibernate. @@ -356,4 +365,15 @@ 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 fd54e772e5..74b8ab74cf 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,21 +23,24 @@ */ package org.hibernate.dialect.function; +import static org.jboss.logging.Logger.Level.WARN; import java.util.ArrayList; import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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". + * Delegate for handling function "templates". * * @author Steve Ebersole */ public class TemplateRenderer { - private static final Logger log = LoggerFactory.getLogger( TemplateRenderer.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TemplateRenderer.class.getPackage().getName()); private final String template; private final String[] chunks; @@ -99,10 +102,8 @@ public class TemplateRenderer { @SuppressWarnings({ "UnusedDeclaration" }) public String render(List args, SessionFactoryImplementor factory) { int numberOfArguments = args.size(); - if ( getAnticipatedNumberOfArguments() > 0 && numberOfArguments != getAnticipatedNumberOfArguments() ) { - log.warn( "Function template anticipated {} arguments, but {} arguments encountered", - getAnticipatedNumberOfArguments(), numberOfArguments ); - } + if (getAnticipatedNumberOfArguments() > 0 && numberOfArguments != getAnticipatedNumberOfArguments()) LOG.missingArguments(getAnticipatedNumberOfArguments(), + numberOfArguments); StringBuffer buf = new StringBuffer(); for ( int i = 0; i < chunks.length; ++i ) { if ( i < paramIndexes.length ) { @@ -118,4 +119,16 @@ 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/OptimisticLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java index fd831df661..733b38fde2 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java @@ -24,15 +24,16 @@ package org.hibernate.dialect.lock; import java.io.Serializable; - -import org.hibernate.*; -import org.hibernate.event.EventSource; +import org.hibernate.HibernateException; +import org.hibernate.JDBCException; +import org.hibernate.LockMode; +import org.hibernate.OptimisticLockException; +import org.hibernate.StaleObjectStateException; import org.hibernate.action.EntityVerifyVersionProcess; -import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.EntityEntry; +import org.hibernate.engine.SessionImplementor; +import org.hibernate.event.EventSource; import org.hibernate.persister.entity.Lockable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * An optimistic locking strategy that verifies that the version hasn't changed (prior to transaction commit). @@ -44,7 +45,6 @@ import org.slf4j.LoggerFactory; * @author Scott Marlow */ public class OptimisticLockingStrategy implements LockingStrategy { - private static final Logger log = LoggerFactory.getLogger( OptimisticLockingStrategy.class ); private final Lockable lockable; private final LockMode lockMode; 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 9d473ca9b9..e561813cfa 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 @@ -26,19 +26,16 @@ package org.hibernate.dialect.lock; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.SQLException; - +import org.hibernate.HibernateException; +import org.hibernate.JDBCException; +import org.hibernate.LockMode; +import org.hibernate.PessimisticLockException; +import org.hibernate.StaleObjectStateException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.entity.Lockable; import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.Update; -import org.hibernate.LockMode; -import org.hibernate.HibernateException; -import org.hibernate.StaleObjectStateException; -import org.hibernate.JDBCException; -import org.hibernate.PessimisticLockException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * A pessimistic locking strategy where the locks are obtained through update statements. @@ -53,7 +50,9 @@ import org.slf4j.LoggerFactory; * @author Scott Marlow */ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { - private static final Logger log = LoggerFactory.getLogger( PessimisticReadUpdateLockingStrategy.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PessimisticReadUpdateLockingStrategy.class.getPackage().getName()); private final Lockable lockable; private final LockMode lockMode; @@ -73,7 +72,7 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { throw new HibernateException( "[" + lockMode + "] not valid for update statement" ); } if ( !lockable.isVersioned() ) { - log.warn( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); + LOG.writeLocksNotSupported(lockable.getEntityName()); this.sql = null; } else { 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 47d9af492c..21643b5981 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 @@ -26,19 +26,16 @@ package org.hibernate.dialect.lock; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.SQLException; - +import org.hibernate.HibernateException; +import org.hibernate.JDBCException; +import org.hibernate.LockMode; +import org.hibernate.PessimisticLockException; +import org.hibernate.StaleObjectStateException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.entity.Lockable; import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.Update; -import org.hibernate.LockMode; -import org.hibernate.HibernateException; -import org.hibernate.StaleObjectStateException; -import org.hibernate.JDBCException; -import org.hibernate.PessimisticLockException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * A pessimistic locking strategy where the locks are obtained through update statements. @@ -53,7 +50,9 @@ import org.slf4j.LoggerFactory; * @author Scott Marlow */ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { - private static final Logger log = LoggerFactory.getLogger( PessimisticWriteUpdateLockingStrategy.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PessimisticWriteUpdateLockingStrategy.class.getPackage().getName()); private final Lockable lockable; private final LockMode lockMode; @@ -73,7 +72,7 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { throw new HibernateException( "[" + lockMode + "] not valid for update statement" ); } if ( !lockable.isVersioned() ) { - log.warn( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); + LOG.writeLocksNotSupported(lockable.getEntityName()); this.sql = null; } else { 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 a8c7e2b47d..edb891751b 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 @@ -26,7 +26,6 @@ package org.hibernate.dialect.lock; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.SQLException; - import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.LockMode; @@ -36,8 +35,6 @@ import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.entity.Lockable; import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.Update; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * A locking strategy where the locks are obtained through update statements. @@ -49,7 +46,9 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class UpdateLockingStrategy implements LockingStrategy { - private static final Logger log = LoggerFactory.getLogger( UpdateLockingStrategy.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + UpdateLockingStrategy.class.getPackage().getName()); private final Lockable lockable; private final LockMode lockMode; @@ -69,7 +68,7 @@ public class UpdateLockingStrategy implements LockingStrategy { throw new HibernateException( "[" + lockMode + "] not valid for update statement" ); } if ( !lockable.isVersioned() ) { - log.warn( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); + LOG.writeLocksNotSupported(lockable.getEntityName()); this.sql = null; } else { 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 new file mode 100644 index 0000000000..63a0256742 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/AbstractDialectResolver.java @@ -0,0 +1,96 @@ +/* + * 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.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; + +/** + * A templated resolver impl which delegates to the {@link #resolveDialectInternal} method + * and handles any thrown {@link SQLException}s. + * + * @author Steve Ebersole + */ +public abstract class AbstractDialectResolver implements DialectResolver { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionSecondPass.class.getPackage().getName()); + + /** + * {@inheritDoc} + *

    + * Here we template the resolution, delegating to {@link #resolveDialectInternal} and handling + * {@link java.sql.SQLException}s properly. + */ + public final Dialect resolveDialect(DatabaseMetaData metaData) { + try { + return resolveDialectInternal( metaData ); + } + catch ( SQLException sqlException ) { + JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException ); + if (jdbcException instanceof JDBCConnectionException) throw jdbcException; + LOG.unableToQueryDatabaseMetadata(BasicSQLExceptionConverter.MSG, sqlException.getMessage()); + return null; + } + catch ( Throwable t ) { + LOG.unableToExecuteResolver(this, t.getMessage()); + return null; + } + } + + /** + * Perform the actual resolution without caring about handling {@link SQLException}s. + * + * @param metaData The database metadata + * @return The resolved dialect, or null if we could not resolve. + * @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 515f1421af..fda82438dc 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 @@ -24,10 +24,12 @@ package org.hibernate.dialect.resolver; import java.sql.SQLException; - +import org.hibernate.JDBCException; import org.hibernate.exception.SQLStateConverter; import org.hibernate.exception.ViolatedConstraintNameExtracter; -import org.hibernate.JDBCException; +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. @@ -35,8 +37,11 @@ import org.hibernate.JDBCException; * @author Steve Ebersole */ public class BasicSQLExceptionConverter { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicSQLExceptionConverter.class.getPackage().getName()); public static final BasicSQLExceptionConverter INSTANCE = new BasicSQLExceptionConverter(); - public static final String MSG = "Unable to query java.sql.DatabaseMetaData"; + public static final String MSG = LOG.unableToQueryDatabaseMetadata(); private static final SQLStateConverter CONVERTER = new SQLStateConverter( new ConstraintNameExtracter() ); @@ -58,4 +63,14 @@ 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 new file mode 100644 index 0000000000..7facff6dd3 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectFactory.java @@ -0,0 +1,181 @@ +/* + * 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.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.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. + * + * @author Steve Ebersole + * @author Tomoto Shimizu Washio + */ +public class DialectFactory { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DialectFactory.class.getPackage().getName()); + + private static DialectResolverSet DIALECT_RESOLVERS = new DialectResolverSet(); + + static { + // register the standard dialect resolver + DIALECT_RESOLVERS.addResolver( new StandardDialectResolver() ); + + // register resolvers set via Environment property + String userSpecifedResolverSetting = Environment.getProperties().getProperty( Environment.DIALECT_RESOLVERS ); + if ( userSpecifedResolverSetting != null ) { + String[] userSpecifedResolvers = userSpecifedResolverSetting.split( "\\s+" ); + for ( int i = 0; i < userSpecifedResolvers.length; i++ ) { + registerDialectResolver( userSpecifedResolvers[i] ); + } + } + } + + /*package*/ static void registerDialectResolver(String resolverName) { + try { + DialectResolver resolver = ( DialectResolver ) ReflectHelper.classForName( resolverName ).newInstance(); + DIALECT_RESOLVERS.addResolverAtFirst( resolver ); + } + catch ( ClassNotFoundException cnfe ) { + LOG.dialectResolverNotFound(resolverName); + } + catch ( Exception e ) { + LOG.unableToInstantiateDialectResolver(e.getMessage()); + } + } + + /** + * Builds an appropriate Dialect instance. + *

    + * If a dialect is explicitly named in the incoming properties, it is used. Otherwise, it is + * determined by dialect resolvers based on the passed connection. + *

    + * An exception is thrown if a dialect was not explicitly set and no resolver could make + * the determination from the given connection. + * + * @param properties The configuration properties. + * @param connection The configured connection. + * @return The appropriate dialect instance. + * @throws HibernateException No dialect specified and no resolver could make the determination. + */ + public static Dialect buildDialect(Properties properties, Connection connection) throws HibernateException { + String dialectName = properties.getProperty( Environment.DIALECT ); + if ( dialectName == null ) { + return determineDialect( connection ); + } + else { + return constructDialect( dialectName ); + } + } + + public static Dialect buildDialect(Properties properties) { + String dialectName = properties.getProperty( Environment.DIALECT ); + if ( dialectName == null ) { + throw new HibernateException( "'hibernate.dialect' must be set when no Connection available" ); + } + return constructDialect( dialectName ); + } + + /** + * Determine the appropriate Dialect to use given the connection. + * + * @param connection The configured connection. + * @return The appropriate dialect instance. + * + * @throws HibernateException No connection given or no resolver could make + * the determination from the given connection. + */ + private static Dialect determineDialect(Connection connection) { + if ( connection == null ) { + throw new HibernateException( "Connection cannot be null when 'hibernate.dialect' not set" ); + } + + try { + final DatabaseMetaData databaseMetaData = connection.getMetaData(); + final Dialect dialect = DIALECT_RESOLVERS.resolveDialect( databaseMetaData ); + + if ( dialect == null ) { + throw new HibernateException( + "Unable to determine Dialect to use [name=" + databaseMetaData.getDatabaseProductName() + + ", majorVersion=" + databaseMetaData.getDatabaseMajorVersion() + + "]; user must register resolver or explicitly set 'hibernate.dialect'" + ); + } + + return dialect; + } + catch ( SQLException sqlException ) { + throw new HibernateException( + "Unable to access java.sql.DatabaseMetaData to determine appropriate Dialect to use", + sqlException + ); + } + } + + /** + * Returns a dialect instance given the name of the class to use. + * + * @param dialectName The name of the dialect class. + * + * @return The dialect instance. + */ + public static Dialect constructDialect(String dialectName) { + try { + return ( Dialect ) ReflectHelper.classForName( dialectName ).newInstance(); + } + catch ( ClassNotFoundException cnfe ) { + throw new HibernateException( "Dialect class not found: " + dialectName, cnfe ); + } + catch ( Exception e ) { + 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 new file mode 100644 index 0000000000..2e872f9363 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/DialectResolverSet.java @@ -0,0 +1,106 @@ +/* + * 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.dialect.resolver; + +import static org.jboss.logging.Logger.Level.INFO; +import java.sql.DatabaseMetaData; +import java.util.ArrayList; +import java.util.Iterator; +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; + +/** + * A {@link DialectResolver} implementation which coordinates resolution by delegating to its + * registered sub-resolvers. Sub-resolvers may be registered by calling either {@link #addResolver} or + * {@link #addResolverAtFirst}. + * + * @author Tomoto Shimizu Washio + */ +public class DialectResolverSet implements DialectResolver { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionSecondPass.class.getPackage().getName()); + + private List resolvers = new ArrayList(); + + /** + * {@inheritDoc} + */ + public Dialect resolveDialect(DatabaseMetaData metaData) { + Iterator i = resolvers.iterator(); + while ( i.hasNext() ) { + final DialectResolver resolver = ( DialectResolver ) i.next(); + try { + Dialect dialect = resolver.resolveDialect( metaData ); + if ( dialect != null ) { + return dialect; + } + } + catch ( JDBCConnectionException e ) { + throw e; + } + catch ( Throwable t ) { + LOG.subResolverException(t.getMessage()); + } + } + return null; + } + + /** + * Add a resolver at the end of the underlying resolver list. The resolver added by this method is at lower + * priority than any other existing resolvers. + * + * @param resolver The resolver to add. + */ + public void addResolver(DialectResolver resolver) { + resolvers.add( resolver ); + } + + /** + * Add a resolver at the beginning of the underlying resolver list. The resolver added by this method is at higher + * priority than any other existing resolvers. + * + * @param resolver The resolver to add. + */ + 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 new file mode 100644 index 0000000000..b7fd38d74d --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/resolver/StandardDialectResolver.java @@ -0,0 +1,164 @@ +/* + * 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.dialect.resolver; + +import static org.jboss.logging.Logger.Level.WARN; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import org.hibernate.dialect.DB2Dialect; +import org.hibernate.dialect.DerbyDialect; +import org.hibernate.dialect.Dialect; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.dialect.HSQLDialect; +import org.hibernate.dialect.InformixDialect; +import org.hibernate.dialect.Ingres10Dialect; +import org.hibernate.dialect.Ingres9Dialect; +import org.hibernate.dialect.IngresDialect; +import org.hibernate.dialect.MySQLDialect; +import org.hibernate.dialect.Oracle10gDialect; +import org.hibernate.dialect.Oracle8iDialect; +import org.hibernate.dialect.Oracle9iDialect; +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. + * + * @author Steve Ebersole + */ +public class StandardDialectResolver extends AbstractDialectResolver{ + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StandardDialectResolver.class.getPackage().getName()); + + @Override + protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { + String databaseName = metaData.getDatabaseProductName(); + int databaseMajorVersion = metaData.getDatabaseMajorVersion(); + + if ( "HSQL Database Engine".equals( databaseName ) ) { + return new HSQLDialect(); + } + + if ( "H2".equals( databaseName ) ) { + return new H2Dialect(); + } + + if ( "MySQL".equals( databaseName ) ) { + return new MySQLDialect(); + } + + if ( "PostgreSQL".equals( databaseName ) ) { + return new PostgreSQLDialect(); + } + + if ( "Apache Derby".equals( databaseName ) ) { + return new DerbyDialect(); + } + + if ( "ingres".equalsIgnoreCase( databaseName ) ) { + switch( databaseMajorVersion ) { + case 9: + int databaseMinorVersion = metaData.getDatabaseMinorVersion(); + if (databaseMinorVersion > 2) { + return new Ingres9Dialect(); + } + return new IngresDialect(); + case 10: + LOG.unsupportedIngresVersion(); + return new Ingres10Dialect(); + default: + LOG.unknownIngresVersion(databaseMajorVersion); + } + return new IngresDialect(); + } + + if ( databaseName.startsWith( "Microsoft SQL Server" ) ) { + return new SQLServerDialect(); + } + + if ( "Sybase SQL Server".equals( databaseName ) || "Adaptive Server Enterprise".equals( databaseName ) ) { + return new SybaseASE15Dialect(); + } + + if ( databaseName.startsWith( "Adaptive Server Anywhere" ) ) { + return new SybaseAnywhereDialect(); + } + + if ( "Informix Dynamic Server".equals( databaseName ) ) { + return new InformixDialect(); + } + + if ( databaseName.startsWith( "DB2/" ) ) { + return new DB2Dialect(); + } + + if ( "Oracle".equals( databaseName ) ) { + switch ( databaseMajorVersion ) { + case 11: + LOG.unsupportedOracleVersion(); + return new Oracle10gDialect(); + case 10: + return new Oracle10gDialect(); + case 9: + return new Oracle9iDialect(); + case 8: + return new Oracle8iDialect(); + default: + LOG.unknownOracleVersion(databaseMajorVersion); + } + } + + 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 56b5bcb939..44c82b7168 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/ActionQueue.java @@ -23,6 +23,9 @@ */ 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; @@ -33,10 +36,6 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.action.AfterTransactionCompletionProcess; @@ -52,6 +51,10 @@ 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. @@ -64,7 +67,8 @@ import org.hibernate.type.Type; */ public class ActionQueue { - private static final Logger log = LoggerFactory.getLogger( ActionQueue.class ); + static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ActionQueue.class.getPackage().getName()); private static final int INIT_QUEUE_LIST_SIZE = 5; private SessionImplementor session; @@ -249,9 +253,7 @@ public class ActionQueue { final Serializable[] spaces = action.getPropertySpaces(); for ( Serializable space : spaces ) { if ( tableSpaces.contains( space ) ) { - if ( log.isDebugEnabled() ) { - log.debug( "changes must be flushed to space: " + space ); - } + LOG.changesMustBeFlushed(space); return true; } } @@ -299,7 +301,8 @@ public class ActionQueue { * * @return a string representation of the object. */ - public String toString() { + @Override + public String toString() { return new StringBuffer() .append( "ActionQueue[insertions=" ).append( insertions ) .append( " updates=" ).append( updates ) @@ -412,45 +415,45 @@ public class ActionQueue { * @throws IOException Indicates an error writing to the stream */ public void serialize(ObjectOutputStream oos) throws IOException { - log.trace( "serializing action-queue" ); + LOG.serializingActionQueue(); int queueSize = insertions.size(); - log.trace( "starting serialization of [" + queueSize + "] insertions entries" ); + LOG.serializingInsertions(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( insertions.get( i ) ); } queueSize = deletions.size(); - log.trace( "starting serialization of [" + queueSize + "] deletions entries" ); + LOG.serializingDeletions(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( deletions.get( i ) ); } queueSize = updates.size(); - log.trace( "starting serialization of [" + queueSize + "] updates entries" ); + LOG.serializingUpdates(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( updates.get( i ) ); } queueSize = collectionUpdates.size(); - log.trace( "starting serialization of [" + queueSize + "] collectionUpdates entries" ); + LOG.serializingCollectionUpdates(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionUpdates.get( i ) ); } queueSize = collectionRemovals.size(); - log.trace( "starting serialization of [" + queueSize + "] collectionRemovals entries" ); + LOG.serializingCollectionRemovals(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionRemovals.get( i ) ); } queueSize = collectionCreations.size(); - log.trace( "starting serialization of [" + queueSize + "] collectionCreations entries" ); + LOG.serializingCollectionCreations(queueSize); oos.writeInt( queueSize ); for ( int i = 0; i < queueSize; i++ ) { oos.writeObject( collectionCreations.get( i ) ); @@ -473,46 +476,46 @@ public class ActionQueue { public static ActionQueue deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { - log.trace( "deserializing action-queue" ); + LOG.deserializingActionQueue(); ActionQueue rtn = new ActionQueue( session ); int queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] insertions entries" ); + LOG.deserializingInsertions(queueSize); rtn.insertions = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.insertions.add( ois.readObject() ); } queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] deletions entries" ); + LOG.deserializingDeletions(queueSize); rtn.deletions = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.deletions.add( ois.readObject() ); } queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] updates entries" ); + LOG.deserializingUpdates(queueSize); rtn.updates = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.updates.add( ois.readObject() ); } queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] collectionUpdates entries" ); + LOG.deserializingCollectionUpdates(queueSize); rtn.collectionUpdates = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionUpdates.add( ois.readObject() ); } queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] collectionRemovals entries" ); + LOG.deserializingCollectionRemovals(queueSize); rtn.collectionRemovals = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionRemovals.add( ois.readObject() ); } queueSize = ois.readInt(); - log.trace( "starting deserialization of [" + queueSize + "] collectionCreations entries" ); + LOG.deserializingCollectionCreations(queueSize); rtn.collectionCreations = new ArrayList( queueSize ); for ( int i = 0; i < queueSize; i++ ) { rtn.collectionCreations.add( ois.readObject() ); @@ -591,7 +594,7 @@ public class ActionQueue { process.doAfterTransactionCompletion( success, session ); } catch ( CacheException ce ) { - log.error( "could not release a cache lock", ce ); + LOG.unableToReleaseCacheLock(ce); // continue loop } catch ( Exception e ) { @@ -730,4 +733,74 @@ 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 6189ce543a..51015a316d 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Cascade.java @@ -23,14 +23,12 @@ */ package org.hibernate.engine; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Stack; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.collection.PersistentCollection; @@ -44,6 +42,10 @@ 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 @@ -97,8 +99,7 @@ public final class Cascade { */ public static final int BEFORE_MERGE = 0; - - private static final Logger log = LoggerFactory.getLogger( Cascade.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Cascade.class.getPackage().getName()); private int cascadeTo; @@ -141,9 +142,7 @@ public final class Cascade { throws HibernateException { if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { // performance opt - if ( log.isTraceEnabled() ) { - log.trace( "processing cascade " + action + " for: " + persister.getEntityName() ); - } + LOG.processingCascade(action, persister.getEntityName()); Type[] types = persister.getPropertyTypes(); CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles(); @@ -179,9 +178,7 @@ public final class Cascade { } } - if ( log.isTraceEnabled() ) { - log.trace( "done processing cascade " + action + " for: " + persister.getEntityName() ); - } + LOG.processingCascadeEnded(action, persister.getEntityName()); } } @@ -250,10 +247,10 @@ public final class Cascade { } if ( loadedValue != null ) { final String entityName = entry.getPersister().getEntityName(); - if ( log.isTraceEnabled() ) { + if (LOG.isTraceEnabled()) { final Serializable id = entry.getPersister().getIdentifier( loadedValue, eventSource ); final String description = MessageHelper.infoString( entityName, id ); - log.trace( "deleting orphaned entity instance: " + description ); + LOG.deletingOrphanedEntity(description); } eventSource.delete( entityName, loadedValue, false, new HashSet() ); } @@ -411,52 +408,44 @@ public final class Cascade { // we can't cascade to non-embedded elements boolean embeddedElements = eventSource.getEntityMode()!=EntityMode.DOM4J || ( (EntityType) collectionType.getElementType( eventSource.getFactory() ) ).isEmbeddedInXML(); - - boolean reallyDoCascade = style.reallyDoCascade(action) && + + boolean reallyDoCascade = style.reallyDoCascade(action) && embeddedElements && child!=CollectionType.UNFETCHED_COLLECTION; - + if ( reallyDoCascade ) { - if ( log.isTraceEnabled() ) { - log.trace( "cascade " + action + " for collection: " + collectionType.getRole() ); - } - + LOG.cascadeActionForCollection(action, collectionType.getRole()); + Iterator iter = action.getCascadableChildrenIterator(eventSource, collectionType, child); while ( iter.hasNext() ) { cascadeProperty( parent, - iter.next(), + iter.next(), elemType, style, null, - anything, - isCascadeDeleteEnabled + anything, + isCascadeDeleteEnabled ); } - - if ( log.isTraceEnabled() ) { - log.trace( "done cascade " + action + " for collection: " + collectionType.getRole() ); - } + + LOG.cascadeActionForColectionEnded(action, collectionType.getRole()); } - - final boolean deleteOrphans = style.hasOrphanDelete() && - action.deleteOrphans() && - elemType.isEntityType() && + + final boolean deleteOrphans = style.hasOrphanDelete() && + action.deleteOrphans() && + elemType.isEntityType() && child instanceof PersistentCollection; //a newly instantiated collection can't have orphans - + if ( deleteOrphans ) { // handle orphaned entities!! - if ( log.isTraceEnabled() ) { - log.trace( "deleting orphans for collection: " + collectionType.getRole() ); - } - + LOG.deletingOrphansForCollection(collectionType.getRole()); + // we can do the cast since orphan-delete does not apply to: // 1. newly instantiated collections // 2. arrays (we can't track orphans for detached arrays) final String entityName = collectionType.getAssociatedEntityName( eventSource.getFactory() ); deleteOrphans( entityName, (PersistentCollection) child ); - - if ( log.isTraceEnabled() ) { - log.trace( "done deleting orphans for collection: " + collectionType.getRole() ); - } + + LOG.deletingOrphansForCollectionEnded(collectionType.getRole()); } } @@ -468,24 +457,60 @@ public final class Cascade { final Collection orphans; if ( pc.wasInitialized() ) { CollectionEntry ce = eventSource.getPersistenceContext().getCollectionEntry(pc); - orphans = ce==null ? + orphans = ce==null ? CollectionHelper.EMPTY_COLLECTION : ce.getOrphans(entityName, pc); } else { orphans = pc.getQueuedOrphans(entityName); } - + final Iterator orphanIter = orphans.iterator(); while ( orphanIter.hasNext() ) { Object orphan = orphanIter.next(); if (orphan!=null) { - if ( log.isTraceEnabled() ) { - log.trace("deleting orphaned entity instance: " + entityName); - } + LOG.deletingOrphanedEntity(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 08342b0884..4989b8b3c9 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/CascadingAction.java @@ -24,24 +24,26 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.LockOptions; import org.hibernate.ReplicationMode; import org.hibernate.TransientObjectException; -import org.hibernate.LockOptions; -import org.hibernate.proxy.HibernateProxy; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.collection.PersistentCollection; import org.hibernate.event.EventSource; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.proxy.HibernateProxy; import org.hibernate.type.CollectionType; -import org.hibernate.type.Type; 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 @@ -50,7 +52,8 @@ import org.hibernate.type.EntityType; */ public abstract class CascadingAction { - private static final Logger log = LoggerFactory.getLogger( CascadingAction.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CascadingAction.class.getPackage().getName()); // the CascadingAction contract ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -137,22 +140,24 @@ public abstract class CascadingAction { * @see org.hibernate.Session#delete(Object) */ public static final CascadingAction DELETE = 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 { - if ( log.isTraceEnabled() ) { - log.trace("cascading to delete: " + entityName); - } + LOG.cascadingToDelete(entityName); session.delete( entityName, child, isCascadeDeleteEnabled, ( Set ) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // delete does cascade to uninitialized collections return CascadingAction.getAllElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { // orphans should be deleted during delete return true; } - public String toString() { + @Override + public String toString() { return "ACTION_DELETE"; } }; @@ -161,11 +166,10 @@ public abstract class CascadingAction { * @see org.hibernate.Session#lock(Object, LockMode) */ public static final CascadingAction LOCK = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to lock: " + entityName ); - } + LOG.cascadingToLock(entityName); LockMode lockMode = LockMode.NONE; LockOptions lr = new LockOptions(); if ( anything instanceof LockOptions) { @@ -178,15 +182,18 @@ public abstract class CascadingAction { lr.setLockMode(lockMode); session.buildLockRequest(lr).lock(entityName, child); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // lock doesn't cascade to uninitialized collections return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { //TODO: should orphans really be deleted during lock??? return false; } - public String toString() { + @Override + public String toString() { return "ACTION_LOCK"; } }; @@ -195,21 +202,23 @@ public abstract class CascadingAction { * @see org.hibernate.Session#refresh(Object) */ public static final CascadingAction REFRESH = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to refresh: " + entityName ); - } + LOG.cascadingToRefresh(entityName); session.refresh( child, (Map) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // refresh doesn't cascade to uninitialized collections return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { return false; } - public String toString() { + @Override + public String toString() { return "ACTION_REFRESH"; } }; @@ -218,24 +227,27 @@ public abstract class CascadingAction { * @see org.hibernate.Session#evict(Object) */ public static final CascadingAction EVICT = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to evict: " + entityName ); - } + LOG.cascadingToEvict(entityName); session.evict(child); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // evicts don't cascade to uninitialized collections return 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_EVICT"; } }; @@ -244,25 +256,28 @@ public abstract class CascadingAction { * @see org.hibernate.Session#saveOrUpdate(Object) */ public static final CascadingAction SAVE_UPDATE = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to saveOrUpdate: " + entityName ); - } + LOG.cascadingToSaveOrUpdate(entityName); session.saveOrUpdate(entityName, child); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // saves / updates don't cascade to uninitialized collections return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { // orphans should be deleted during save/update return true; } - public boolean performOnLazyProperty() { + @Override + public boolean performOnLazyProperty() { return false; } - public String toString() { + @Override + public String toString() { return "ACTION_SAVE_UPDATE"; } }; @@ -271,23 +286,25 @@ public abstract class CascadingAction { * @see org.hibernate.Session#merge(Object) */ public static final CascadingAction MERGE = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to merge: " + entityName ); - } + LOG.cascadingToMerge(entityName); session.merge( entityName, child, (Map) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // merges don't cascade to uninitialized collections // //TODO: perhaps this does need to cascade after all.... return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { // orphans should not be deleted during merge?? return false; } - public String toString() { + @Override + public String toString() { return "ACTION_MERGE"; } }; @@ -297,22 +314,24 @@ public abstract class CascadingAction { */ public static final CascadingAction SAVE_UPDATE_COPY = new CascadingAction() { // for deprecated saveOrUpdateCopy() - 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to saveOrUpdateCopy: " + entityName ); - } + LOG.cascadingToSaveOrUpdateCopy(entityName); session.saveOrUpdateCopy( entityName, child, (Map) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // saves / updates don't cascade to uninitialized collections return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { // orphans should not be deleted during copy?? return false; } - public String toString() { + @Override + public String toString() { return "ACTION_SAVE_UPDATE_COPY"; } }; @@ -321,24 +340,27 @@ public abstract class CascadingAction { * @see org.hibernate.Session#persist(Object) */ public static final CascadingAction PERSIST = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to persist: " + entityName ); - } + LOG.cascadingToPersist(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.getAllElementsIterator(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"; } }; @@ -349,24 +371,27 @@ public abstract class CascadingAction { * @see org.hibernate.Session#persist(Object) */ public static final CascadingAction PERSIST_ON_FLUSH = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to persistOnFlush: " + entityName ); - } + LOG.cascadingToPersistOnFlush(entityName); session.persistOnFlush( 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 true; } - public boolean requiresNoCascadeChecking() { + @Override + public boolean requiresNoCascadeChecking() { return true; } - public void noCascade( + @Override + public void noCascade( EventSource session, Object child, Object parent, @@ -393,7 +418,8 @@ public abstract class CascadingAction { } } } - public boolean performOnLazyProperty() { + @Override + public boolean performOnLazyProperty() { return false; } @@ -402,7 +428,8 @@ public abstract class CascadingAction { return entry != null && (entry.getStatus() == Status.MANAGED || entry.getStatus() == Status.READ_ONLY); } - public String toString() { + @Override + public String toString() { return "ACTION_PERSIST_ON_FLUSH"; } }; @@ -411,21 +438,23 @@ public abstract class CascadingAction { * @see org.hibernate.Session#replicate(Object, org.hibernate.ReplicationMode) */ public static final CascadingAction REPLICATE = 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 { - if ( log.isTraceEnabled() ) { - log.trace( "cascading to replicate: " + entityName ); - } + LOG.cascadingToReplicate(entityName); session.replicate( entityName, child, (ReplicationMode) anything ); } - public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { + @Override + public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) { // replicate does cascade to uninitialized collections return getLoadedElementsIterator(session, collectionType, collection); } - public boolean deleteOrphans() { + @Override + public boolean deleteOrphans() { return false; //I suppose? } - public String toString() { + @Override + public String toString() { return "ACTION_REPLICATE"; } }; @@ -469,4 +498,50 @@ public abstract class CascadingAction { 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 b4f11a53c0..251fca577b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/CollectionEntry.java @@ -24,45 +24,48 @@ */ package org.hibernate.engine; -import java.io.Serializable; -import java.io.ObjectOutputStream; +import static org.jboss.logging.Logger.Level.DEBUG; import java.io.IOException; import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; import java.util.Collection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; 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 * of a collection with respect to its persistent state - * + * * @author Gavin King */ public final class CollectionEntry implements Serializable { - private static final Logger log = LoggerFactory.getLogger(CollectionEntry.class); - + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionEntry.class.getPackage().getName()); + //ATTRIBUTES MAINTAINED BETWEEN FLUSH CYCLES - + // session-start/post-flush persistent state private Serializable snapshot; // allow the CollectionSnapshot to be serialized private String role; - - // "loaded" means the reference that is consistent + + // "loaded" means the reference that is consistent // with the current database state private transient CollectionPersister loadedPersister; private Serializable loadedKey; // ATTRIBUTES USED ONLY DURING FLUSH CYCLE - + // during flush, we navigate the object graph to // collections and decide what to do with them private transient boolean reached; @@ -73,8 +76,8 @@ public final class CollectionEntry implements Serializable { // if we instantiate a collection during the flush() process, // we must ignore it for the rest of the flush() private transient boolean ignore; - - // "current" means the reference that was found during flush() + + // "current" means the reference that was found during flush() private transient CollectionPersister currentPersister; private transient Serializable currentKey; @@ -87,7 +90,7 @@ public final class CollectionEntry implements Serializable { ignore = false; collection.clearDirty(); //a newly wrapped collection is NOT dirty (or we get unnecessary version updates) - + snapshot = persister.isMutable() ? collection.getSnapshot(persister) : null; @@ -98,15 +101,15 @@ public final class CollectionEntry implements Serializable { * For collections just loaded from the database */ public CollectionEntry( - final PersistentCollection collection, - final CollectionPersister loadedPersister, - final Serializable loadedKey, + final PersistentCollection collection, + final CollectionPersister loadedPersister, + final Serializable loadedKey, final boolean ignore ) { this.ignore=ignore; //collection.clearDirty() - + this.loadedKey = loadedKey; setLoadedPersister(loadedPersister); @@ -124,11 +127,11 @@ public final class CollectionEntry implements Serializable { ignore = false; //collection.clearDirty() - + this.loadedKey = loadedKey; setLoadedPersister(loadedPersister); } - + /** * For initialized detached collections */ @@ -141,7 +144,7 @@ public final class CollectionEntry implements Serializable { loadedKey = collection.getKey(); setLoadedPersister( factory.getCollectionPersister( collection.getRole() ) ); - snapshot = collection.getStoredSnapshot(); + snapshot = collection.getStoredSnapshot(); } /** @@ -168,40 +171,36 @@ public final class CollectionEntry implements Serializable { * of the collection elements, if necessary */ private void dirty(PersistentCollection collection) throws HibernateException { - + boolean forceDirty = collection.wasInitialized() && !collection.isDirty() && //optimization getLoadedPersister() != null && getLoadedPersister().isMutable() && //optimization ( collection.isDirectlyAccessible() || getLoadedPersister().getElementType().isMutable() ) && //optimization !collection.equalsSnapshot( getLoadedPersister() ); - + if ( forceDirty ) { collection.dirty(); } - + } public void preFlush(PersistentCollection collection) throws HibernateException { - - boolean nonMutableChange = collection.isDirty() && - getLoadedPersister()!=null && + + boolean nonMutableChange = collection.isDirty() && + getLoadedPersister()!=null && !getLoadedPersister().isMutable(); if (nonMutableChange) { throw new HibernateException( - "changed an immutable collection instance: " + + "changed an immutable collection instance: " + MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() ) ); } - + dirty(collection); - - if ( log.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null ) { - log.debug( - "Collection dirty: " + - MessageHelper.collectionInfoString( getLoadedPersister().getRole(), getLoadedKey() ) - ); - } + + if (LOG.isDebugEnabled() && collection.isDirty() && getLoadedPersister() != null) LOG.collectionDirty(MessageHelper.collectionInfoString(getLoadedPersister().getRole(), + getLoadedKey())); setDoupdate(false); setDoremove(false); @@ -229,22 +228,22 @@ public final class CollectionEntry implements Serializable { } collection.setSnapshot(loadedKey, role, snapshot); } - + /** * Called after execution of an action */ public void afterAction(PersistentCollection collection) { loadedKey = getCurrentKey(); setLoadedPersister( getCurrentPersister() ); - - boolean resnapshot = collection.wasInitialized() && + + boolean resnapshot = collection.wasInitialized() && ( isDoremove() || isDorecreate() || isDoupdate() ); if ( resnapshot ) { - snapshot = loadedPersister==null || !loadedPersister.isMutable() ? - null : + snapshot = loadedPersister==null || !loadedPersister.isMutable() ? + null : collection.getSnapshot(loadedPersister); //re-snapshot } - + collection.postAction(); } @@ -264,7 +263,7 @@ public final class CollectionEntry implements Serializable { loadedPersister = persister; setRole( persister == null ? null : persister.getRole() ); } - + void afterDeserialize(SessionFactoryImplementor factory) { loadedPersister = ( factory == null ? null : factory.getCollectionPersister(role) ); } @@ -336,7 +335,7 @@ public final class CollectionEntry implements Serializable { public void setCurrentKey(Serializable currentKey) { this.currentKey = currentKey; } - + /** * This is only available late during the flush cycle */ @@ -352,11 +351,12 @@ public final class CollectionEntry implements Serializable { this.role = role; } - public String toString() { - String result = "CollectionEntry" + + @Override + public String toString() { + String result = "CollectionEntry" + MessageHelper.collectionInfoString( loadedPersister.getRole(), loadedKey ); if (currentPersister!=null) { - result += "->" + + result += "->" + MessageHelper.collectionInfoString( currentPersister.getRole(), currentKey ); } return result; @@ -365,7 +365,7 @@ public final class CollectionEntry implements Serializable { /** * Get the collection orphans (entities which were removed from the collection) */ - public Collection getOrphans(String entityName, PersistentCollection collection) + public Collection getOrphans(String entityName, PersistentCollection collection) throws HibernateException { if (snapshot==null) { throw new AssertionFailure("no collection snapshot for orphan delete"); @@ -377,7 +377,7 @@ public final class CollectionEntry implements Serializable { //TODO: does this really need to be here? // does the collection already have // it's own up-to-date snapshot? - return collection.wasInitialized() && + return collection.wasInitialized() && ( getLoadedPersister()==null || getLoadedPersister().isMutable() ) && collection.isSnapshotEmpty( getSnapshot() ); } @@ -417,4 +417,15 @@ 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 019c12cc14..1442b07f25 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/Collections.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Collections.java @@ -24,8 +24,9 @@ */ package org.hibernate.engine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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; @@ -33,8 +34,10 @@ import org.hibernate.collection.PersistentCollection; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.CollectionType; - -import java.io.Serializable; +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 @@ -42,9 +45,10 @@ import java.io.Serializable; */ public final class Collections { - private Collections() {} + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Collections.class.getPackage().getName()); - private static final Logger log = LoggerFactory.getLogger(Collections.class); + private Collections() {} /** * record the fact that this collection was dereferenced @@ -71,15 +75,9 @@ public final class Collections { CollectionEntry entry = persistenceContext.getCollectionEntry(coll); final CollectionPersister loadedPersister = entry.getLoadedPersister(); - if ( log.isDebugEnabled() && loadedPersister != null ) - log.debug( - "Collection dereferenced: " + - MessageHelper.collectionInfoString( - loadedPersister, - entry.getLoadedKey(), - session.getFactory() - ) - ); + if (LOG.isDebugEnabled() && loadedPersister != null) LOG.collectionDereferenced(MessageHelper.collectionInfoString(loadedPersister, + entry.getLoadedKey(), + session.getFactory())); // do a check boolean hasOrphanDelete = loadedPersister != null && @@ -135,14 +133,9 @@ public final class Collections { final PersistenceContext persistenceContext = session.getPersistenceContext(); CollectionEntry entry = persistenceContext.getCollectionEntry(coll); - log.debug( - "Found collection with unloaded owner: " + - MessageHelper.collectionInfoString( - entry.getLoadedPersister(), - entry.getLoadedKey(), - session.getFactory() - ) - ); + LOG.foundCollectionWithUnloadedOwner(MessageHelper.collectionInfoString(entry.getLoadedPersister(), + entry.getLoadedKey(), + session.getFactory())); entry.setCurrentPersister( entry.getLoadedPersister() ); entry.setCurrentKey( entry.getLoadedKey() ); @@ -151,14 +144,14 @@ public final class Collections { } - /** - * Initialize the role of the collection. - * - * @param collection The collection to be updated by reachibility. - * @param type The type of the collection. - * @param entity The owner of the collection. - * @throws HibernateException - */ + /** + * 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. + * @throws HibernateException + */ public static void processReachableCollection( PersistentCollection collection, CollectionType type, @@ -178,7 +171,7 @@ public final class Collections { ); } - // The CollectionEntry.isReached() stuff is just to detect any silly users + // The CollectionEntry.isReached() stuff is just to detect any silly users // who set up circular or shared references between/to collections. if ( ce.isReached() ) { // We've been here before @@ -194,15 +187,18 @@ public final class Collections { ce.setCurrentPersister(persister); ce.setCurrentKey( type.getKeyOfOwner(entity, session) ); //TODO: better to pass the id in as an argument? - if ( log.isDebugEnabled() ) { - log.debug( - "Collection found: " + - MessageHelper.collectionInfoString( persister, ce.getCurrentKey(), factory ) + - ", was: " + - MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), factory ) + - ( collection.wasInitialized() ? " (initialized)" : " (uninitialized)" ) - ); - } + 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()); + } prepareCollectionForUpdate( collection, ce, session.getEntityMode(), factory ); @@ -259,7 +255,7 @@ public final class Collections { if ( loadedPersister != null ) { entry.setDoremove(true); // we will need to remove ye olde entries if ( entry.isDorecreate() ) { - log.trace( "Forcing collection initialization" ); + LOG.forcingCollectionInitialization(); collection.forceInitialization(); // force initialize! } } @@ -273,4 +269,34 @@ 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 d1a8681540..d006b6c3e8 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/IdentifierValue.java @@ -24,94 +24,109 @@ */ package org.hibernate.engine; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 an identifier value is an identifier of * a new transient instance or a previously persistent transient instance. * The strategy is determined by the unsaved-value attribute in * the mapping file. - * + * * @author Gavin King */ public class IdentifierValue { - private static final Logger log = LoggerFactory.getLogger(IdentifierValue.class); - + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + IdentifierValue.class.getPackage().getName()); + private final Serializable value; - + /** * Always assume the transient instance is newly instantiated */ public static final IdentifierValue ANY = new IdentifierValue() { - public final Boolean isUnsaved(Serializable id) { - log.trace("id unsaved-value strategy ANY"); + @Override + public final Boolean isUnsaved(Serializable id) { + LOG.idUnsavedValueStrategy("ANY"); return Boolean.TRUE; } - public Serializable getDefaultValue(Serializable currentValue) { + @Override + public Serializable getDefaultValue(Serializable currentValue) { return currentValue; } - public String toString() { + @Override + public String toString() { return "SAVE_ANY"; } }; - + /** * Never assume the transient instance is newly instantiated */ public static final IdentifierValue NONE = new IdentifierValue() { - public final Boolean isUnsaved(Serializable id) { - log.trace("id unsaved-value strategy NONE"); + @Override + public final Boolean isUnsaved(Serializable id) { + LOG.idUnsavedValueStrategy("NONE"); return Boolean.FALSE; } - public Serializable getDefaultValue(Serializable currentValue) { + @Override + public Serializable getDefaultValue(Serializable currentValue) { return currentValue; } - public String toString() { + @Override + public String toString() { return "SAVE_NONE"; } }; - + /** * Assume the transient instance is newly instantiated if the identifier * is null. */ public static final IdentifierValue NULL = new IdentifierValue() { - public final Boolean isUnsaved(Serializable id) { - log.trace("id unsaved-value strategy NULL"); + @Override + public final Boolean isUnsaved(Serializable id) { + LOG.idUnsavedValueStrategy("NULL"); return id==null ? Boolean.TRUE : Boolean.FALSE; } - public Serializable getDefaultValue(Serializable currentValue) { + @Override + public Serializable getDefaultValue(Serializable currentValue) { return null; } - public String toString() { + @Override + public String toString() { return "SAVE_NULL"; } }; - + /** * Assume nothing. */ public static final IdentifierValue UNDEFINED = new IdentifierValue() { - public final Boolean isUnsaved(Serializable id) { - log.trace("id unsaved-value strategy UNDEFINED"); + @Override + public final Boolean isUnsaved(Serializable id) { + LOG.idUnsavedValueStrategy("UNDEFINED"); return null; } - public Serializable getDefaultValue(Serializable currentValue) { + @Override + public Serializable getDefaultValue(Serializable currentValue) { return null; } - public String toString() { + @Override + public String toString() { return "UNDEFINED"; } }; - + protected IdentifierValue() { this.value = null; } - + /** * Assume the transient instance is newly instantiated if * its identifier is null or equal to value @@ -119,20 +134,36 @@ public class IdentifierValue { public IdentifierValue(Serializable value) { this.value = value; } - + /** * Does the given identifier belong to a new instance? */ public Boolean isUnsaved(Serializable id) { - if ( log.isTraceEnabled() ) log.trace("id unsaved-value: " + value); + LOG.idUnsavedValue(value); return id==null || id.equals(value) ? Boolean.TRUE : Boolean.FALSE; } - + public Serializable getDefaultValue(Serializable currentValue) { return value; } - - public String toString() { + + @Override + 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 4c174aa388..5970c748f1 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/ParameterBinder.java @@ -24,15 +24,17 @@ */ package org.hibernate.engine; -import org.hibernate.HibernateException; -import org.hibernate.type.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.PreparedStatement; import java.sql.SQLException; -import java.util.Map; import java.util.Iterator; +import java.util.Map; +import org.hibernate.HibernateException; +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 @@ -40,12 +42,13 @@ import java.util.Iterator; *

    * Ideally would like to move to the parameter handling as it is done in * the hql.ast package. - * + * * @author Steve Ebersole */ public class ParameterBinder { - private static final Logger log = LoggerFactory.getLogger( ParameterBinder.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ParameterBinder.class.getPackage().getName()); public static interface NamedParameterSource { public int[] getNamedParameterLocations(String name); @@ -119,19 +122,26 @@ public class ParameterBinder { TypedValue typedval = ( TypedValue ) e.getValue(); int[] locations = source.getNamedParameterLocations( name ); for ( int i = 0; i < locations.length; i++ ) { - if ( log.isDebugEnabled() ) { - log.debug( "bindNamedParameters() " + - typedval.getValue() + " -> " + name + - " [" + ( locations[i] + start ) + "]" ); - } + LOG.bindNamedParameters(typedval.getValue(), name, locations[i] + start); typedval.getType().nullSafeSet( ps, typedval.getValue(), locations[i] + start, session ); } result += locations.length; } return result; } - else { - return 0; - } + 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 a2ca492422..624a795306 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/QueryParameters.java @@ -24,6 +24,7 @@ */ package org.hibernate.engine; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -31,27 +32,29 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; +import org.hibernate.LockOptions; import org.hibernate.QueryException; import org.hibernate.ScrollMode; -import org.hibernate.LockOptions; -import org.hibernate.impl.FilterImpl; import org.hibernate.dialect.Dialect; import org.hibernate.hql.classic.ParserHelper; +import org.hibernate.impl.FilterImpl; 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 */ public final class QueryParameters { - private static final Logger log = LoggerFactory.getLogger( QueryParameters.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryParameters.class.getPackage().getName()); private Type[] positionalParameterTypes; private Object[] positionalParameterValues; @@ -278,15 +281,9 @@ public final class QueryParameters { public void traceParameters(SessionFactoryImplementor factory) throws HibernateException { Printer print = new Printer( factory ); - if ( positionalParameterValues.length != 0 ) { - log.trace( - "parameters: " + - print.toString( positionalParameterTypes, positionalParameterValues ) - ); - } - if ( namedParameters != null ) { - log.trace( "named parameters: " + print.toString( namedParameters ) ); - } + if (positionalParameterValues.length != 0) LOG.parameters(print.toString(positionalParameterTypes, + positionalParameterValues)); + if (namedParameters != null) LOG.namedParameters(print.toString(namedParameters)); } public boolean isCacheable() { @@ -419,7 +416,7 @@ public final class QueryParameters { public boolean isReadOnly(SessionImplementor session) { return ( isReadOnlyInitialized ? isReadOnly() : - session.getPersistenceContext().isDefaultReadOnly() + session.getPersistenceContext().isDefaultReadOnly() ); } @@ -567,5 +564,18 @@ public final class QueryParameters { 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 cf025f4f8b..cbdb08e3e9 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java @@ -24,6 +24,9 @@ */ 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; import java.io.ObjectInputStream; @@ -35,10 +38,8 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; - +import org.apache.commons.collections.map.AbstractReferenceMap; import org.apache.commons.collections.map.ReferenceMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; import org.hibernate.Hibernate; import org.hibernate.HibernateException; @@ -47,16 +48,20 @@ import org.hibernate.MappingException; import org.hibernate.NonUniqueObjectException; import org.hibernate.PersistentObjectException; import org.hibernate.TransientObjectException; -import org.hibernate.engine.loading.LoadContexts; -import org.hibernate.pretty.MessageHelper; import org.hibernate.collection.PersistentCollection; +import org.hibernate.engine.loading.LoadContexts; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; 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 @@ -74,59 +79,59 @@ public class StatefulPersistenceContext implements PersistenceContext { public static final Object NO_ROW = new MarkerObject( "NO_ROW" ); - private static final Logger log = LoggerFactory.getLogger( StatefulPersistenceContext.class ); - private static final Logger PROXY_WARN_LOG = LoggerFactory.getLogger( StatefulPersistenceContext.class.getName() + ".ProxyWarnLog" ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StatefulPersistenceContext.class.getPackage().getName()); private static final int INIT_COLL_SIZE = 8; private SessionImplementor session; - + // Loaded entity instances, by EntityKey private Map entitiesByKey; // Loaded entity instances, by EntityUniqueKey private Map entitiesByUniqueKey; - + // Identity map of EntityEntry instances, by the entity instance private Map entityEntries; - + // Entity proxies, by EntityKey private Map proxiesByKey; - + // Snapshots of current database state for entities // that have *not* been loaded private Map entitySnapshotsByKey; - + // Identity map of array holder ArrayHolder instances, by the array instance private Map arrayHolders; - + // Identity map of CollectionEntry instances, by the collection wrapper private Map collectionEntries; - + // Collection wrappers, by the CollectionKey private Map collectionsByKey; //key=CollectionKey, value=PersistentCollection - + // Set of EntityKeys of deleted objects private HashSet nullifiableEntityKeys; - + // properties that we have tried to load, and not found in the database private HashSet nullAssociations; - + // A list of collection wrappers that were instantiating during result set // processing, that we will need to initialize at the end of the query private List nonlazyCollections; - + // A container for collections we load up when the owning entity is not // yet loaded ... for now, this is purely transient! private Map unownedCollections; - + // Parent entities cache by their child for cascading - // May be empty or not contains all relation + // May be empty or not contains all relation private Map parentsByChild; - + private int cascading = 0; private int loadCounter = 0; private boolean flushing = false; - + private boolean defaultReadOnly = false; private boolean hasNonReadOnlyEntities = false; @@ -145,7 +150,7 @@ public class StatefulPersistenceContext implements PersistenceContext { entitiesByKey = new HashMap( INIT_COLL_SIZE ); entitiesByUniqueKey = new HashMap( INIT_COLL_SIZE ); - proxiesByKey = new ReferenceMap( ReferenceMap.HARD, ReferenceMap.WEAK ); + proxiesByKey = new ReferenceMap( AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK ); entitySnapshotsByKey = new HashMap( INIT_COLL_SIZE ); entityEntries = IdentityMap.instantiateSequenced( INIT_COLL_SIZE ); @@ -153,7 +158,7 @@ public class StatefulPersistenceContext implements PersistenceContext { collectionsByKey = new HashMap( INIT_COLL_SIZE ); arrayHolders = IdentityMap.instantiate( INIT_COLL_SIZE ); parentsByChild = IdentityMap.instantiateSequenced( INIT_COLL_SIZE ); - + nullifiableEntityKeys = new HashSet(); initTransientState(); @@ -167,7 +172,7 @@ public class StatefulPersistenceContext implements PersistenceContext { public boolean isStateless() { return false; } - + public SessionImplementor getSession() { return session; } @@ -185,7 +190,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } unownedCollections.put(key, collection); } - + public PersistentCollection useUnownedCollection(CollectionKey key) { if (unownedCollections==null) { return null; @@ -194,7 +199,7 @@ public class StatefulPersistenceContext implements PersistenceContext { return (PersistentCollection) unownedCollections.remove(key); } } - + /** * Get the BatchFetchQueue, instantiating one if * necessary. @@ -256,12 +261,12 @@ public class StatefulPersistenceContext implements PersistenceContext { public boolean hasNonReadOnlyEntities() { return hasNonReadOnlyEntities; } - + public void setEntryStatus(EntityEntry entry, Status status) { entry.setStatus(status); setHasNonReadOnlyEnties(status); } - + private void setHasNonReadOnlyEnties(Status status) { if ( status==Status.DELETED || status==Status.MANAGED || status==Status.SAVING ) { hasNonReadOnlyEntities = true; @@ -279,7 +284,7 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * Get the current state of the entity as known to the underlying - * database, or null if there is no corresponding row + * database, or null if there is no corresponding row */ public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) throws HibernateException { @@ -361,7 +366,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } /** - * Get the entity instance associated with the given + * Get the entity instance associated with the given * EntityKey */ public Object getEntity(EntityKey key) { @@ -449,12 +454,12 @@ public class StatefulPersistenceContext implements PersistenceContext { final LockMode lockMode, final boolean existsInDatabase, final EntityPersister persister, - final boolean disableVersionIncrement, + final boolean disableVersionIncrement, boolean lazyPropertiesAreUnfetched ) { - + addEntity( entityKey, entity ); - + return addEntry( entity, status, @@ -465,14 +470,14 @@ public class StatefulPersistenceContext implements PersistenceContext { lockMode, existsInDatabase, persister, - disableVersionIncrement, + disableVersionIncrement, lazyPropertiesAreUnfetched ); } /** - * Generates an appropriate EntityEntry instance and adds it + * Generates an appropriate EntityEntry instance and adds it * to the event source's internal caches. */ public EntityEntry addEntry( @@ -485,9 +490,9 @@ public class StatefulPersistenceContext implements PersistenceContext { final LockMode lockMode, final boolean existsInDatabase, final EntityPersister persister, - final boolean disableVersionIncrement, + final boolean disableVersionIncrement, boolean lazyPropertiesAreUnfetched) { - + EntityEntry e = new EntityEntry( status, loadedState, @@ -502,7 +507,7 @@ public class StatefulPersistenceContext implements PersistenceContext { lazyPropertiesAreUnfetched ); entityEntries.put(entity, e); - + setHasNonReadOnlyEnties(status); return e; } @@ -514,7 +519,7 @@ public class StatefulPersistenceContext implements PersistenceContext { public boolean containsProxy(Object entity) { return proxiesByKey.containsValue( entity ); } - + /** * Takes the given object and, if it represents a proxy, reassociates it with this event source. * @@ -526,7 +531,7 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( value instanceof ElementWrapper ) { value = ( (ElementWrapper) value ).getElement(); } - + if ( !Hibernate.isInitialized(value) ) { HibernateProxy proxy = (HibernateProxy) value; LazyInitializer li = proxy.getHibernateLazyInitializer(); @@ -540,15 +545,15 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * If a deleted entity instance is re-saved, and it has a proxy, we need to - * reset the identifier of the proxy + * reset the identifier of the proxy */ public void reassociateProxy(Object value, Serializable id) throws MappingException { if ( value instanceof ElementWrapper ) { value = ( (ElementWrapper) value ).getElement(); } - + if ( value instanceof HibernateProxy ) { - if ( log.isDebugEnabled() ) log.debug("setting proxy identifier: " + id); + LOG.settingProxyIdentifier(id); HibernateProxy proxy = (HibernateProxy) value; LazyInitializer li = proxy.getHibernateLazyInitializer(); li.setIdentifier(id); @@ -583,7 +588,7 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( maybeProxy instanceof ElementWrapper ) { maybeProxy = ( (ElementWrapper) maybeProxy ).getElement(); } - + if ( maybeProxy instanceof HibernateProxy ) { HibernateProxy proxy = (HibernateProxy) maybeProxy; LazyInitializer li = proxy.getHibernateLazyInitializer(); @@ -611,7 +616,7 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( maybeProxy instanceof ElementWrapper ) { maybeProxy = ( (ElementWrapper) maybeProxy ).getElement(); } - + if ( maybeProxy instanceof HibernateProxy ) { HibernateProxy proxy = (HibernateProxy) maybeProxy; LazyInitializer li = proxy.getHibernateLazyInitializer(); @@ -654,18 +659,12 @@ public class StatefulPersistenceContext implements PersistenceContext { */ public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object) throws HibernateException { - + boolean alreadyNarrow = persister.getConcreteProxyClass( session.getEntityMode() ) .isAssignableFrom( proxy.getClass() ); - + if ( !alreadyNarrow ) { - if ( PROXY_WARN_LOG.isWarnEnabled() ) { - PROXY_WARN_LOG.warn( - "Narrowing proxy to " + - persister.getConcreteProxyClass( session.getEntityMode() ) + - " - this operation breaks ==" - ); - } + if (LOG.isEnabled(WARN)) LOG.narrowingProxy(persister.getConcreteProxyClass(session.getEntityMode())); if ( object != null ) { proxiesByKey.remove(key); @@ -685,19 +684,19 @@ public class StatefulPersistenceContext implements PersistenceContext { ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig ); } return proxy; - } + } } else { - + if ( object != null ) { LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer(); li.setImplementation(object); } - + return proxy; - + } - + } /** @@ -705,7 +704,7 @@ public class StatefulPersistenceContext implements PersistenceContext { * third argument (the entity associated with the key) if no proxy exists. Init * the proxy to the target implementation, if necessary. */ - public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) + public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) throws HibernateException { if ( !persister.hasProxy() ) return impl; Object proxy = proxiesByKey.get(key); @@ -845,7 +844,7 @@ public class StatefulPersistenceContext implements PersistenceContext { * add an (initialized) collection that was created by another session and passed * into update() (ie. one with a snapshot and existing state on the database) */ - public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection) + public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection) throws HibernateException { if ( collection.isUnreferenced() ) { //treat it just like a new collection @@ -867,14 +866,14 @@ public class StatefulPersistenceContext implements PersistenceContext { addCollection(collection, ce, id); return ce; } - + /** * Get the collection instance associated with the CollectionKey */ public PersistentCollection getCollection(CollectionKey collectionKey) { return (PersistentCollection) collectionsByKey.get(collectionKey); } - + /** * Register a collection for non-lazy loading at the end of the * two-phase load @@ -890,7 +889,7 @@ public class StatefulPersistenceContext implements PersistenceContext { */ public void initializeNonLazyCollections() throws HibernateException { if ( loadCounter == 0 ) { - log.debug( "initializing non-lazy collections" ); + LOG.initializingNonLazyCollections(); //do this work only at the very highest level of the load loadCounter++; //don't let this method be called recursively try { @@ -917,7 +916,7 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * Register a PersistentCollection object for an array. - * Associates a holder with an array - MUST be called after loading + * Associates a holder with an array - MUST be called after loading * array, since the array instance is not created until endLoad(). */ public void addCollectionHolder(PersistentCollection holder) { @@ -999,7 +998,7 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * Record the fact that an entity does not exist in the database - * + * * @param key the primary key of the entity */ /*public void addNonExistantEntityKey(EntityKey key) { @@ -1008,7 +1007,7 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * Record the fact that an entity does not exist in the database - * + * * @param key a unique key of the entity */ /*public void addNonExistantEntityUniqueKey(EntityUniqueKey key) { @@ -1019,7 +1018,7 @@ public class StatefulPersistenceContext implements PersistenceContext { nonExistantEntityKeys.remove(key); }*/ - /** + /** * Retrieve the set of EntityKeys representing nullifiable references */ public HashSet getNullifiableEntityKeys() { @@ -1104,7 +1103,8 @@ public class StatefulPersistenceContext implements PersistenceContext { * * @return a string representation of the object. */ - public String toString() { + @Override + public String toString() { return new StringBuffer() .append("PersistenceContext[entityKeys=") .append(entitiesByKey.keySet()) @@ -1258,7 +1258,7 @@ public class StatefulPersistenceContext implements PersistenceContext { .getEntityPersister(entity); CollectionPersister cp = session.getFactory() .getCollectionPersister(entity + '.' + property); - + // try cache lookup first Object parent = parentsByChild.get(childEntity); if (parent != null) { @@ -1290,9 +1290,9 @@ public class StatefulPersistenceContext implements PersistenceContext { EntityEntry ee = (EntityEntry) me.getValue(); if ( persister.isSubclassEntityName( ee.getEntityName() ) ) { Object instance = me.getKey(); - + Object index = getIndexInParent(property, childEntity, persister, cp, instance); - + if (index==null && mergeMap!=null) { Object unmergedInstance = mergeMap.get(instance); Object unmergedChild = mergeMap.get(childEntity); @@ -1300,20 +1300,20 @@ public class StatefulPersistenceContext implements PersistenceContext { index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance); } } - + if (index!=null) return index; } } return null; } - + private Object getIndexInParent( - String property, - Object childEntity, - EntityPersister persister, + String property, + Object childEntity, + EntityPersister persister, CollectionPersister collectionPersister, Object potentialParent - ){ + ){ Object collection = persister.getPropertyValue( potentialParent, property, session.getEntityMode() ); if ( collection!=null && Hibernate.isInitialized(collection) ) { return collectionPersister.getCollectionType().indexOf(collection, childEntity); @@ -1322,7 +1322,7 @@ public class StatefulPersistenceContext implements PersistenceContext { return null; } } - + /** * Record the fact that the association belonging to the keyed * entity is null. @@ -1330,14 +1330,14 @@ public class StatefulPersistenceContext implements PersistenceContext { public void addNullProperty(EntityKey ownerKey, String propertyName) { nullAssociations.add( new AssociationKey(ownerKey, propertyName) ); } - + /** * Is the association property belonging to the keyed entity null? */ public boolean isPropertyNull(EntityKey ownerKey, String propertyName) { return nullAssociations.contains( new AssociationKey(ownerKey, propertyName) ); } - + private void clearNullProperties() { nullAssociations.clear(); } @@ -1435,13 +1435,13 @@ public class StatefulPersistenceContext implements PersistenceContext { * @throws IOException serialization errors. */ public void serialize(ObjectOutputStream oos) throws IOException { - log.trace( "serializing persistent-context" ); + LOG.serializingPersistentContext(); oos.writeBoolean( defaultReadOnly ); oos.writeBoolean( hasNonReadOnlyEntities ); oos.writeInt( entitiesByKey.size() ); - log.trace( "starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries" ); + LOG.serializingEntitiesByKey(entitiesByKey.size()); Iterator itr = entitiesByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1450,7 +1450,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entitiesByUniqueKey.size() ); - log.trace( "starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries" ); + LOG.serializingEntitiesByUniqueKey(entitiesByUniqueKey.size()); itr = entitiesByUniqueKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1459,7 +1459,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( proxiesByKey.size() ); - log.trace( "starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries" ); + LOG.serializingProxiesByKey(proxiesByKey.size()); itr = proxiesByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1468,7 +1468,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entitySnapshotsByKey.size() ); - log.trace( "starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries" ); + LOG.serializingEntitySnapshotsByKey(entitySnapshotsByKey.size()); itr = entitySnapshotsByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1477,7 +1477,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( entityEntries.size() ); - log.trace( "starting serialization of [" + entityEntries.size() + "] entityEntries entries" ); + LOG.serializingEntityEntries(entityEntries.size()); itr = entityEntries.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1486,7 +1486,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( collectionsByKey.size() ); - log.trace( "starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries" ); + LOG.serializingCollectionsByKey(collectionsByKey.size()); itr = collectionsByKey.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1495,7 +1495,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( collectionEntries.size() ); - log.trace( "starting serialization of [" + collectionEntries.size() + "] collectionEntries entries" ); + LOG.serializingCollectionEntries(collectionEntries.size()); itr = collectionEntries.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1504,7 +1504,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( arrayHolders.size() ); - log.trace( "starting serialization of [" + arrayHolders.size() + "] arrayHolders entries" ); + LOG.serializingArrayHolders(arrayHolders.size()); itr = arrayHolders.entrySet().iterator(); while ( itr.hasNext() ) { Map.Entry entry = ( Map.Entry ) itr.next(); @@ -1513,7 +1513,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } oos.writeInt( nullifiableEntityKeys.size() ); - log.trace( "starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKeys entries" ); + LOG.serializingNullifiableEntityKeys(nullifiableEntityKeys.size()); itr = nullifiableEntityKeys.iterator(); while ( itr.hasNext() ) { EntityKey entry = ( EntityKey ) itr.next(); @@ -1524,7 +1524,7 @@ public class StatefulPersistenceContext implements PersistenceContext { public static StatefulPersistenceContext deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { - log.trace( "deserializing persistent-context" ); + LOG.deserializingPersistentContext(); StatefulPersistenceContext rtn = new StatefulPersistenceContext( session ); // during deserialization, we need to reconnect all proxies and @@ -1538,44 +1538,41 @@ public class StatefulPersistenceContext implements PersistenceContext { rtn.hasNonReadOnlyEntities = ois.readBoolean(); int count = ois.readInt(); - log.trace( "staring deserialization of [" + count + "] entitiesByKey entries" ); + LOG.deserializingEntitiesByKey(count); 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.trace( "staring deserialization of [" + count + "] entitiesByUniqueKey entries" ); + LOG.deserializingEntitiesByUniqueKey(count); 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.trace( "staring deserialization of [" + count + "] proxiesByKey entries" ); - rtn.proxiesByKey = new ReferenceMap( ReferenceMap.HARD, ReferenceMap.WEAK, count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count, .75f ); + LOG.deserializingProxiesByKey(count); + 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 ); Object proxy = ois.readObject(); if ( proxy instanceof HibernateProxy ) { ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setSession( session ); rtn.proxiesByKey.put( ek, proxy ); - } - else { - log.trace( "encountered prunded proxy" ); - } + } else LOG.encounteredPrunedProxy(); // otherwise, the proxy was pruned during the serialization process } count = ois.readInt(); - log.trace( "staring deserialization of [" + count + "] entitySnapshotsByKey entries" ); + LOG.deserializingEntitySnapshotsByKey(count); 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.trace( "staring deserialization of [" + count + "] entityEntries entries" ); + LOG.deserializingEntityEntries(count); rtn.entityEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { Object entity = ois.readObject(); @@ -1584,14 +1581,14 @@ public class StatefulPersistenceContext implements PersistenceContext { } count = ois.readInt(); - log.trace( "staring deserialization of [" + count + "] collectionsByKey entries" ); + LOG.deserializingCollectionsByKey(count); 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.trace( "staring deserialization of [" + count + "] collectionEntries entries" ); + LOG.deserializingCollectionEntries(count); 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(); @@ -1601,14 +1598,14 @@ public class StatefulPersistenceContext implements PersistenceContext { } count = ois.readInt(); - log.trace( "staring deserialization of [" + count + "] arrayHolders entries" ); + LOG.deserializingArrayHolders(count); 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.trace( "staring deserialization of [" + count + "] nullifiableEntityKeys entries" ); + LOG.deserializingNullifiableEntityKeys(count); rtn.nullifiableEntityKeys = new HashSet(); for ( int i = 0; i < count; i++ ) { rtn.nullifiableEntityKeys.add( EntityKey.deserialize( ois, session ) ); @@ -1628,7 +1625,7 @@ public class StatefulPersistenceContext implements PersistenceContext { public void addChildParent(Object child, Object parent) { parentsByChild.put(child, parent); } - + /** * @see org.hibernate.engine.PersistenceContext#removeChildParent(java.lang.Object) */ @@ -1680,4 +1677,106 @@ public class StatefulPersistenceContext implements PersistenceContext { } } + /** + * 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 2f4cb21359..9f4a9b33fd 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java @@ -23,15 +23,13 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; import org.hibernate.CacheMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; -import org.hibernate.proxy.HibernateProxy; import org.hibernate.cache.CacheKey; import org.hibernate.cache.entry.CacheEntry; import org.hibernate.event.PostLoadEvent; @@ -42,66 +40,72 @@ import org.hibernate.intercept.LazyPropertyInitializer; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; 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, * that may be reused by persisters that do not use the Loader * framework - * + * * @author Gavin King */ public final class TwoPhaseLoad { - private static final Logger log = LoggerFactory.getLogger(TwoPhaseLoad.class); - + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TwoPhaseLoad.class.getPackage().getName()); + private TwoPhaseLoad() {} /** * Register the "hydrated" state of an entity instance, after the first step of 2-phase loading. - * + * * Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try * to resolve any associations yet, because there might be other entities waiting to be * read from the JDBC result set we are currently processing */ public static void postHydrate( - final EntityPersister persister, - final Serializable id, - final Object[] values, + final EntityPersister persister, + final Serializable id, + final Object[] values, final Object rowId, - final Object object, + final Object object, final LockMode lockMode, - final boolean lazyPropertiesAreUnfetched, - final SessionImplementor session) + final boolean lazyPropertiesAreUnfetched, + final SessionImplementor session) throws HibernateException { - + Object version = Versioning.getVersion(values, persister); - session.getPersistenceContext().addEntry( - object, + session.getPersistenceContext().addEntry( + object, Status.LOADING, - values, - rowId, - id, - version, - lockMode, - true, - persister, - false, - lazyPropertiesAreUnfetched + values, + rowId, + id, + version, + lockMode, + true, + persister, + false, + lazyPropertiesAreUnfetched ); - - if ( log.isTraceEnabled() && version!=null ) { + + if (LOG.isTraceEnabled() && version != null) { String versionStr = persister.isVersioned() ? persister.getVersionType().toLoggableString( version, session.getFactory() ) : "null"; - log.trace( "Version: " + versionStr ); + LOG.version(versionStr); } - + } /** - * Perform the second step of 2-phase load. Fully initialize the entity + * Perform the second step of 2-phase load. Fully initialize the entity * instance. * * After processing a JDBC result set, we "resolve" all the associations @@ -109,14 +113,14 @@ public final class TwoPhaseLoad { * "hydrated" into an array */ public static void initializeEntity( - final Object entity, + final Object entity, final boolean readOnly, final SessionImplementor session, final PreLoadEvent preLoadEvent, final PostLoadEvent postLoadEvent) throws HibernateException { - + //TODO: Should this be an InitializeEntityEventListener??? (watch out for performance!) - + final PersistenceContext persistenceContext = session.getPersistenceContext(); EntityEntry entityEntry = persistenceContext.getEntry(entity); if ( entityEntry == null ) { @@ -125,13 +129,9 @@ public final class TwoPhaseLoad { EntityPersister persister = entityEntry.getPersister(); Serializable id = entityEntry.getId(); Object[] hydratedState = entityEntry.getLoadedState(); - - if ( log.isDebugEnabled() ) - log.debug( - "resolving associations for " + - MessageHelper.infoString(persister, id, session.getFactory()) - ); - + + if (LOG.isDebugEnabled()) LOG.resolvingAssociations(MessageHelper.infoString(persister, id, session.getFactory())); + Type[] types = persister.getPropertyTypes(); for ( int i = 0; i < hydratedState.length; i++ ) { final Object value = hydratedState[i]; @@ -139,7 +139,7 @@ public final class TwoPhaseLoad { hydratedState[i] = types[i].resolve( value, session, entity ); } } - + //Must occur after resolving identifiers! if ( session.isEventSource() ) { preLoadEvent.setEntity(entity).setState(hydratedState).setId(id).setPersister(persister); @@ -148,33 +148,31 @@ public final class TwoPhaseLoad { listeners[i].onPreLoad(preLoadEvent); } } - + persister.setPropertyValues( entity, hydratedState, session.getEntityMode() ); - + final SessionFactoryImplementor factory = session.getFactory(); if ( persister.hasCache() && session.getCacheMode().isPutEnabled() ) { - - if ( log.isDebugEnabled() ) - log.debug( - "adding entity to second-level cache: " + - MessageHelper.infoString( persister, id, session.getFactory() ) - ); + + if (LOG.isDebugEnabled()) LOG.addingEntityToSecondLevelCache(MessageHelper.infoString(persister, + id, + session.getFactory())); Object version = Versioning.getVersion(hydratedState, persister); CacheEntry entry = new CacheEntry( - hydratedState, - persister, - entityEntry.isLoadedWithLazyPropertiesUnfetched(), - version, - session, + hydratedState, + persister, + entityEntry.isLoadedWithLazyPropertiesUnfetched(), + version, + session, entity ); - CacheKey cacheKey = new CacheKey( - id, - persister.getIdentifierType(), - persister.getRootEntityName(), - session.getEntityMode(), - session.getFactory() + CacheKey cacheKey = new CacheKey( + id, + persister.getIdentifierType(), + persister.getRootEntityName(), + session.getEntityMode(), + session.getFactory() ); // explicit handling of caching for rows just inserted and then somehow forced to be read @@ -219,30 +217,30 @@ public final class TwoPhaseLoad { } } if ( isReallyReadOnly ) { - //no need to take a snapshot - this is a + //no need to take a snapshot - this is a //performance optimization, but not really - //important, except for entities with huge + //important, except for entities with huge //mutable property values persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY); } else { //take a snapshot TypeHelper.deepCopy( - hydratedState, - persister.getPropertyTypes(), - persister.getPropertyUpdateability(), + hydratedState, + persister.getPropertyTypes(), + persister.getPropertyUpdateability(), hydratedState, //after setting values to object, entityMode session ); persistenceContext.setEntryStatus(entityEntry, Status.MANAGED); } - + persister.afterInitialize( - entity, - entityEntry.isLoadedWithLazyPropertiesUnfetched(), + entity, + entityEntry.isLoadedWithLazyPropertiesUnfetched(), session ); - + if ( session.isEventSource() ) { postLoadEvent.setEntity(entity).setId(id).setPersister(persister); PostLoadEventListener[] listeners = session.getListeners().getPostLoadEventListeners(); @@ -250,76 +248,95 @@ public final class TwoPhaseLoad { listeners[i].onPostLoad(postLoadEvent); } } - - if ( log.isDebugEnabled() ) - log.debug( - "done materializing entity " + - MessageHelper.infoString( persister, id, session.getFactory() ) - ); - + + if (LOG.isDebugEnabled()) LOG.doneMaterializingEntity(MessageHelper.infoString(persister, id, session.getFactory())); + if ( factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor().loadEntity( persister.getEntityName() ); } - + } private static boolean useMinimalPuts(SessionImplementor session, EntityEntry entityEntry) { - return ( session.getFactory().getSettings().isMinimalPutsEnabled() && + return ( session.getFactory().getSettings().isMinimalPutsEnabled() && session.getCacheMode()!=CacheMode.REFRESH ) || - ( entityEntry.getPersister().hasLazyProperties() && - entityEntry.isLoadedWithLazyPropertiesUnfetched() && + ( entityEntry.getPersister().hasLazyProperties() && + entityEntry.isLoadedWithLazyPropertiesUnfetched() && entityEntry.getPersister().isLazyPropertiesCacheable() ); } /** - * Add an uninitialized instance of an entity class, as a placeholder to ensure object + * Add an uninitialized instance of an entity class, as a placeholder to ensure object * identity. Must be called before postHydrate(). * * Create a "temporary" entry for a newly instantiated entity. The entity is uninitialized, * but we need the mapping from id to instance in order to guarantee uniqueness. */ public static void addUninitializedEntity( - final EntityKey key, - final Object object, - final EntityPersister persister, + final EntityKey key, + final Object object, + final EntityPersister persister, final LockMode lockMode, - final boolean lazyPropertiesAreUnfetched, + final boolean lazyPropertiesAreUnfetched, final SessionImplementor session ) { session.getPersistenceContext().addEntity( - object, - Status.LOADING, - null, - key, - null, - lockMode, - true, - persister, - false, + object, + Status.LOADING, + null, + key, + null, + lockMode, + true, + persister, + false, lazyPropertiesAreUnfetched ); } public static void addUninitializedCachedEntity( - final EntityKey key, - final Object object, - final EntityPersister persister, + final EntityKey key, + final Object object, + final EntityPersister persister, final LockMode lockMode, final boolean lazyPropertiesAreUnfetched, final Object version, final SessionImplementor session ) { session.getPersistenceContext().addEntity( - object, - Status.LOADING, - null, - key, - version, - lockMode, - true, - persister, - false, + object, + Status.LOADING, + null, + key, + version, + lockMode, + true, + persister, + false, 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 fa2ae7c0fc..1d8efc0505 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/VersionValue.java @@ -24,22 +24,26 @@ */ package org.hibernate.engine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.TRACE; 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 * a new transient instance or a previously persistent transient instance. * The strategy is determined by the unsaved-value attribute in * the mapping file. - * + * * @author Gavin King */ public class VersionValue { - private static final Logger log = LoggerFactory.getLogger(VersionValue.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + VersionValue.class.getPackage().getName()); private final Object value; /** @@ -47,14 +51,17 @@ public class VersionValue { * is null, otherwise assume it is a detached instance. */ public static final VersionValue NULL = new VersionValue() { - public final Boolean isUnsaved(Object version) { - log.trace("version unsaved-value strategy NULL"); + @Override + public final Boolean isUnsaved(Object version) { + LOG.versionUnsavedValueStrategy("NULL"); return version==null ? Boolean.TRUE : Boolean.FALSE; } - public Object getDefaultValue(Object currentValue) { + @Override + public Object getDefaultValue(Object currentValue) { return null; } - public String toString() { + @Override + public String toString() { return "VERSION_SAVE_NULL"; } }; @@ -63,14 +70,17 @@ public class VersionValue { * is null, otherwise defer to the identifier unsaved-value. */ public static final VersionValue UNDEFINED = new VersionValue() { - public final Boolean isUnsaved(Object version) { - log.trace("version unsaved-value strategy UNDEFINED"); + @Override + public final Boolean isUnsaved(Object version) { + LOG.versionUnsavedValueStrategy("UNDEFINED"); return version==null ? Boolean.TRUE : null; } - public Object getDefaultValue(Object currentValue) { + @Override + public Object getDefaultValue(Object currentValue) { return currentValue; } - public String toString() { + @Override + public String toString() { return "VERSION_UNDEFINED"; } }; @@ -79,27 +89,26 @@ public class VersionValue { * is negative, otherwise assume it is a detached instance. */ public static final VersionValue NEGATIVE = new VersionValue() { - - public final Boolean isUnsaved(Object version) throws MappingException { - log.trace("version unsaved-value strategy NEGATIVE"); + + @Override + public final Boolean isUnsaved(Object version) throws MappingException { + LOG.versionUnsavedValueStrategy("NEGATIVE"); if (version==null) return Boolean.TRUE; - if (version instanceof Number) { - return ( (Number) version ).longValue() < 0l ? Boolean.TRUE : Boolean.FALSE; - } - else { - throw new MappingException("unsaved-value NEGATIVE may only be used with short, int and long types"); - } + 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"); } - public Object getDefaultValue(Object currentValue) { + @Override + public Object getDefaultValue(Object currentValue) { return IdentifierGeneratorHelper.getIntegralDataTypeHolder( currentValue.getClass() ) .initialize( -1L ) .makeValue(); } - public String toString() { + @Override + public String toString() { return "VERSION_NEGATIVE"; } }; - + protected VersionValue() { this.value = null; } @@ -112,7 +121,7 @@ public class VersionValue { public VersionValue(Object value) { this.value = value; } - + /** * Does the given version belong to a new instance? * @@ -120,15 +129,31 @@ public class VersionValue { * @return true is unsaved, false is saved, null is undefined */ public Boolean isUnsaved(Object version) throws MappingException { - if ( log.isTraceEnabled() ) log.trace("version unsaved-value: " + value); + LOG.versionUnsavedValue(value); return version==null || version.equals(value) ? Boolean.TRUE : Boolean.FALSE; } - + public Object getDefaultValue(Object currentValue) { return value; } - - public String toString() { + + @Override + 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 d89bdfb68b..b6f28432f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/Versioning.java @@ -24,11 +24,13 @@ */ package org.hibernate.engine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import static org.jboss.logging.Logger.Level.TRACE; 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. @@ -59,7 +61,8 @@ public final class Versioning { */ public static final int OPTIMISTIC_LOCK_DIRTY = 1; - private static final Logger log = LoggerFactory.getLogger( Versioning.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Versioning.class.getPackage().getName()); /** * Private constructor disallowing instantiation. @@ -76,7 +79,7 @@ public final class Versioning { */ private static Object seed(VersionType versionType, SessionImplementor session) { Object seed = versionType.seed( session ); - if ( log.isTraceEnabled() ) log.trace("Seeding: " + seed); + LOG.seeding(seed); return seed; } @@ -110,9 +113,7 @@ public final class Versioning { return true; } else { - if ( log.isTraceEnabled() ) { - log.trace( "using initial version: " + initialVersion ); - } + LOG.usingInitialVersion(initialVersion); return false; } } @@ -129,14 +130,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.trace( - "Incrementing: " + - versionType.toLoggableString( version, session.getFactory() ) + - " to " + - versionType.toLoggableString( next, session.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.incrementing(versionType.toLoggableString(version, session.getFactory()), + versionType.toLoggableString(next, session.getFactory())); return next; } @@ -191,5 +186,23 @@ 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 7dd457fa3e..b42b34fc90 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 @@ -23,17 +23,18 @@ */ package org.hibernate.engine.jdbc; +import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; import java.sql.ResultSet; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 @@ -43,7 +44,9 @@ import org.hibernate.util.JDBCExceptionReporter; * @author Gail Badner */ public class ResultSetWrapperProxy implements InvocationHandler { - private static final Logger log = LoggerFactory.getLogger( ResultSetWrapperProxy.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ResultSetWrapperProxy.class.getPackage().getName()); private static final Class[] PROXY_INTERFACES = new Class[] { ResultSet.class }; private final ResultSet rs; @@ -110,14 +113,9 @@ public class ResultSetWrapperProxy implements InvocationHandler { JDBCExceptionReporter.logExceptions( ex, buf.toString() ); } catch ( NoSuchMethodException ex ) { - 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( "]" ); - if ( log.isWarnEnabled() ) { - log.warn( buf.toString() ); + 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()); } } } @@ -191,4 +189,15 @@ 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 5d171f4a38..52b2ae78bf 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 @@ -27,10 +27,6 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.LinkedHashSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.engine.jdbc.batch.spi.Batch; import org.hibernate.engine.jdbc.batch.spi.BatchObserver; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; @@ -42,7 +38,9 @@ import org.hibernate.engine.jdbc.spi.SQLStatementLogger; * @author Steve Ebersole */ public abstract class AbstractBatchImpl implements Batch { - private static final Logger log = LoggerFactory.getLogger( AbstractBatchImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractBatchImpl.class.getPackage().getName()); private final SQLStatementLogger statementLogger; private final SQLExceptionHelper exceptionHelper; @@ -176,8 +174,8 @@ public abstract class AbstractBatchImpl implements Batch { statement.close(); } catch ( SQLException e ) { - log.error( "unable to release batch statement..." ); - log.error( "sqlexception escaped proxy", e ); + LOG.unableToReleaseBatchStatement(); + LOG.sqlExceptionEscapedProxy(e.getMessage()); } } getStatements().clear(); @@ -199,9 +197,7 @@ public abstract class AbstractBatchImpl implements Batch { } public void release() { - if ( getStatements() != null && !getStatements().isEmpty() ) { - log.info( "On release of batch it still contained JDBC statements" ); - } + if (getStatements() != null && !getStatements().isEmpty()) LOG.batchContainedStatementsOnRelease(); releaseStatements(); observers.clear(); } 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 e01a7047b3..9d45f380be 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 @@ -23,11 +23,7 @@ */ package org.hibernate.engine.jdbc.batch.internal; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.engine.jdbc.batch.spi.Batch; -import org.hibernate.engine.jdbc.spi.LogicalConnectionImplementor; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; import org.hibernate.engine.jdbc.spi.SQLStatementLogger; @@ -37,7 +33,9 @@ import org.hibernate.engine.jdbc.spi.SQLStatementLogger; * @author Steve Ebersole */ public class BatchBuilder { - private static final Logger log = LoggerFactory.getLogger( BatchBuilder.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BatchBuilder.class.getPackage().getName()); private int size; 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 9dc1b27020..758295dc0e 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 @@ -29,10 +29,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; @@ -47,7 +43,9 @@ import org.hibernate.jdbc.Expectation; * @author Steve Ebersole */ public class BatchingBatch extends AbstractBatchImpl { - private static final Logger log = LoggerFactory.getLogger( BatchingBatch.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BatchingBatch.class.getPackage().getName()); private final int batchSize; @@ -83,7 +81,7 @@ public class BatchingBatch extends AbstractBatchImpl { statement.addBatch(); } catch ( SQLException e ) { - log.error( "sqlexception escaped proxy", e ); + LOG.error( LOG.sqlExceptionEscapedProxy(), e ); throw getSqlExceptionHelper().convert( e, "could not perform addBatch", sql ); } List expectations = expectationsBySql.get( sql ); @@ -106,7 +104,8 @@ public class BatchingBatch extends AbstractBatchImpl { /** * {@inheritDoc} */ - protected void doExecuteBatch() { + @Override + protected void doExecuteBatch() { if ( maxBatchPosition == 0 ) { log.debug( "no batched statements to execute" ); } @@ -120,13 +119,13 @@ public class BatchingBatch extends AbstractBatchImpl { executeStatements(); } catch ( RuntimeException re ) { - log.error( "Exception executing batch [{}]", re.getMessage() ); + LOG.unableToExecuteBatch(re.getMessage()); throw re; } finally { for ( List expectations : expectationsBySql.values() ) { expectations.clear(); - } + } maxBatchPosition = 0; } } @@ -188,7 +187,8 @@ public class BatchingBatch extends AbstractBatchImpl { } } - public void release() { + @Override + public void release() { expectationsBySql.clear(); maxBatchPosition = 0; } 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 64eb6b116a..d4100ca497 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,10 +25,6 @@ package org.hibernate.engine.jdbc.batch.internal; import java.sql.PreparedStatement; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.jdbc.Expectation; @@ -40,7 +36,9 @@ import org.hibernate.jdbc.Expectation; * @author Steve Ebersole */ public class NonBatchingBatch extends AbstractBatchImpl { - private static final Logger log = LoggerFactory.getLogger( NonBatchingBatch.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NonBatchingBatch.class.getPackage().getName()); protected NonBatchingBatch(Object key, SQLStatementLogger statementLogger, @@ -65,7 +63,8 @@ public class NonBatchingBatch extends AbstractBatchImpl { } } - protected void doExecuteBatch() { + @Override + protected void doExecuteBatch() { // nothing to do } } 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 bc3e7fb75a..c2cb5fd12a 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 @@ -25,15 +25,15 @@ 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; +import java.io.Serializable; import java.sql.Connection; import java.sql.SQLException; - import javax.transaction.TransactionManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; @@ -46,10 +46,19 @@ 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 mediary between "entity-mode related" sessions in terms of - * their interaction with the JDBC data store. + * Acts as the intermediary between "entity-mode related" sessions in terms of their interaction with the JDBC data store. * * @author Steve Ebersole */ @@ -63,7 +72,8 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont // ConnectionManager is a "JDBCContext"? A "SessionContext" should // live in the impl package... - private static final Logger log = LoggerFactory.getLogger( JDBCContextImpl.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JDBCContext.class.getPackage().getName()); private Context owner; private ConnectionManagerImpl connectionManager; @@ -154,6 +164,8 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont throw new SessionException( "Session is closed" ); } + public Connection connection() throws HibernateException { + if (owner.isClosed()) throw new SessionException("Session is closed"); return connectionManager.getConnection(); } @@ -162,72 +174,52 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont if ( isTransactionCallbackRegistered ) { return false; } - else { - isTransactionCallbackRegistered = true; - return true; - } - + isTransactionCallbackRegistered = true; + return true; } @Override public boolean registerSynchronizationIfPossible() { - if ( isTransactionCallbackRegistered ) { - // we already have a callback registered; either a local - // (org.hibernate.Transaction) transaction has accepted - // callback responsibilities, or we have previously - // registered a transaction synch. - return true; - } + // we already have a callback registered; either a local + // (org.hibernate.Transaction) transaction has accepted + // callback responsibilities, or we have previously + // registered a transaction synch. + if (isTransactionCallbackRegistered) return true; boolean localCallbacksOnly = owner.getFactory().getSettings() .getTransactionFactory() .areCallbacksLocalToHibernateTransactions(); - if ( localCallbacksOnly ) { - // the configured transaction-factory says it only supports - // local callback mode, so no sense attempting to register a - // JTA Synchronization - return false; - } + // the configured transaction-factory says it only supports + // local callback mode, so no sense attempting to register a + // JTA Synchronization + if (localCallbacksOnly) return false; TransactionManager tm = owner.getFactory().getTransactionManager(); - if ( tm == null ) { - // if there is no TM configured, we will not be able to access - // the javax.transaction.Transaction object in order to - // register a synch anyway. - return false; - } - else { - try { - if ( !isTransactionInProgress() ) { - log.trace( "TransactionFactory reported no active transaction; Synchronization not registered" ); - return false; - } - else { - javax.transaction.Transaction tx = tm.getTransaction(); - if ( JTAHelper.isMarkedForRollback( tx ) ) { - // transactions marked for rollback-only cause some TM impls to throw exceptions - log.debug( "Transaction is marked for rollback; skipping Synchronization registration" ); - return false; - } - else { - if ( hibernateTransaction == null ) { - hibernateTransaction = owner.getFactory().getSettings().getTransactionFactory().createTransaction( this, owner ); - } - tx.registerSynchronization( - new HibernateSynchronizationImpl( getJtaSynchronizationCallbackCoordinator( tx ) ) - ); + // if there is no TM configured, we will not be able to access + // the javax.transaction.Transaction object in order to + // register a synch anyway. + if (tm == null) return false; + try { + if (!isTransactionInProgress()) { + LOG.noActiveTransaction(); + 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(); + return false; + } + if (hibernateTransaction == null) hibernateTransaction = owner.getFactory().getSettings().getTransactionFactory().createTransaction(this, + owner); + tx.registerSynchronization(new HibernateSynchronizationImpl(getJtaSynchronizationCallbackCoordinator(tx))); // tx.registerSynchronization( new CacheSynchronization(owner, this, tx, hibernateTransaction) ); - isTransactionCallbackRegistered = true; - log.debug("successfully registered Synchronization"); - return true; - } - } - } - catch( HibernateException e ) { - throw e; - } - catch (Exception e) { - throw new TransactionException( "could not register synchronization with JTA TransactionManager", e ); - } - } + isTransactionCallbackRegistered = true; + LOG.successfullyRegisteredSynchronization(); + return true; + } catch (HibernateException e) { + throw e; + } catch (Exception e) { + throw new TransactionException("could not register synchronization with JTA TransactionManager", e); + } } @Override @@ -248,23 +240,23 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont @Override public void beforeTransactionCompletion(Transaction tx) { - log.trace( "before transaction completion" ); + LOG.beforeTransactionCompletion(); owner.beforeTransactionCompletion(tx); } - + /** * We cannot rely upon this method being called! It is only * called if we are using Hibernate Transaction API. */ @Override public void afterTransactionBegin(Transaction tx) { - log.trace( "after transaction begin" ); + LOG.afterTransactionBegin(); owner.afterTransactionBegin(tx); } @Override public void afterTransactionCompletion(boolean success, Transaction tx) { - log.trace( "after transaction completion" ); + LOG.afterTransactionCompletion(); if ( getFactory().getStatistics().isStatisticsEnabled() ) { getFactory().getStatisticsImplementor().endTransaction(success); @@ -276,23 +268,23 @@ public class JDBCContextImpl implements ConnectionManagerImpl.Callback, JDBCCont hibernateTransaction = null; owner.afterTransactionCompletion(success, tx); } - + /** * Called after executing a query outside the scope of * a Hibernate or JTA transaction */ @Override public void afterNontransactionalQuery(boolean success) { - log.trace( "after autocommit" ); + LOG.afterAutoCommit(); try { - // check to see if the connection is in auto-commit + // check to see if the connection is in auto-commit // mode (no connection means aggressive connection // release outside a JTA transaction context, so MUST // be autocommit mode) boolean isAutocommit = connectionManager.isAutoCommit(); connectionManager.afterTransaction(); - + if ( isAutocommit ) { owner.afterTransactionCompletion(success, null); } @@ -366,4 +358,39 @@ 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 bcace088a0..ca18987f1c 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,6 +23,9 @@ */ 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; @@ -30,15 +33,16 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; +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.hibernate.engine.jdbc.spi.JdbcResourceRegistry; -import org.hibernate.engine.jdbc.spi.InvalidatableWrapper; +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 @@ -46,7 +50,9 @@ import org.hibernate.engine.jdbc.spi.InvalidatableWrapper; * @author Steve Ebersole */ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { - private static final Logger log = LoggerFactory.getLogger( JdbcResourceRegistryImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JdbcResourceRegistryImpl.class.getPackage().getName()); private final HashMap> xref = new HashMap>(); private final Set unassociatedResultSets = new HashSet(); @@ -59,7 +65,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void register(Statement statement) { - log.trace( "registering statement [" + statement + "]" ); + LOG.registeringStatement(statement); if ( xref.containsKey( statement ) ) { throw new HibernateException( "statement already registered with JDBCContainer" ); } @@ -95,7 +101,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void release(Statement statement) { - log.trace( "releasing statement [" + statement + "]" ); + LOG.releasingStatement(statement); Set resultSets = xref.get( statement ); if ( resultSets != null ) { for ( ResultSet resultSet : resultSets ) { @@ -108,7 +114,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void register(ResultSet resultSet) { - log.trace( "registering result set [" + resultSet + "]" ); + LOG.registeringResultSet(resultSet); Statement statement; try { statement = resultSet.getStatement(); @@ -117,9 +123,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { throw exceptionHelper.convert( e, "unable to access statement from resultset" ); } if ( statement != null ) { - if ( log.isWarnEnabled() && !xref.containsKey( statement ) ) { - log.warn( "resultset's statement was not yet registered" ); - } + if (LOG.isEnabled(Level.WARN) && !xref.containsKey(statement)) LOG.unregisteredStatement(); Set resultSets = xref.get( statement ); if ( resultSets == null ) { resultSets = new HashSet(); @@ -133,7 +137,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void release(ResultSet resultSet) { - log.trace( "releasing result set [{}]", resultSet ); + LOG.releasingResultSet(resultSet); Statement statement; try { statement = resultSet.getStatement(); @@ -142,9 +146,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { throw exceptionHelper.convert( e, "unable to access statement from resultset" ); } if ( statement != null ) { - if ( log.isWarnEnabled() && !xref.containsKey( statement ) ) { - log.warn( "resultset's statement was not registered" ); - } + if (LOG.isEnabled(Level.WARN) && !xref.containsKey(statement)) LOG.unregisteredStatement(); Set resultSets = xref.get( statement ); if ( resultSets != null ) { resultSets.remove( resultSet ); @@ -155,9 +157,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } else { boolean removed = unassociatedResultSets.remove( resultSet ); - if ( !removed ) { - log.warn( "ResultSet had no statement associated with it, but was not yet registered" ); - } + if (!removed) LOG.unregisteredResultSetWithoutStatement(); } close( resultSet ); } @@ -167,7 +167,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void releaseResources() { - log.trace( "releasing JDBC container resources [{}]", this ); + LOG.releasingJdbcContainerResources(this); cleanup(); } @@ -243,13 +243,13 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } public void close() { - log.trace( "closing JDBC container [{}]", this ); + LOG.closingJdbcContainer(this); cleanup(); } @SuppressWarnings({ "unchecked" }) protected void close(Statement statement) { - log.trace( "closing prepared statement [{}]", statement ); + LOG.closingPreparedStatement(statement); if ( statement instanceof InvalidatableWrapper ) { InvalidatableWrapper wrapper = ( InvalidatableWrapper ) statement; @@ -271,7 +271,7 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } catch( SQLException sqle ) { // there was a problem "cleaning" the prepared statement - log.debug( "Exception clearing maxRows/queryTimeout [{}]", sqle.getMessage() ); + LOG.unableToClearMaxRowsQueryTimeout(sqle.getMessage()); return; // EARLY EXIT!!! } statement.close(); @@ -280,13 +280,13 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { } } catch( SQLException sqle ) { - log.debug( "Unable to release statement [{}]", sqle.getMessage() ); + LOG.unableToReleaseStatement(sqle.getMessage()); } } @SuppressWarnings({ "unchecked" }) protected void close(ResultSet resultSet) { - log.trace( "closing result set [{}]", resultSet ); + LOG.closingResultSet(resultSet); if ( resultSet instanceof InvalidatableWrapper ) { InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet; @@ -298,8 +298,66 @@ public class JdbcResourceRegistryImpl implements JdbcResourceRegistry { resultSet.close(); } catch( SQLException e ) { - log.debug( "Unable to release result set [{}]", e.getMessage() ); + LOG.unableToReleaseResultSet(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 e5585eab4d..dfd0e31151 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,6 +23,8 @@ */ 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; @@ -32,14 +34,8 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; -import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.service.jdbc.dialect.spi.DialectFactory; import org.hibernate.engine.jdbc.spi.ExtractedDatabaseMetaData; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.SQLExceptionHelper; @@ -47,10 +43,16 @@ import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.engine.jdbc.spi.SchemaNameResolver; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.internal.util.jdbc.TypeInfo; +import org.hibernate.internal.util.jdbc.TypeInfoExtracter; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +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.hibernate.internal.util.jdbc.TypeInfoExtracter; +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 @@ -58,7 +60,9 @@ import org.hibernate.internal.util.jdbc.TypeInfoExtracter; * @author Steve Ebersole */ public class JdbcServicesImpl implements JdbcServices, Configurable { - private static final Logger log = LoggerFactory.getLogger( JdbcServicesImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JdbcServicesImpl.class.getPackage().getName()); private ConnectionProvider connectionProvider; @@ -107,19 +111,15 @@ public class JdbcServicesImpl implements JdbcServices, Configurable { Connection conn = connectionProvider.getConnection(); try { DatabaseMetaData meta = conn.getMetaData(); - log.info( "Database ->\n" + - " name : " + meta.getDatabaseProductName() + '\n' + - " version : " + meta.getDatabaseProductVersion() + '\n' + - " major : " + meta.getDatabaseMajorVersion() + '\n' + - " minor : " + meta.getDatabaseMinorVersion() - ); - log.info( "Driver ->\n" + - " name : " + meta.getDriverName() + '\n' + - " version : " + meta.getDriverVersion() + '\n' + - " major : " + meta.getDriverMajorVersion() + '\n' + - " minor : " + meta.getDriverMinorVersion() - ); - log.info( "JDBC version : " + meta.getJDBCMajorVersion() + "." + meta.getJDBCMinorVersion() ); + LOG.database(meta.getDatabaseProductName(), + meta.getDatabaseProductVersion(), + meta.getDatabaseMajorVersion(), + meta.getDatabaseMinorVersion()); + LOG.driver(meta.getDriverName(), + meta.getDriverVersion(), + meta.getDriverMajorVersion(), + meta.getDriverMinorVersion()); + LOG.jdbcVersion(meta.getJDBCMajorVersion(), meta.getJDBCMinorVersion()); metaSupportsScrollable = meta.supportsResultSetType( ResultSet.TYPE_SCROLL_INSENSITIVE ); metaSupportsBatchUpdates = meta.supportsBatchUpdates(); @@ -144,14 +144,14 @@ public class JdbcServicesImpl implements JdbcServices, Configurable { } } catch ( SQLException sqle ) { - log.warn( "Could not obtain connection metadata", sqle ); + LOG.unableToObtainConnectionMetadata(sqle.getMessage()); } finally { connectionProvider.closeConnection( conn ); } } catch ( SQLException sqle ) { - log.warn( "Could not obtain connection to query metadata", sqle ); + LOG.unableToObtainConnectionToQueryMetadata(sqle.getMessage()); dialect = dialectFactory.buildDialect( configValues, null ); } catch ( UnsupportedOperationException uoe ) { @@ -200,13 +200,13 @@ public class JdbcServicesImpl implements JdbcServices, Configurable { return (SchemaNameResolver) ReflectHelper.getDefaultConstructor( resolverClass ).newInstance(); } catch ( ClassNotFoundException e ) { - log.warn( "Unable to locate configured schema name resolver class [" + resolverClassName + "]" + e.toString() ); + LOG.unableToLocateConfiguredSchemaNameResolver(resolverClassName, e.toString()); } catch ( InvocationTargetException e ) { - log.warn( "Unable to instantiate configured schema name resolver [" + resolverClassName + "]" + e.getTargetException().toString() ); + LOG.unableToInstantiateConfiguredSchemaNameResolver(resolverClassName, e.getTargetException().toString()); } catch ( Exception e ) { - log.warn( "Unable to instantiate configured schema name resolver [" + resolverClassName + "]" + e.toString() ); + LOG.unableToInstantiateConfiguredSchemaNameResolver(resolverClassName, e.toString()); } } return null; @@ -336,4 +336,60 @@ 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 8191d94162..c99ca886f8 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 @@ -30,16 +30,12 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.JDBCException; +import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.spi.JdbcResourceRegistry; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.spi.LogicalConnectionImplementor; import org.hibernate.jdbc.BorrowedConnectionProxy; import org.hibernate.stat.StatisticsImplementor; @@ -50,7 +46,9 @@ import org.hibernate.stat.StatisticsImplementor; * @author Steve Ebersole */ public class LogicalConnectionImpl implements LogicalConnectionImplementor { - private static final Logger log = LoggerFactory.getLogger( LogicalConnectionImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + LogicalConnectionImpl.class.getPackage().getName()); private Connection physicalConnection; private Connection borrowedConnection; @@ -200,11 +198,11 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { // no matter what physicalConnection = null; isClosed = true; - log.trace( "logical connection closed" ); + LOG.closedLogicalConnection(); for ( ConnectionObserver observer : observers ) { observer.logicalConnectionClosed(); } - } + } } /** @@ -245,19 +243,19 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } public void afterStatementExecution() { - log.trace( "starting after statement execution processing [{}]", connectionReleaseMode ); + LOG.startingAfterStatementExecution(connectionReleaseMode); if ( connectionReleaseMode == ConnectionReleaseMode.AFTER_STATEMENT ) { if ( ! releasesEnabled ) { - log.debug( "skipping aggressive release due to manual disabling" ); + LOG.skippingAggressiveReleaseDueToManualDisabling(); return; } if ( jdbcResourceRegistry.hasRegisteredResources() ) { - log.debug( "skipping aggressive release due to registered resources" ); + LOG.skippingAggressiveReleaseDueToRegisteredResources(); return; } else if ( borrowedConnection != null ) { log.debug( "skipping aggresive-release due to borrowed connection" ); - } + } releaseConnection(); } } @@ -266,7 +264,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { if ( connectionReleaseMode == ConnectionReleaseMode.AFTER_STATEMENT || connectionReleaseMode == ConnectionReleaseMode.AFTER_TRANSACTION ) { if ( jdbcResourceRegistry.hasRegisteredResources() ) { - log.info( "forcing container resource cleanup on transaction completion" ); + LOG.forcingContainerResourceCleanup(); jdbcResourceRegistry.releaseResources(); } aggressiveRelease(); @@ -274,12 +272,12 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } public void disableReleases() { - log.trace( "disabling releases" ); + LOG.disablingReleases(); releasesEnabled = false; } public void enableReleases() { - log.trace( "(re)enabling releases" ); + LOG.enablingReleases(); releasesEnabled = true; //FIXME: uncomment after new batch stuff is integrated!!! //afterStatementExecution(); @@ -290,10 +288,10 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { */ public void aggressiveRelease() { if ( isUserSuppliedConnection ) { - log.debug( "cannot aggressively release user-supplied connection; skipping" ); + LOG.unableToAggressivelyReleaseUserSuppliedConnection(); } else { - log.debug( "aggressively releasing JDBC connection" ); + LOG.aggressivelyReleasingJdbcConnection( ); if ( physicalConnection != null ) { releaseConnection(); } @@ -307,13 +305,13 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { * @throws org.hibernate.JDBCException Indicates problem opening a connection */ private void obtainConnection() throws JDBCException { - log.debug( "obtaining JDBC connection" ); + LOG.obtainingJdbcConnection(); try { physicalConnection = getJdbcServices().getConnectionProvider().getConnection(); for ( ConnectionObserver observer : observers ) { observer.physicalConnectionObtained( physicalConnection ); } - log.debug( "obtained JDBC connection" ); + LOG.obtainedJdbcConnection(); } catch ( SQLException sqle) { throw getJdbcServices().getSqlExceptionHelper().convert( sqle, "Could not open connection" ); @@ -326,7 +324,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { * @throws JDBCException Indicates problem closing a connection */ private void releaseConnection() throws JDBCException { - log.debug( "releasing JDBC connection" ); + LOG.releasingJdbcConnection(); if ( physicalConnection == null ) { return; } @@ -337,7 +335,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { if ( !isUserSuppliedConnection ) { getJdbcServices().getConnectionProvider().closeConnection( physicalConnection ); } - log.debug( "released JDBC connection" ); + LOG.releasedJdbcConnection(); } catch (SQLException sqle) { throw getJdbcServices().getSqlExceptionHelper().convert( sqle, "Could not close connection" ); @@ -427,4 +425,72 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { ); } + /** + * 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/proxy/AbstractResultSetProxyHandler.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/proxy/AbstractResultSetProxyHandler.java index b5807d58e2..b10beef378 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,17 +23,18 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 @@ -41,7 +42,9 @@ import org.hibernate.engine.jdbc.spi.JdbcServices; * @author Steve Ebersole */ public abstract class AbstractResultSetProxyHandler extends AbstractProxyHandler { - private static final Logger log = LoggerFactory.getLogger( AbstractResultSetProxyHandler.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractResultSetProxyHandler.class.getPackage().getName()); private ResultSet resultSet; @@ -65,9 +68,10 @@ public abstract class AbstractResultSetProxyHandler extends AbstractProxyHandler return resultSet; } - protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { + @Override + protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - log.trace( "Handling invocation of ResultSet method [{}]", methodName ); + LOG.handlingInvocationOfResultSetMethod(methodName); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -123,4 +127,15 @@ 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 18e6773770..8437113b7e 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,19 +23,20 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 @@ -43,7 +44,9 @@ import org.hibernate.engine.jdbc.spi.LogicalConnectionImplementor; * @author Steve Ebersole */ public abstract class AbstractStatementProxyHandler extends AbstractProxyHandler { - private static final Logger log = LoggerFactory.getLogger( AbstractStatementProxyHandler.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractStatementProxyHandler.class.getPackage().getName()); private ConnectionProxyHandler connectionProxyHandler; private Connection connectionProxy; @@ -81,9 +84,10 @@ public abstract class AbstractStatementProxyHandler extends AbstractProxyHandler return statement; } - protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { + @Override + protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - log.trace( "Handling invocation of statement method [{}]", methodName ); + LOG.handlingInvocationOfStatementMethod(methodName); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -165,4 +169,15 @@ 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 ef5e0fcf47..6abc433c6f 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 @@ -32,14 +32,9 @@ import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.TransactionException; +import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.spi.JdbcResourceRegistry; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.spi.LogicalConnectionImplementor; import org.hibernate.stat.StatisticsImplementor; @@ -49,7 +44,9 @@ import org.hibernate.stat.StatisticsImplementor; * @author Steve Ebersole */ public class ConnectionProxyHandler extends AbstractProxyHandler implements InvocationHandler, ConnectionObserver { - private static final Logger log = LoggerFactory.getLogger( ConnectionProxyHandler.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractProxyHandler.class.getPackage().getName()); private LogicalConnectionImplementor logicalConnection; @@ -102,9 +99,10 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo return logicalConnection.getResourceRegistry(); } - protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { + @Override + protected Object continueInvocation(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - log.trace( "Handling invocation of connection method [{}]", methodName ); + LOG.handlingInvocationOfConnectionMethod(methodName); // other methods allowed while invalid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( "close".equals( methodName ) ) { @@ -198,7 +196,7 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo } private void invalidateHandle() { - log.trace( "Invalidating connection handle" ); + LOG.invalidatingConnectionHandle(); logicalConnection = null; invalidate(); } @@ -213,14 +211,14 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo * {@inheritDoc} */ public void physicalConnectionReleased() { - log.info( "logical connection releasing its physical connection"); + LOG.logicalConnectionReleasingPhysicalConnection(); } /** * {@inheritDoc} */ public void logicalConnectionClosed() { - log.info( "*** logical connection closed ***" ); + LOG.logicalConnectionClosed(); invalidateHandle(); } @@ -228,4 +226,29 @@ public class ConnectionProxyHandler extends AbstractProxyHandler implements Invo 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(); + } + */ } 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 bb70a938cf..4b71c0d585 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,18 +23,22 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.JDBCException; 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. @@ -42,7 +46,9 @@ import org.hibernate.util.StringHelper; * @author Steve Ebersole */ public class SQLExceptionHelper { - private static final Logger log = LoggerFactory.getLogger( SQLExceptionHelper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLExceptionHelper.class.getPackage().getName()); public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception"; public static final String DEFAULT_WARNING_MSG = "SQL Warning"; @@ -123,13 +129,13 @@ public class SQLExceptionHelper { * @param connection The connection to check for warnings. */ public void logAndClearWarnings(Connection connection) { - if ( log.isWarnEnabled() ) { + if (LOG.isEnabled(WARN)) { try { logWarnings( connection.getWarnings() ); } catch ( SQLException sqle ) { //workaround for WebLogic - log.debug( "could not log warnings", sqle ); + LOG.unableToLogWarnings(sqle); } } try { @@ -137,7 +143,7 @@ public class SQLExceptionHelper { connection.clearWarnings(); } catch ( SQLException sqle ) { - log.debug( "could not clear warnings", sqle ); + LOG.unableToClearWarnings(sqle); } } @@ -158,19 +164,16 @@ public class SQLExceptionHelper { * @param message The message text to use as a preamble. */ public void logWarnings(SQLWarning warning, String message) { - if ( log.isWarnEnabled() ) { - if ( log.isDebugEnabled() && warning != null ) { - message = StringHelper.isNotEmpty( message ) ? message : DEFAULT_WARNING_MSG; - log.debug( message, warning ); - } + if (LOG.isEnabled(WARN)) { + if (warning != null) LOG.warningPreamble(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.warn( buf.toString() ); - log.warn( warning.getMessage() ); + LOG.warningProperties(buf.toString()); + LOG.warningMessage(warning.getMessage()); warning = warning.getNextWarning(); } } @@ -192,21 +195,63 @@ public class SQLExceptionHelper { * @param message The message text to use as a preamble. */ public void logExceptions(SQLException sqlException, String message) { - if ( log.isErrorEnabled() ) { - if ( log.isDebugEnabled() ) { - message = StringHelper.isNotEmpty( message ) ? message : DEFAULT_EXCEPTION_MSG; - log.debug( message, sqlException ); - } + if (LOG.isEnabled(ERROR)) { + LOG.errorPreamble(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.warn( buf.toString() ); - log.error( sqlException.getMessage() ); + LOG.errorProperties(buf.toString()); + LOG.errorMessage(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 141c14ce79..c306918a19 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,10 +23,12 @@ */ package org.hibernate.engine.jdbc.spi; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import static org.jboss.logging.Logger.Level.DEBUG; 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. @@ -34,7 +36,9 @@ import org.hibernate.jdbc.util.FormatStyle; * @author Steve Ebersole */ public class SQLStatementLogger { - private static final Logger log = LoggerFactory.getLogger( SQLStatementLogger.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLStatementLogger.class.getPackage().getName()); private boolean logToStdout; private boolean format; @@ -90,15 +94,20 @@ public class SQLStatementLogger { */ public void logStatement(String statement) { // for now just assume a DML log for formatting - if ( format ) { - if ( logToStdout || log.isDebugEnabled() ) { - statement = FormatStyle.BASIC.getFormatter().format( statement ); - } - } - log.debug( statement ); - if ( logToStdout ) { - System.out.println( "Hibernate: " + statement ); - } + if (format && (logToStdout || LOG.isDebugEnabled())) statement = FormatStyle.BASIC.getFormatter().format(statement); + LOG.statement(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 97ce884e9d..b1349e3a40 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,29 +24,32 @@ */ package org.hibernate.engine.loading; -import java.sql.ResultSet; +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.util.List; -import java.util.Iterator; +import java.sql.ResultSet; import java.util.ArrayList; -import java.util.Set; import java.util.HashSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.collection.PersistentCollection; -import org.hibernate.persister.collection.CollectionPersister; -import org.hibernate.EntityMode; +import java.util.Iterator; +import java.util.List; +import java.util.Set; import org.hibernate.CacheMode; -import org.hibernate.cache.entry.CollectionCacheEntry; +import org.hibernate.EntityMode; import org.hibernate.cache.CacheKey; -import org.hibernate.pretty.MessageHelper; -import org.hibernate.engine.CollectionKey; -import org.hibernate.engine.Status; -import org.hibernate.engine.SessionImplementor; +import org.hibernate.cache.entry.CollectionCacheEntry; +import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.CollectionEntry; +import org.hibernate.engine.CollectionKey; import org.hibernate.engine.SessionFactoryImplementor; +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} @@ -59,7 +62,9 @@ import org.hibernate.engine.SessionFactoryImplementor; * @author Steve Ebersole */ public class CollectionLoadContext { - private static final Logger log = LoggerFactory.getLogger( CollectionLoadContext.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionLoadContext.class.getPackage().getName()); private final LoadContexts loadContexts; private final ResultSet resultSet; @@ -109,22 +114,16 @@ 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.trace( "starting attempt to find loading collection [" + MessageHelper.collectionInfoString( persister.getRole(), key ) + "]" ); - } + if (LOG.isTraceEnabled()) LOG.findingLoadingCollection(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.trace( "collection already initialized; ignoring" ); + LOG.collectionAlreadyInitialized(); return null; // ignore this row of results! Note the early exit - } - else { - // initialize this collection - log.trace( "collection not yet initialized; initializing" ); - } + } else LOG.collectionNotYetInitialized(); } else { Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister ); @@ -134,14 +133,12 @@ public class CollectionLoadContext { if ( newlySavedEntity ) { // important, to account for newly saved entities in query // todo : some kind of check for new status... - log.trace( "owning entity already loaded; ignoring" ); + LOG.owningEntityAlreadyLoaded(); return null; } else { // create one - if ( log.isTraceEnabled() ) { - log.trace( "instantiating new collection [key=" + key + ", rs=" + resultSet + "]" ); - } + LOG.instantiatingNewCollection(key, resultSet); collection = persister.getCollectionType() .instantiate( loadContexts.getPersistenceContext().getSession(), persister, key ); } @@ -154,13 +151,13 @@ public class CollectionLoadContext { } else { if ( loadingCollectionEntry.getResultSet() == resultSet ) { - log.trace( "found loading collection bound to current result set processing; reading row" ); + LOG.foundLoadingCollection(); return loadingCollectionEntry.getCollection(); } else { // 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" ); + LOG.collectionAlreadyInitializing(); return null; } } @@ -191,9 +188,7 @@ public class CollectionLoadContext { while ( iter.hasNext() ) { final CollectionKey collectionKey = (CollectionKey) iter.next(); final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry( collectionKey ); - if ( lce == null) { - log.warn( "In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [" + collectionKey + "], but no LoadingCollectionEntry was found in loadContexts" ); - } + if (lce == null) LOG.loadingCollectionKeyNotFound(collectionKey); else if ( lce.getResultSet() == resultSet && lce.getPersister() == persister ) { if ( matches == null ) { matches = new ArrayList(); @@ -205,9 +200,7 @@ public class CollectionLoadContext { lce.getCollection() ); } - if ( log.isTraceEnabled() ) { - log.trace( "removing collection load entry [" + lce + "]" ); - } + LOG.removingCollectionLoadEntry(lce); // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)... loadContexts.unregisterLoadingCollectionXRef( collectionKey ); @@ -229,31 +222,23 @@ public class CollectionLoadContext { private void endLoadingCollections(CollectionPersister persister, List matchedCollectionEntries) { if ( matchedCollectionEntries == null ) { - if ( log.isDebugEnabled() ) { - log.debug( "no collections were found in result set for role: " + persister.getRole() ); - } + LOG.noCollectionFoundInResultSet(persister.getRole()); return; } final int count = matchedCollectionEntries.size(); - if ( log.isDebugEnabled() ) { - log.debug( count + " collections were found in result set for role: " + persister.getRole() ); - } + LOG.collectionsFound(count, persister.getRole()); for ( int i = 0; i < count; i++ ) { LoadingCollectionEntry lce = ( LoadingCollectionEntry ) matchedCollectionEntries.get( i ); endLoadingCollection( lce, persister ); } - if ( log.isDebugEnabled() ) { - log.debug( count + " collections initialized for role: " + persister.getRole() ); - } + LOG.collectionsInitialized(count, persister.getRole()); } private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) { - if ( log.isTraceEnabled() ) { - log.debug( "ending loading collection [" + lce + "]" ); - } + LOG.endingLoadingCollection(lce); final SessionImplementor session = getLoadContext().getPersistenceContext().getSession(); final EntityMode em = session.getEntityMode(); @@ -279,10 +264,9 @@ public class CollectionLoadContext { addCollectionToCache( lce, persister ); } - if ( log.isDebugEnabled() ) { - log.debug( "collection fully initialized: " + MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory() ) ); - } - + if (LOG.isDebugEnabled()) LOG.collectionInitialized(MessageHelper.collectionInfoString(persister, + lce.getKey(), + session.getFactory())); if ( session.getFactory().getStatistics().isStatisticsEnabled() ) { session.getFactory().getStatisticsImplementor().loadCollection( persister.getRole() ); } @@ -298,13 +282,11 @@ public class CollectionLoadContext { final SessionImplementor session = getLoadContext().getPersistenceContext().getSession(); final SessionFactoryImplementor factory = session.getFactory(); - if ( log.isDebugEnabled() ) { - log.debug( "Caching collection: " + MessageHelper.collectionInfoString( persister, lce.getKey(), factory ) ); - } + if (LOG.isDebugEnabled()) LOG.cachingCollection(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.debug( "Refusing to add to cache due to enabled filters" ); + LOG.notAddingToCache(); // 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 @@ -344,15 +326,92 @@ public class CollectionLoadContext { } void cleanup() { - if ( !localLoadingCollectionKeys.isEmpty() ) { - log.warn( "On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [" + localLoadingCollectionKeys.size() + "] entries" ); - } + if (!localLoadingCollectionKeys.isEmpty()) LOG.localLoadingCollectionKeysCount(localLoadingCollectionKeys.size()); loadContexts.cleanupCollectionXRefs( localLoadingCollectionKeys ); localLoadingCollectionKeys.clear(); } - public String toString() { + @Override + 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 8fdcfdd942..86c327f17a 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,12 +24,14 @@ */ package org.hibernate.engine.loading; +import static org.jboss.logging.Logger.Level.WARN; import java.sql.ResultSet; -import java.util.List; import java.util.ArrayList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.List; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * {@inheritDoc} @@ -37,7 +39,9 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class EntityLoadContext { - private static final Logger log = LoggerFactory.getLogger( EntityLoadContext.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + EntityLoadContext.class.getPackage().getName()); private final LoadContexts loadContexts; private final ResultSet resultSet; @@ -49,15 +53,24 @@ public class EntityLoadContext { } void cleanup() { - if ( !hydratingEntities.isEmpty() ) { - log.warn( "On EntityLoadContext#clear, hydratingEntities contained [" + hydratingEntities.size() + "] entries" ); - } + if (!hydratingEntities.isEmpty()) LOG.hydratingEntitiesCount(hydratingEntities.size()); hydratingEntities.clear(); } - public String toString() { + @Override + 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 c2c73d3210..f48d67be63 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,24 +24,26 @@ */ 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; +import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.Iterator; -import java.util.HashMap; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.util.IdentityMap; -import org.hibernate.engine.PersistenceContext; -import org.hibernate.engine.CollectionKey; -import org.hibernate.engine.SessionImplementor; +import org.hibernate.EntityMode; import org.hibernate.collection.PersistentCollection; +import org.hibernate.engine.CollectionKey; +import org.hibernate.engine.PersistenceContext; +import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.pretty.MessageHelper; -import org.hibernate.EntityMode; +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 @@ -60,7 +62,9 @@ import org.hibernate.EntityMode; * @author Steve Ebersole */ public class LoadContexts { - private static final Logger log = LoggerFactory.getLogger( LoadContexts.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + LoadContexts.class.getPackage().getName()); private final PersistenceContext persistenceContext; private Map collectionLoadContexts; @@ -129,7 +133,7 @@ public class LoadContexts { Iterator itr = collectionLoadContexts.values().iterator(); while ( itr.hasNext() ) { CollectionLoadContext collectionLoadContext = ( CollectionLoadContext ) itr.next(); - log.warn( "fail-safe cleanup (collections) : " + collectionLoadContext ); + LOG.failSafeCleanup(collectionLoadContext); collectionLoadContext.cleanup(); } collectionLoadContexts.clear(); @@ -138,7 +142,7 @@ public class LoadContexts { Iterator itr = entityLoadContexts.values().iterator(); while ( itr.hasNext() ) { EntityLoadContext entityLoadContext = ( EntityLoadContext ) itr.next(); - log.warn( "fail-safe cleanup (entities) : " + entityLoadContext ); + LOG.failSafeCleanup(entityLoadContext); entityLoadContext.cleanup(); } entityLoadContexts.clear(); @@ -187,9 +191,7 @@ public class LoadContexts { context = ( CollectionLoadContext ) collectionLoadContexts.get( resultSet ); } if ( context == null ) { - if ( log.isTraceEnabled() ) { - log.trace( "constructing collection load context for result set [" + resultSet + "]" ); - } + LOG.constructingCollectionLoadContext(resultSet); context = new CollectionLoadContext( this, resultSet ); collectionLoadContexts.put( resultSet, context ); } @@ -207,18 +209,16 @@ 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.trace( "returning loading collection:" + MessageHelper.collectionInfoString( persister, ownerKey, getSession().getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.returningLoadingCollection(MessageHelper.collectionInfoString(persister, + ownerKey, + getSession().getFactory())); return lce.getCollection(); } - else { - // todo : should really move this log statement to CollectionType, where this is used from... - if ( log.isTraceEnabled() ) { - log.trace( "creating collection wrapper:" + MessageHelper.collectionInfoString( persister, ownerKey, getSession().getFactory() ) ); - } - return null; - } + // 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())); + return null; } // loading collection xrefs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -286,18 +286,10 @@ public class LoadContexts { if ( xrefLoadingCollectionEntries == null ) { return null; } - if ( log.isTraceEnabled() ) { - log.trace( "attempting to locate loading collection entry [" + key + "] in any result-set context" ); - } + LOG.locatingLoadingCollectionEntry(key); LoadingCollectionEntry rtn = ( LoadingCollectionEntry ) xrefLoadingCollectionEntries.get( key ); - if ( log.isTraceEnabled() ) { - if ( rtn == null ) { - log.trace( "collection [" + key + "] not located in load context" ); - } - else { - log.trace( "collection [" + key + "] located in load context" ); - } - } + if (rtn == null) LOG.collectionNotLocated(key); + else LOG.collectionLocated(key); return rtn; } @@ -328,4 +320,42 @@ 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 42631183c9..88e4dd5c78 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,15 +23,17 @@ */ package org.hibernate.engine.profile; -import java.util.Map; +import static org.jboss.logging.Logger.Level.TRACE; +import static org.jboss.logging.Logger.Level.WARN; import java.util.HashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.util.Map; import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.type.Type; 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 @@ -42,7 +44,9 @@ import org.hibernate.type.BagType; * @author Steve Ebersole */ public class FetchProfile { - private static final Logger log = LoggerFactory.getLogger( FetchProfile.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FetchProfile.class.getPackage().getName()); private final String name; private Map fetches = new HashMap(); @@ -92,7 +96,7 @@ public class FetchProfile { public void addFetch(Fetch fetch) { Type associationType = fetch.getAssociation().getOwner().getPropertyType( fetch.getAssociation().getAssociationPath() ); if ( associationType.isCollectionType() ) { - log.trace( "handling request to add collection fetch [{}]", fetch.getAssociation().getRole() ); + LOG.addingFetch(fetch.getAssociation().getRole()); // couple of things for which to account in the case of collection // join fetches @@ -101,7 +105,7 @@ public class FetchProfile { // processed collection join fetches if ( BagType.class.isInstance( associationType ) ) { if ( containsJoinFetchedCollection ) { - log.warn( "Ignoring bag join fetch [{}] due to prior collection join fetch", fetch.getAssociation().getRole() ); + LOG.containsJoinFetchedCollection(fetch.getAssociation().getRole()); return; // EARLY EXIT!!! } } @@ -110,10 +114,8 @@ public class FetchProfile { // fetch where we had already added a bag join fetch previously, // we need to go back and ignore that previous bag join fetch. if ( containsJoinFetchedBag ) { - if ( fetches.remove( bagJoinFetch.getAssociation().getRole() ) != bagJoinFetch ) { - // just for safety... - log.warn( "Unable to erase previously added bag join fetch" ); - } + // just for safety... + if (fetches.remove(bagJoinFetch.getAssociation().getRole()) != bagJoinFetch) LOG.unableToRemoveBagJoinFetch(); bagJoinFetch = null; containsJoinFetchedBag = false; } @@ -168,4 +170,23 @@ 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 cd65749f39..e946987356 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,34 +24,37 @@ */ package org.hibernate.engine.query; -import org.hibernate.hql.QuerySplitter; -import org.hibernate.hql.QueryTranslator; -import org.hibernate.hql.ParameterTranslations; -import org.hibernate.hql.FilterTranslator; -import org.hibernate.util.ArrayHelper; -import org.hibernate.util.EmptyIterator; -import org.hibernate.util.JoinedIterator; -import org.hibernate.util.IdentitySet; -import org.hibernate.HibernateException; -import org.hibernate.ScrollableResults; -import org.hibernate.QueryException; -import org.hibernate.type.Type; -import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.engine.QueryParameters; -import org.hibernate.engine.SessionImplementor; -import org.hibernate.engine.RowSelection; -import org.hibernate.event.EventSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +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; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Set; -import java.util.HashSet; -import java.util.List; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.HashMap; +import org.hibernate.HibernateException; +import org.hibernate.QueryException; +import org.hibernate.ScrollableResults; +import org.hibernate.engine.QueryParameters; +import org.hibernate.engine.RowSelection; +import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.engine.SessionImplementor; +import org.hibernate.event.EventSource; +import org.hibernate.hql.FilterTranslator; +import org.hibernate.hql.ParameterTranslations; +import org.hibernate.hql.QuerySplitter; +import org.hibernate.hql.QueryTranslator; +import org.hibernate.type.Type; +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). @@ -60,9 +63,10 @@ import java.util.HashMap; */ public class HQLQueryPlan implements Serializable { - // TODO : keep seperate notions of QT[] here for shallow/non-shallow queries... + // TODO : keep separate notions of QT[] here for shallow/non-shallow queries... - private static final Logger log = LoggerFactory.getLogger( HQLQueryPlan.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HQLQueryPlan.class.getPackage().getName()); private final String sourceQuery; private final QueryTranslator[] translators; @@ -170,8 +174,8 @@ public class HQLQueryPlan implements Serializable { public List performList( QueryParameters queryParameters, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "find: " + getSourceQuery() ); + if (LOG.isTraceEnabled()) { + LOG.find(getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } boolean hasLimit = queryParameters.getRowSelection() != null && @@ -179,7 +183,7 @@ public class HQLQueryPlan implements Serializable { boolean needsLimit = hasLimit && translators.length > 1; QueryParameters queryParametersToUse; if ( needsLimit ) { - log.warn( "firstResult/maxResults specified on polymorphic query; applying in memory!" ); + LOG.needsLimit(); RowSelection selection = new RowSelection(); selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() ); selection.setTimeout( queryParameters.getRowSelection().getTimeout() ); @@ -229,8 +233,8 @@ public class HQLQueryPlan implements Serializable { public Iterator performIterate( QueryParameters queryParameters, EventSource session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "iterate: " + getSourceQuery() ); + if (LOG.isTraceEnabled()) { + LOG.iterate(getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length == 0 ) { @@ -255,8 +259,8 @@ public class HQLQueryPlan implements Serializable { public ScrollableResults performScroll( QueryParameters queryParameters, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "iterate: " + getSourceQuery() ); + if (LOG.isTraceEnabled()) { + LOG.iterate(getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length != 1 ) { @@ -271,13 +275,11 @@ public class HQLQueryPlan implements Serializable { public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "executeUpdate: " + getSourceQuery() ); + if (LOG.isTraceEnabled()) { + LOG.executeUpdate(getSourceQuery()); queryParameters.traceParameters( session.getFactory() ); } - if ( translators.length != 1 ) { - log.warn( "manipulation query [" + getSourceQuery() + "] resulted in [" + translators.length + "] split queries" ); - } + if (translators.length != 1) LOG.splitQueries(getSourceQuery(), translators.length); int result = 0; for ( int i = 0; i < translators.length; i++ ) { result += translators[i].executeUpdate( queryParameters, session ); @@ -289,9 +291,7 @@ public class HQLQueryPlan implements Serializable { long start = System.currentTimeMillis(); ParamLocationRecognizer recognizer = ParamLocationRecognizer.parseLocations( hql ); long end = System.currentTimeMillis(); - if ( log.isTraceEnabled() ) { - log.trace( "HQL param location recognition took " + (end - start) + " mills (" + hql + ")" ); - } + LOG.hqlParamLocationRecognition(end - start, hql); int ordinalParamCount = parameterTranslations.getOrdinalParameterCount(); int[] locations = ArrayHelper.toIntArray( recognizer.getOrdinalParameterLocationList() ); @@ -336,4 +336,37 @@ 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 e930ef4ff4..876997dffd 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,27 +24,29 @@ */ 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; import java.util.Iterator; import java.util.List; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.QueryException; -import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; import org.hibernate.action.BulkOperationCleanupAction; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.TypedValue; +import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; 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. @@ -56,7 +58,8 @@ public class NativeSQLQueryPlan implements Serializable { private final SQLCustomQuery customQuery; - private static final Logger log = LoggerFactory.getLogger(NativeSQLQueryPlan.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NativeSQLQueryPlan.class.getPackage().getName()); public NativeSQLQueryPlan( NativeSQLQuerySpecification specification, @@ -154,11 +157,7 @@ public class NativeSQLQueryPlan implements Serializable { TypedValue typedval = (TypedValue) e.getValue(); int[] locs = getNamedParameterLocs( name ); for (int i = 0; i < locs.length; i++) { - if ( log.isDebugEnabled() ) { - log.debug( "bindNamedParameters() " - + typedval.getValue() + " -> " + name + " [" - + (locs[i] + start ) + "]" ); - } + LOG.bindNamedParameters(typedval.getValue(), name, locs[i] + start); typedval.getType().nullSafeSet( ps, typedval.getValue(), locs[i] + start, session ); } @@ -222,4 +221,16 @@ 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 01f140c49c..8a3363cb5b 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,28 +23,29 @@ */ package org.hibernate.engine.query; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.util.SimpleMRUCache; -import org.hibernate.util.SoftLimitMRUCache; -import org.hibernate.util.CollectionHelper; +import static org.jboss.logging.Logger.Level.TRACE; +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import org.hibernate.MappingException; +import org.hibernate.QueryException; import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; -import org.hibernate.QueryException; -import org.hibernate.MappingException; import org.hibernate.impl.FilterImpl; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.Serializable; -import java.util.Map; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; -import java.util.HashSet; -import java.util.Collections; -import java.util.Collection; +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. @@ -56,7 +57,8 @@ import java.util.Collection; */ public class QueryPlanCache implements Serializable { - private static final Logger log = LoggerFactory.getLogger( QueryPlanCache.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryPlanCache.class.getPackage().getName()); private SessionFactoryImplementor factory; @@ -118,16 +120,9 @@ public class QueryPlanCache implements Serializable { HQLQueryPlan plan = ( HQLQueryPlan ) planCache.get ( key ); if ( plan == null ) { - if ( log.isTraceEnabled() ) { - log.trace( "unable to locate HQL query plan in cache; generating (" + queryString + ")" ); - } + LOG.unableToLocateHqlQuery(queryString); plan = new HQLQueryPlan(queryString, shallow, enabledFilters, factory ); - } - else { - if ( log.isTraceEnabled() ) { - log.trace( "located HQL query plan in cache (" + queryString + ")" ); - } - } + } else LOG.locatedHqlQuery(queryString); planCache.put( key, plan ); @@ -140,16 +135,9 @@ public class QueryPlanCache implements Serializable { FilterQueryPlan plan = ( FilterQueryPlan ) planCache.get ( key ); if ( plan == null ) { - if ( log.isTraceEnabled() ) { - log.trace( "unable to locate collection-filter query plan in cache; generating (" + collectionRole + " : " + filterString + ")" ); - } + LOG.unableToLocateCollectionFilter(collectionRole, filterString); plan = new FilterQueryPlan( filterString, collectionRole, shallow, enabledFilters, factory ); - } - else { - if ( log.isTraceEnabled() ) { - log.trace( "located collection-filter query plan in cache (" + collectionRole + " : " + filterString + ")" ); - } - } + } else LOG.locatedCollectionFilter(collectionRole, filterString); planCache.put( key, plan ); @@ -160,16 +148,9 @@ public class QueryPlanCache implements Serializable { NativeSQLQueryPlan plan = ( NativeSQLQueryPlan ) planCache.get( spec ); if ( plan == null ) { - if ( log.isTraceEnabled() ) { - log.trace( "unable to locate native-sql query plan in cache; generating (" + spec.getQueryString() + ")" ); - } + LOG.unableToLocationNativeSqlQueryPlan(spec.getQueryString()); plan = new NativeSQLQueryPlan( spec, factory ); - } - else { - if ( log.isTraceEnabled() ) { - log.trace( "located native-sql query plan in cache (" + spec.getQueryString() + ")" ); - } - } + } else LOG.locatedNativeSqlQueryPlan(spec.getQueryString()); planCache.put( spec, plan ); return plan; @@ -232,7 +213,8 @@ public class QueryPlanCache implements Serializable { this.hashCode = hash; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -248,7 +230,8 @@ public class QueryPlanCache implements Serializable { } - public int hashCode() { + @Override + public int hashCode() { return hashCode; } } @@ -288,7 +271,8 @@ public class QueryPlanCache implements Serializable { this.hashCode = hash; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -303,7 +287,8 @@ public class QueryPlanCache implements Serializable { } - public int hashCode() { + @Override + public int hashCode() { return hashCode; } } @@ -337,7 +322,8 @@ public class QueryPlanCache implements Serializable { this.hashCode = hash; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -354,8 +340,42 @@ public class QueryPlanCache implements Serializable { } - public int hashCode() { + @Override + public int hashCode() { 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 ba2c75f799..822ea4a5fd 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,20 +24,24 @@ */ 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; +import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; -import javax.transaction.SystemException; -import javax.transaction.NotSupportedException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; 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 @@ -52,7 +56,7 @@ import org.hibernate.exception.SQLExceptionConverter; */ public class Isolater { - private static final Logger log = LoggerFactory.getLogger( Isolater.class ); + static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Isolater.class.getPackage().getName()); /** * Ensures that all processing actually performed by the given work will @@ -116,9 +120,7 @@ public class Isolater { try { // First we suspend any current JTA transaction Transaction surroundingTransaction = transactionManager.suspend(); - if ( log.isDebugEnabled() ) { - log.debug( "surrounding JTA transaction suspended [" + surroundingTransaction + "]" ); - } + LOG.jtaTransactionSuspended(surroundingTransaction); boolean hadProblems = false; try { @@ -137,9 +139,7 @@ public class Isolater { finally { try { transactionManager.resume( surroundingTransaction ); - if ( log.isDebugEnabled() ) { - log.debug( "surrounding JTA transaction resumed [" + surroundingTransaction + "]" ); - } + LOG.jtaTransactionResumed(surroundingTransaction); } catch( Throwable t ) { // if the actually work had an error use that, otherwise error based on t @@ -170,7 +170,7 @@ public class Isolater { transactionManager.rollback(); } catch ( Exception ignore ) { - log.info( "Unable to rollback isolated transaction on error [" + e + "] : [" + ignore + "]" ); + LOG.unableToRollbackIsolatedTransaction(e, ignore); } } } @@ -206,7 +206,7 @@ public class Isolater { session.getFactory().getConnectionProvider().closeConnection( connection ); } catch ( Throwable ignore ) { - log.info( "Unable to release isolated connection [" + ignore + "]" ); + LOG.unableToReleaseIsolatedConnection(ignore); } } } @@ -259,7 +259,7 @@ public class Isolater { } } catch( Exception ignore ) { - log.info( "unable to rollback connection on exception [" + ignore + "]" ); + LOG.unableToRollbackConnection(ignore); } if ( e instanceof HibernateException ) { @@ -281,14 +281,14 @@ public class Isolater { connection.setAutoCommit( true ); } catch( Exception ignore ) { - log.trace( "was unable to reset connection back to auto-commit" ); + LOG.unableToResetConnectionToAutoCommit(); } } try { session.getFactory().getConnectionProvider().closeConnection( connection ); } catch ( Exception ignore ) { - log.info( "Unable to release isolated connection [" + ignore + "]" ); + LOG.unableToReleaseIsolatedConnection(ignore); } } } @@ -304,4 +304,40 @@ 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 c0a3ad9e68..f337cddf69 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,13 +23,15 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Manages a registry of {@link Synchronization Synchronizations}. @@ -37,7 +39,9 @@ import org.hibernate.HibernateException; * @author Steve Ebersole */ public class SynchronizationRegistry { - private static final Logger log = LoggerFactory.getLogger( SynchronizationRegistry.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SynchronizationRegistry.class.getPackage().getName()); private LinkedHashSet synchronizations; @@ -45,7 +49,7 @@ public class SynchronizationRegistry { * Register a user {@link Synchronization} callback for this transaction. * * @param synchronization The synchronization callback to register. - * + * * @throws HibernateException */ public void registerSynchronization(Synchronization synchronization) { @@ -58,9 +62,7 @@ public class SynchronizationRegistry { } boolean added = synchronizations.add( synchronization ); - if ( !added ) { - log.info( "Synchronization [{}] was already registered", synchronization ); - } + if (!added) LOG.synchronizationAlreadyRegistered(synchronization); } /** @@ -74,7 +76,7 @@ public class SynchronizationRegistry { synchronization.beforeCompletion(); } catch ( Throwable t ) { - log.error( "exception calling user Synchronization [{}]", synchronization, t ); + LOG.synchronizationFailed(synchronization, t); } } } @@ -93,9 +95,25 @@ public class SynchronizationRegistry { synchronization.afterCompletion( status ); } catch ( Throwable t ) { - log.error( "exception calling user Synchronization [{}]", synchronization, t ); + LOG.synchronizationFailed(synchronization, t); } } } } + + /** + * 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 d252b091f1..88b834148c 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,13 +24,13 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.action.CollectionRecreateAction; import org.hibernate.action.CollectionRemoveAction; @@ -44,16 +44,20 @@ import org.hibernate.engine.CollectionKey; import org.hibernate.engine.Collections; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.PersistenceContext; +import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.Status; import org.hibernate.event.EventSource; import org.hibernate.event.FlushEntityEvent; import org.hibernate.event.FlushEntityEventListener; import org.hibernate.event.FlushEvent; -import org.hibernate.engine.SessionImplementor; 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. @@ -62,13 +66,14 @@ import org.hibernate.util.LazyIterator; */ public abstract class AbstractFlushingEventListener implements Serializable { - private static final Logger log = LoggerFactory.getLogger(AbstractFlushingEventListener.class); - + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractFlushingEventListener.class.getPackage().getName()); + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Pre-flushing section // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** + /** * Coordinates the processing necessary to get things ready for executions * as db calls by preping the session caches and moving the appropriate * entities and collections to their respective execution queues. @@ -78,10 +83,10 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void flushEverythingToExecutions(FlushEvent event) throws HibernateException { - log.trace("flushing session"); - + LOG.flushingSession(); + EventSource session = event.getSession(); - + final PersistenceContext persistenceContext = session.getPersistenceContext(); session.getInterceptor().preFlush( new LazyIterator( persistenceContext.getEntitiesByKey() ) ); @@ -93,7 +98,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { // now, any collections that are initialized // inside this block do not get updated - they // are ignored until the next flush - + persistenceContext.setFlushing(true); try { flushEntities(event); @@ -104,22 +109,18 @@ public abstract class AbstractFlushingEventListener implements Serializable { } //some statistics - if ( log.isDebugEnabled() ) { - 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() + 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()); + new Printer( session.getFactory() ).toString( + persistenceContext.getEntitiesByKey().values().iterator(), + session.getEntityMode() ); } } @@ -130,8 +131,8 @@ public abstract class AbstractFlushingEventListener implements Serializable { * and also apply orphan delete */ private void prepareEntityFlushes(EventSource session) throws HibernateException { - - log.debug("processing flush-time cascades"); + + LOG.processingFlushTimeCascades(); final Map.Entry[] list = IdentityMap.concurrentEntries( session.getPersistenceContext().getEntityEntries() ); //safe from concurrent modification because of how entryList() is implemented on IdentityMap @@ -146,8 +147,8 @@ public abstract class AbstractFlushingEventListener implements Serializable { } } } - - private void cascadeOnFlush(EventSource session, EntityPersister persister, Object object, Object anything) + + private void cascadeOnFlush(EventSource session, EntityPersister persister, Object object, Object anything) throws HibernateException { session.getPersistenceContext().incrementCascadeLevel(); try { @@ -158,9 +159,9 @@ public abstract class AbstractFlushingEventListener implements Serializable { session.getPersistenceContext().decrementCascadeLevel(); } } - + protected Object getAnything() { return null; } - + protected CascadingAction getCascadingAction() { return CascadingAction.SAVE_UPDATE; } @@ -173,8 +174,8 @@ public abstract class AbstractFlushingEventListener implements Serializable { // Initialize dirty flags for arrays + collections with composite elements // and reset reached, doupdate, etc. - - log.debug("dirty checking collections"); + + LOG.dirtyCheckingCollections(); final List list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); final int size = list.size(); @@ -191,7 +192,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ private void flushEntities(FlushEvent event) throws HibernateException { - log.trace("Flushing entities and processing referenced collections"); + LOG.flushingEntitiesAndProcessingReferencedCollections(); // Among other things, updateReachables() will recursively load all // collections that are moving roles. This might cause entities to @@ -201,7 +202,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { // It is safe because of how IdentityMap implements entrySet() final EventSource source = event.getSession(); - + final Map.Entry[] list = IdentityMap.concurrentEntries( source.getPersistenceContext().getEntityEntries() ); final int size = list.length; for ( int i = 0; i < size; i++ ) { @@ -230,7 +231,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ private void flushCollections(EventSource session) throws HibernateException { - log.trace("Processing unreferenced collections"); + LOG.processingUnreferencedCollections(); List list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); int size = list.size(); @@ -244,7 +245,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { // Schedule updates to collections: - log.trace( "Scheduling collection removes/(re)creates/updates" ); + LOG.schedulingCollectionChanges(); list = IdentityMap.entries( session.getPersistenceContext().getCollectionEntries() ); size = list.size(); @@ -257,35 +258,35 @@ public abstract class AbstractFlushingEventListener implements Serializable { if ( ce.isDorecreate() ) { session.getInterceptor().onCollectionRecreate( coll, ce.getCurrentKey() ); actionQueue.addAction( - new CollectionRecreateAction( - coll, - ce.getCurrentPersister(), - ce.getCurrentKey(), - session + new CollectionRecreateAction( + coll, + ce.getCurrentPersister(), + ce.getCurrentKey(), + session ) ); } if ( ce.isDoremove() ) { session.getInterceptor().onCollectionRemove( coll, ce.getLoadedKey() ); actionQueue.addAction( - new CollectionRemoveAction( - coll, - ce.getLoadedPersister(), - ce.getLoadedKey(), - ce.isSnapshotEmpty(coll), - session + new CollectionRemoveAction( + coll, + ce.getLoadedPersister(), + ce.getLoadedKey(), + ce.isSnapshotEmpty(coll), + session ) ); } if ( ce.isDoupdate() ) { session.getInterceptor().onCollectionUpdate( coll, ce.getLoadedKey() ); actionQueue.addAction( - new CollectionUpdateAction( - coll, - ce.getLoadedPersister(), - ce.getLoadedKey(), - ce.isSnapshotEmpty(coll), - session + new CollectionUpdateAction( + coll, + ce.getLoadedPersister(), + ce.getLoadedKey(), + ce.isSnapshotEmpty(coll), + session ) ); } @@ -293,7 +294,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { } actionQueue.sortCollectionActions(); - + } /** @@ -310,7 +311,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void performExecutions(EventSource session) throws HibernateException { - log.trace("executing flush"); + LOG.flush(); try { session.getJDBCContext().getConnectionManager().flushBeginning(); @@ -321,7 +322,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { session.getActionQueue().executeActions(); } catch (HibernateException he) { - log.error("Could not synchronize database state with session", he); + LOG.unableToSynchronizeDatabaseStateWithSession(he); throw he; } finally { @@ -341,7 +342,7 @@ public abstract class AbstractFlushingEventListener implements Serializable { */ protected void postFlush(SessionImplementor session) throws HibernateException { - log.trace( "post flush" ); + LOG.postFlush(); final PersistenceContext persistenceContext = session.getPersistenceContext(); persistenceContext.getCollectionsByKey().clear(); @@ -362,18 +363,74 @@ public abstract class AbstractFlushingEventListener implements Serializable { } else { //otherwise recreate the mapping between the collection and its key - CollectionKey collectionKey = new CollectionKey( - collectionEntry.getLoadedPersister(), - collectionEntry.getLoadedKey(), - session.getEntityMode() + CollectionKey collectionKey = new CollectionKey( + collectionEntry.getLoadedPersister(), + collectionEntry.getLoadedKey(), + session.getEntityMode() ); persistenceContext.getCollectionsByKey() .put(collectionKey, persistentCollection); } } - + 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 b365cb26e5..aaa2662ffd 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,19 +24,21 @@ */ package org.hibernate.event.def; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.LockMode; -import org.hibernate.ObjectDeletedException; import org.hibernate.LockOptions; -import org.hibernate.event.EventSource; +import org.hibernate.ObjectDeletedException; import org.hibernate.cache.CacheKey; import org.hibernate.cache.access.SoftLock; import org.hibernate.engine.EntityEntry; 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 @@ -46,7 +48,8 @@ import org.hibernate.pretty.MessageHelper; */ public class AbstractLockUpgradeEventListener extends AbstractReassociateEventListener { - private static final Logger log = LoggerFactory.getLogger(AbstractLockUpgradeEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractLockUpgradeEventListener.class.getPackage().getName()); /** * Performs a pessimistic lock upgrade on a given entity, if needed. @@ -73,23 +76,18 @@ public class AbstractLockUpgradeEventListener extends AbstractReassociateEventLi final EntityPersister persister = entry.getPersister(); - if ( log.isTraceEnabled() ) - log.trace( - "locking " + - MessageHelper.infoString( persister, entry.getId(), source.getFactory() ) + - " in mode: " + - requestedLockMode - ); + if (LOG.isTraceEnabled()) LOG.locking(MessageHelper.infoString(persister, entry.getId(), source.getFactory()), + requestedLockMode); final SoftLock lock; final CacheKey ck; if ( persister.hasCache() ) { - ck = new CacheKey( - entry.getId(), - persister.getIdentifierType(), - persister.getRootEntityName(), - source.getEntityMode(), - source.getFactory() + ck = new CacheKey( + entry.getId(), + persister.getIdentifierType(), + persister.getRootEntityName(), + source.getEntityMode(), + source.getFactory() ); lock = persister.getCacheAccessStrategy().lockItem( ck, entry.getVersion() ); } @@ -97,7 +95,7 @@ public class AbstractLockUpgradeEventListener extends AbstractReassociateEventLi ck = null; lock = null; } - + try { if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE ) { // todo : should we check the current isolation mode explicitly? @@ -122,4 +120,15 @@ 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 7a39c70e0f..03c696e9d3 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,11 +23,8 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.LockMode; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityKey; @@ -38,6 +35,10 @@ 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 @@ -47,7 +48,8 @@ import org.hibernate.type.TypeHelper; */ public class AbstractReassociateEventListener implements Serializable { - private static final Logger log = LoggerFactory.getLogger( AbstractReassociateEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractReassociateEventListener.class.getPackage().getName()); /** * Associates a given entity (either transient or associated with another session) to @@ -62,12 +64,9 @@ public class AbstractReassociateEventListener implements Serializable { */ protected final EntityEntry reassociate(AbstractEvent event, Object object, Serializable id, EntityPersister persister) { - if ( log.isTraceEnabled() ) { - log.trace( - "reassociating transient instance: " + - MessageHelper.infoString( persister, id, event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.reassociatingTransientInstance(MessageHelper.infoString(persister, + id, + event.getSession().getFactory())); EventSource source = event.getSession(); EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); @@ -106,4 +105,14 @@ public class AbstractReassociateEventListener implements Serializable { } + /** + * 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 9bf1ad0950..d7054eb18d 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,12 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.LockMode; import org.hibernate.NonUniqueObjectException; import org.hibernate.action.EntityIdentityInsertAction; @@ -53,6 +51,10 @@ 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. @@ -66,7 +68,8 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent protected static final int DETACHED = 2; protected static final int DELETED = 3; - private static final Logger log = LoggerFactory.getLogger( AbstractSaveEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractSaveEventListener.class.getPackage().getName()); /** * Prepares the save call using the given requested id. @@ -129,16 +132,10 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent return performSave( entity, null, persister, true, anything, source, requiresImmediateIdAccess ); } else { - - if ( log.isDebugEnabled() ) { - log.debug( - "generated identifier: " + - persister.getIdentifierType().toLoggableString( generatedId, source.getFactory() ) + - ", using strategy: " + - persister.getIdentifierGenerator().getClass().getName() - //TODO: define toString()s for generators - ); - } + // TODO: define toString()s for generators + if (LOG.isDebugEnabled()) LOG.generatedIdentifier(persister.getIdentifierType().toLoggableString(generatedId, + source.getFactory()), + persister.getIdentifierGenerator().getClass().getName()); return performSave( entity, generatedId, persister, false, anything, source, true ); } @@ -171,12 +168,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent EventSource source, boolean requiresImmediateIdAccess) { - if ( log.isTraceEnabled() ) { - log.trace( - "saving " + - MessageHelper.infoString( persister, id, source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.saving(MessageHelper.infoString(persister, id, source.getFactory())); EntityKey key; if ( !useIdentityColumn ) { @@ -215,9 +207,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.debug( "calling onSave()" ); + LOG.callingOnSave(); if ( ( ( Lifecycle ) entity ).onSave( source ) ) { - log.debug( "insertion vetoed by onSave()" ); + LOG.insertionVetoed(); return true; } } @@ -282,9 +274,9 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent cascadeBeforeSave( source, persister, entity, anything ); if ( useIdentityColumn && !shouldDelayIdentityInserts ) { - log.trace( "executing insertions" ); + LOG.executingInsertions(); source.getActionQueue().executeInserts(); - } + } Object[] values = persister.getPropertyValuesToInsert( entity, getMergeMap( anything ), source ); Type[] types = persister.getPropertyTypes(); @@ -316,14 +308,14 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent values, entity, persister, source, shouldDelayIdentityInserts ); if ( !shouldDelayIdentityInserts ) { - log.debug( "executing identity-insert immediately" ); + LOG.executingIdentityInsert(); source.getActionQueue().execute( insert ); id = insert.getGeneratedId(); key = new EntityKey( id, persister, source.getEntityMode() ); source.getPersistenceContext().checkUniqueness( key, entity ); } else { - log.debug( "delaying identity-insert due to no transaction in progress" ); + LOG.delayingIdentityInsert(); source.getActionQueue().addAction( insert ); key = insert.getDelayedEntityKey(); } @@ -503,22 +495,12 @@ 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.trace( - "persistent instance of: " + - getLoggableName( entityName, entity ) - ); - } + if (LOG.isTraceEnabled()) LOG.persistentInstanceOf(getLoggableName(entityName, entity)); return PERSISTENT; } else { //ie. e.status==DELETED - if ( log.isTraceEnabled() ) { - log.trace( - "deleted instance of: " + - getLoggableName( entityName, entity ) - ); - } + if (LOG.isTraceEnabled()) LOG.deletedInstanceOf(getLoggableName(entityName, entity)); return DELETED; } @@ -529,21 +511,11 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent //try interceptor and unsaved-value if ( ForeignKeys.isTransient( entityName, entity, getAssumedUnsaved(), source ) ) { - if ( log.isTraceEnabled() ) { - log.trace( - "transient instance of: " + - getLoggableName( entityName, entity ) - ); - } + if (LOG.isTraceEnabled()) LOG.transientInstanceOf(getLoggableName(entityName, entity)); return TRANSIENT; } else { - if ( log.isTraceEnabled() ) { - log.trace( - "detached instance of: " + - getLoggableName( entityName, entity ) - ); - } + if (LOG.isTraceEnabled()) LOG.detachedInstanceOf(getLoggableName(entityName, entity)); return DETACHED; } @@ -558,4 +530,55 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent 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 145c60648f..cf555d0a23 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,23 +24,27 @@ */ package org.hibernate.event.def; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.FlushMode; import org.hibernate.HibernateException; 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 + * Defines the default flush event listeners used by hibernate for * flushing session state in response to generated auto-flush events. * * @author Steve Ebersole */ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener implements AutoFlushEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultAutoFlushEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultAutoFlushEventListener.class.getPackage().getName()); /** Handle the given auto-flush event. * @@ -50,33 +54,33 @@ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener 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.trace("Need to execute flush"); + LOG.needToExecuteFlush(); performExecutions(source); postFlush(source); - // note: performExecutions() clears all collectionXxxxtion + // note: performExecutions() clears all collectionXxxxtion // collections (the collection actions) in the session if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { source.getFactory().getStatisticsImplementor().flush(); } - + } else { - log.trace("Dont need to execute flush"); + LOG.dontNeedToExecuteFlush(); source.getActionQueue().clearFromFlushNeededCheck( oldSize ); } - + event.setFlushRequired( flushIsReallyNeeded( event, source ) ); } @@ -85,15 +89,29 @@ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener private boolean flushIsReallyNeeded(AutoFlushEvent event, final EventSource source) { return source.getActionQueue() - .areTablesToBeUpdated( event.getQuerySpaces() ) || + .areTablesToBeUpdated( event.getQuerySpaces() ) || source.getFlushMode()==FlushMode.ALWAYS; } private boolean flushMightBeNeeded(final EventSource source) { - return !source.getFlushMode().lessThan(FlushMode.AUTO) && + return !source.getFlushMode().lessThan(FlushMode.AUTO) && source.getDontFlushFromFind() == 0 && ( 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 21fbee797f..c8f7f62cb9 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,12 +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 java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.CacheMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; @@ -51,6 +50,10 @@ 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 @@ -60,7 +63,8 @@ import org.hibernate.util.IdentitySet; */ public class DefaultDeleteEventListener implements DeleteEventListener { - private static final Logger log = LoggerFactory.getLogger( DefaultDeleteEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultDeleteEventListener.class.getPackage().getName()); /** * Handle the given delete event. @@ -94,7 +98,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener { final Object version; if ( entityEntry == null ) { - log.trace( "entity was not persistent in delete processing" ); + LOG.entityNotpersistentInDeleteProcessing(); persister = source.getEntityPersister( event.getEntityName(), entity ); @@ -137,10 +141,10 @@ public class DefaultDeleteEventListener implements DeleteEventListener { ); } else { - log.trace( "deleting a persistent instance" ); + LOG.deletingPersistentInstance(); if ( entityEntry.getStatus() == Status.DELETED || entityEntry.getStatus() == Status.GONE ) { - log.trace( "object was already deleted" ); + LOG.objectAlreadyDeleted(); return; } persister = entityEntry.getPersister(); @@ -200,9 +204,9 @@ public class DefaultDeleteEventListener implements DeleteEventListener { boolean cascadeDeleteEnabled, EntityPersister persister, Set transientEntities) { - log.info( "handling transient entity in delete processing" ); + LOG.handlingTransientEntity(); if ( transientEntities.contains( entity ) ) { - log.trace( "already handled transient entity; skipping" ); + LOG.alreadyHandledTransientEntity(); return; } transientEntities.add( entity ); @@ -230,12 +234,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener { final EntityPersister persister, final Set transientEntities) { - if ( log.isTraceEnabled() ) { - log.trace( - "deleting " + - MessageHelper.infoString( persister, entityEntry.getId(), session.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.deleting(MessageHelper.infoString(persister, entityEntry.getId(), session.getFactory())); final PersistenceContext persistenceContext = session.getPersistenceContext(); final Type[] propTypes = persister.getPropertyTypes(); @@ -304,9 +303,9 @@ public class DefaultDeleteEventListener implements DeleteEventListener { protected boolean invokeDeleteLifecycle(EventSource session, Object entity, EntityPersister persister) { if ( persister.implementsLifecycle( session.getEntityMode() ) ) { - log.debug( "calling onDelete()" ); + LOG.callingOnDelete(); if ( ( ( Lifecycle ) entity ).onDelete( session ) ) { - log.debug( "deletion vetoed by onDelete()" ); + LOG.deletionVetoed(); return true; } } @@ -354,4 +353,42 @@ public class DefaultDeleteEventListener implements DeleteEventListener { } } + /** + * 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 86562eb005..434e2d14c1 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,11 +24,14 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.HibernateException; import org.hibernate.event.DirtyCheckEvent; import org.hibernate.event.DirtyCheckEventListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -39,7 +42,8 @@ import org.slf4j.LoggerFactory; */ public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListener implements DirtyCheckEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultDirtyCheckEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultDirtyCheckEventListener.class.getPackage().getName()); /** Handle the given dirty-check event. * @@ -53,12 +57,28 @@ public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListene try { flushEverythingToExecutions(event); boolean wasNeeded = event.getSession().getActionQueue().hasAnyQueuedActions(); - log.debug( wasNeeded ? "session dirty" : "session not dirty" ); + if (wasNeeded) LOG.sessionDirty(); + else LOG.sessionNotDirty(); event.setDirty( wasNeeded ); } finally { event.getSession().getActionQueue().clearFromFlushNeededCheck( oldSize ); } - + } + + /** + * 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 74c9d1b217..37d7e7f150 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,10 +24,8 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.engine.Cascade; import org.hibernate.engine.CascadingAction; @@ -41,6 +39,10 @@ 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 @@ -52,9 +54,10 @@ import org.hibernate.proxy.LazyInitializer; */ public class DefaultEvictEventListener implements EvictEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultEvictEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultEvictEventListener.class.getPackage().getName()); - /** + /** * Handle the given evict event. * * @param event The evict event to be handled. @@ -95,15 +98,13 @@ public class DefaultEvictEventListener implements EvictEventListener { } protected void doEvict( - final Object object, - final EntityKey key, + final Object object, + final EntityKey key, final EntityPersister persister, - final EventSource session) + final EventSource session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "evicting " + MessageHelper.infoString(persister) ); - } + if (LOG.isTraceEnabled()) LOG.evicting(MessageHelper.infoString(persister)); // remove all collections for the entity from the session-level cache if ( persister.hasCollections() ) { @@ -111,7 +112,7 @@ public class DefaultEvictEventListener implements EvictEventListener { } // remove any snapshot, not really for memory management purposes, but - // rather because it might now be stale, and there is no longer any + // rather because it might now be stale, and there is no longer any // EntityEntry to take precedence // This is now handled by removeEntity() //session.getPersistenceContext().removeDatabaseSnapshot(key); @@ -119,4 +120,15 @@ 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 bd3fe9962f..c403483e91 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,16 +24,14 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.StaleObjectStateException; -import org.hibernate.action.EntityUpdateAction; import org.hibernate.action.DelayedPostInsertIdentifier; +import org.hibernate.action.EntityUpdateAction; import org.hibernate.classic.Validatable; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityKey; @@ -49,6 +47,10 @@ 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 @@ -57,7 +59,8 @@ import org.hibernate.util.ArrayHelper; */ public class DefaultFlushEntityEventListener implements FlushEntityEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultFlushEntityEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultFlushEntityEventListener.class.getPackage().getName()); /** * make sure user didn't mangle the id @@ -101,7 +104,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener EntityMode entityMode, SessionImplementor session) { if ( persister.hasNaturalIdentifier() && entry.getStatus() != Status.READ_ONLY ) { - Object[] snapshot = null; + Object[] snapshot = null; Type[] types = persister.getPropertyTypes(); int[] props = persister.getNaturalIdentifierProperties(); boolean[] updateable = persister.getPropertyUpdateability(); @@ -117,7 +120,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener } else { loadedVal = loaded[prop]; } - if ( !types[prop].isEqual( current[prop], loadedVal, entityMode ) ) { + if ( !types[prop].isEqual( current[prop], loadedVal, entityMode ) ) { throw new HibernateException( "immutable natural identifier of an instance of " + persister.getEntityName() + @@ -242,7 +245,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener } private boolean scheduleUpdate(final FlushEntityEvent event) { - + final EntityEntry entry = event.getEntityEntry(); final EventSource session = event.getSession(); final Object entity = event.getEntity(); @@ -250,34 +253,18 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener final EntityMode entityMode = session.getEntityMode(); final EntityPersister persister = entry.getPersister(); final Object[] values = event.getPropertyValues(); - - if ( log.isTraceEnabled() ) { + + if (LOG.isTraceEnabled()) { if ( status == Status.DELETED ) { - 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() ) - ); + 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())); } final boolean intercepted; @@ -327,7 +314,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener session ) ); - + return intercepted; } @@ -337,13 +324,13 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener ( (Validatable) entity ).validate(); } } - + protected boolean handleInterception(FlushEntityEvent event) { SessionImplementor session = event.getSession(); EntityEntry entry = event.getEntityEntry(); EntityPersister persister = entry.getPersister(); Object entity = event.getEntity(); - + //give the Interceptor a chance to modify property values final Object[] values = event.getPropertyValues(); final boolean intercepted = invokeInterceptor( session, entity, entry, values, persister ); @@ -359,7 +346,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener } event.setDirtyProperties(dirtyProperties); } - + return intercepted; } @@ -383,54 +370,54 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener * Convience method to retreive an entities next version value */ private Object getNextVersion(FlushEntityEvent event) throws HibernateException { - + EntityEntry entry = event.getEntityEntry(); EntityPersister persister = entry.getPersister(); if ( persister.isVersioned() ) { Object[] values = event.getPropertyValues(); - + if ( entry.isBeingReplicated() ) { return Versioning.getVersion(values, persister); } else { int[] dirtyProperties = event.getDirtyProperties(); - - final boolean isVersionIncrementRequired = isVersionIncrementRequired( - event, - entry, - persister, - dirtyProperties + + final boolean isVersionIncrementRequired = isVersionIncrementRequired( + event, + entry, + persister, + dirtyProperties ); - + final Object nextVersion = isVersionIncrementRequired ? Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) : entry.getVersion(); //use the current version - + Versioning.setVersion(values, nextVersion, persister); - + return nextVersion; } } else { return null; } - + } private boolean isVersionIncrementRequired( - FlushEntityEvent event, - EntityEntry entry, - EntityPersister persister, + FlushEntityEvent event, + EntityEntry entry, + EntityPersister persister, int[] dirtyProperties ) { - final boolean isVersionIncrementRequired = entry.getStatus()!=Status.DELETED && ( - dirtyProperties==null || - Versioning.isVersionIncrementRequired( - dirtyProperties, + final boolean isVersionIncrementRequired = entry.getStatus()!=Status.DELETED && ( + dirtyProperties==null || + Versioning.isVersionIncrementRequired( + dirtyProperties, event.hasDirtyCollection(), persister.getPropertyVersionability() - ) + ) ); return isVersionIncrementRequired; } @@ -444,12 +431,12 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener EntityPersister persister = event.getEntityEntry().getPersister(); Status status = event.getEntityEntry().getStatus(); - + if ( !event.isDirtyCheckPossible() ) { return true; } else { - + int[] dirtyProperties = event.getDirtyProperties(); if ( dirtyProperties!=null && dirtyProperties.length!=0 ) { return true; //TODO: suck into event class @@ -457,13 +444,13 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener else { return hasDirtyCollections( event, persister, status ); } - + } } private boolean hasDirtyCollections(FlushEntityEvent event, EntityPersister persister, Status status) { if ( isCollectionDirtyCheckNecessary(persister, status ) ) { - DirtyCollectionSearchVisitor visitor = new DirtyCollectionSearchVisitor( + DirtyCollectionSearchVisitor visitor = new DirtyCollectionSearchVisitor( event.getSession(), persister.getPropertyVersionability() ); @@ -482,12 +469,12 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener persister.isVersioned() && persister.hasCollections(); } - + /** * Perform a dirty check, and attach the results to the event */ protected void dirtyCheck(FlushEntityEvent event) throws HibernateException { - + final Object entity = event.getEntity(); final Object[] values = event.getPropertyValues(); final SessionImplementor session = event.getSession(); @@ -496,24 +483,24 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener final Serializable id = entry.getId(); final Object[] loadedState = entry.getLoadedState(); - int[] dirtyProperties = session.getInterceptor().findDirty( - entity, - id, - values, - loadedState, - persister.getPropertyNames(), - persister.getPropertyTypes() + int[] dirtyProperties = session.getInterceptor().findDirty( + entity, + id, + values, + loadedState, + persister.getPropertyNames(), + persister.getPropertyTypes() ); - + event.setDatabaseSnapshot(null); final boolean interceptorHandledDirtyCheck; boolean cannotDirtyCheck; - + if ( dirtyProperties==null ) { // Interceptor returned null, so do the dirtycheck ourself, if possible interceptorHandledDirtyCheck = false; - + cannotDirtyCheck = loadedState==null; // object loaded by update() if ( !cannotDirtyCheck ) { // dirty check against the usual snapshot of the entity @@ -561,21 +548,17 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener event.setDirtyProperties(dirtyProperties); event.setDirtyCheckHandledByInterceptor(interceptorHandledDirtyCheck); event.setDirtyCheckPossible(!cannotDirtyCheck); - + } private void logDirtyProperties(Serializable id, int[] dirtyProperties, EntityPersister persister) { - if ( log.isTraceEnabled() && dirtyProperties != null && dirtyProperties.length > 0 ) { + if (LOG.isTraceEnabled() && dirtyProperties != null && dirtyProperties.length > 0) { final String[] allPropertyNames = persister.getPropertyNames(); final String[] dirtyPropertyNames = new String[ dirtyProperties.length ]; for ( int i = 0; i < dirtyProperties.length; i++ ) { dirtyPropertyNames[i] = allPropertyNames[ dirtyProperties[i]]; } - log.trace( - "Found dirty properties [{}] : {}", - MessageHelper.infoString( persister.getEntityName(), id ), - dirtyPropertyNames - ); + LOG.foundDirtyProperties(MessageHelper.infoString(persister.getEntityName(), id), dirtyPropertyNames); } } @@ -591,16 +574,38 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener } throw new StaleObjectStateException( persister.getEntityName(), id ); } - else { - return snapshot; - } - } - else { - //TODO: optimize away this lookup for entities w/o unsaved-value="undefined" - EntityKey entityKey = new EntityKey( id, persister, session.getEntityMode() ); - return session.getPersistenceContext() - .getCachedDatabaseSnapshot( entityKey ); + return snapshot; } + // TODO: optimize away this lookup for entities w/o unsaved-value="undefined" + 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 652ef9106b..e399561aae 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,10 +24,8 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.cache.CacheKey; import org.hibernate.cache.entry.CollectionCacheEntry; @@ -35,18 +33,23 @@ import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.CollectionEntry; import org.hibernate.engine.PersistenceContext; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.engine.SessionImplementor; import org.hibernate.event.InitializeCollectionEvent; import org.hibernate.event.InitializeCollectionEventListener; -import org.hibernate.engine.SessionImplementor; 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 */ public class DefaultInitializeCollectionEventListener implements InitializeCollectionEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultInitializeCollectionEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultInitializeCollectionEventListener.class.getPackage().getName()); /** * called by a collection that wants to initialize itself @@ -60,14 +63,11 @@ 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.trace( - "initializing collection " + - MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.initializingCollection(MessageHelper.collectionInfoString(ce.getLoadedPersister(), + ce.getLoadedKey(), + source.getFactory())); - log.trace("checking second-level cache"); + LOG.checkingSecondLevelCache(); final boolean foundInCache = initializeCollectionFromCache( ce.getLoadedKey(), ce.getLoadedPersister(), @@ -75,17 +75,15 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle source ); - if (foundInCache) { - log.trace("collection initialized from cache"); - } + if (foundInCache) LOG.collectionInitializedFromCache(); else { - log.trace("collection not cached"); + LOG.collectionNotCached(); ce.getLoadedPersister().initialize( ce.getLoadedKey(), source ); - log.trace("collection initialized"); + LOG.collectionInitialized(); if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { - source.getFactory().getStatisticsImplementor().fetchCollection( - ce.getLoadedPersister().getRole() + source.getFactory().getStatisticsImplementor().fetchCollection( + ce.getLoadedPersister().getRole() ); } } @@ -109,65 +107,71 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle SessionImplementor source) { if ( !source.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) { - log.trace( "disregarding cached version (if any) of collection due to enabled filters "); + LOG.ignoringCachedVersionOfCollection(); return false; } - final boolean useCache = persister.hasCache() && + final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled(); - if ( !useCache ) { - return false; - } - else { - - final SessionFactoryImplementor factory = source.getFactory(); + if (!useCache) return false; - final CacheKey ck = new CacheKey( - id, - persister.getKeyType(), - persister.getRole(), - source.getEntityMode(), - source.getFactory() + final SessionFactoryImplementor factory = source.getFactory(); + + final CacheKey ck = new CacheKey(id, persister.getKeyType(), persister.getRole(), source.getEntityMode(), + source.getFactory()); + Object ce = persister.getCacheAccessStrategy().get(ck, source.getTimestamp()); + + if (factory.getStatistics().isStatisticsEnabled()) { + if (ce == null) { + factory.getStatisticsImplementor().secondLevelCacheMiss(persister.getCacheAccessStrategy().getRegion().getName()); + } else { + factory.getStatisticsImplementor().secondLevelCacheHit(persister.getCacheAccessStrategy().getRegion().getName() ); - Object ce = persister.getCacheAccessStrategy().get( ck, source.getTimestamp() ); - - if ( factory.getStatistics().isStatisticsEnabled() ) { - if ( ce == null ) { - factory.getStatisticsImplementor().secondLevelCacheMiss( - persister.getCacheAccessStrategy().getRegion().getName() - ); - } - else { - factory.getStatisticsImplementor().secondLevelCacheHit( - persister.getCacheAccessStrategy().getRegion().getName() - ); - } + } - - } - - if (ce==null) { - return false; - } - else { - CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure() - .destructure(ce, factory); - - final PersistenceContext persistenceContext = source.getPersistenceContext(); - cacheEntry.assemble( - collection, - persister, - persistenceContext.getCollectionOwner(id, persister) - ); - persistenceContext.getCollectionEntry(collection).postInitialize(collection); - //addInitializedCollection(collection, persister, id); - return true; - } - } + + if (ce == null) return false; + + CollectionCacheEntry cacheEntry = (CollectionCacheEntry)persister.getCacheEntryStructure().destructure(ce, factory); + + final PersistenceContext persistenceContext = source.getPersistenceContext(); + cacheEntry.assemble(collection, persister, persistenceContext.getCollectionOwner(id, persister)); + persistenceContext.getCollectionEntry(collection).postInitialize(collection); + // 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 f17a83b110..dfcd3ef5d0 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,16 +23,16 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.NonUniqueObjectException; import org.hibernate.PersistentObjectException; import org.hibernate.TypeMismatchException; -import org.hibernate.EntityMode; import org.hibernate.cache.CacheKey; import org.hibernate.cache.access.SoftLock; import org.hibernate.cache.entry.CacheEntry; @@ -57,6 +57,10 @@ 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 @@ -70,7 +74,8 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i public static final Object INCONSISTENT_RTN_CLASS_MARKER = new Object(); public static final LockMode DEFAULT_LOCK_MODE = LockMode.NONE; - private static final Logger log = LoggerFactory.getLogger(DefaultLoadEventListener.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultLoadEventListener.class.getPackage().getName()); /** @@ -157,7 +162,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i } } catch(HibernateException e) { - log.info("Error performing load command", e); + LOG.unableToLoadCommand(e); throw e; } } @@ -257,12 +262,9 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EntityKey keyToLoad, final LoadEventListener.LoadType options) { - if ( log.isTraceEnabled() ) { - log.trace( - "loading entity: " + - MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.loadingEntity(MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); if ( !persister.hasProxy() ) { // this class has no proxies (so do a shortcut) @@ -308,7 +310,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final LoadEventListener.LoadType options, final PersistenceContext persistenceContext, final Object proxy) { - log.trace("entity proxy found in session cache"); + LOG.entityProxyFoundInSessionCache(); LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer(); if ( li.isUnwrap() ) { return li.getImplementation(); @@ -344,7 +346,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i Object existing = persistenceContext.getEntity( keyToLoad ); if ( existing != null ) { // return existing object or initialized proxy (unless deleted) - log.trace( "entity found in session cache" ); + LOG.entityFoundInSessionCache(); if ( options.isCheckDeleted() ) { EntityEntry entry = persistenceContext.getEntry( existing ); Status status = entry.getStatus(); @@ -355,7 +357,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i return existing; } else { - log.trace( "creating new proxy for entity" ); + LOG.creatingNewProxyForEntity(); // return new uninitialized proxy Object proxy = persister.createProxy( event.getEntityId(), event.getSession() ); persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(keyToLoad); @@ -430,49 +432,37 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EntityKey keyToLoad, final LoadEventListener.LoadType options) { - if ( log.isTraceEnabled() ) { - log.trace( - "attempting to resolve: " + - MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.attemptingToResolve(MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); Object entity = loadFromSessionCache( event, keyToLoad, options ); if ( entity == REMOVED_ENTITY_MARKER ) { - log.debug( "load request found matching entity in context, but it is scheduled for removal; returning null" ); + LOG.entityScheduledForRemoval(); return null; } if ( entity == INCONSISTENT_RTN_CLASS_MARKER ) { - log.debug( "load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null" ); + LOG.entityHasInconsistentReturnType(); return null; } if ( entity != null ) { - if ( log.isTraceEnabled() ) { - log.trace( - "resolved object in session cache: " + - MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.resolvedObjectInSessionCache(MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return entity; } entity = loadFromSecondLevelCache(event, persister, options); if ( entity != null ) { - if ( log.isTraceEnabled() ) { - log.trace( - "resolved object in second-level cache: " + - MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.resolvedObjectInSecondLevelCache(MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return entity; } - if ( log.isTraceEnabled() ) { - log.trace( - "object not resolved in any cache: " + - MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.objectNotResolvedInAnyCache(MessageHelper.infoString(persister, + event.getEntityId(), + event.getSession().getFactory())); return loadFromDatasource(event, persister, keyToLoad, options); } @@ -624,12 +614,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i final EventSource session = event.getSession(); final SessionFactoryImplementor factory = session.getFactory(); - if ( log.isTraceEnabled() ) { - log.trace( - "assembling entity from second-level cache: " + - MessageHelper.infoString( persister, id, factory ) - ); - } + if (LOG.isTraceEnabled()) LOG.assemblingEntityFromSecondLevelCache(MessageHelper.infoString(persister, id, factory)); EntityPersister subclassPersister = factory.getEntityPersister( entry.getSubclass() ); Object result = optionalObject == null ? @@ -658,7 +643,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i ); Object version = Versioning.getVersion( values, subclassPersister ); - if ( log.isTraceEnabled() ) log.trace( "Cached Version: " + version ); + if (LOG.isTraceEnabled()) LOG.cachedVersion(version); final PersistenceContext persistenceContext = session.getPersistenceContext(); boolean isReadOnly = session.isDefaultReadOnly(); @@ -703,4 +688,62 @@ 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 7b64492889..996594be30 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,22 +24,19 @@ */ 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; import java.util.Map; import java.util.Set; -import java.util.HashSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.ObjectDeletedException; +import org.hibernate.PropertyValueException; import org.hibernate.StaleObjectStateException; import org.hibernate.TransientObjectException; import org.hibernate.WrongClassException; -import org.hibernate.PropertyValueException; import org.hibernate.engine.Cascade; import org.hibernate.engine.CascadingAction; import org.hibernate.engine.EntityEntry; @@ -57,6 +54,10 @@ 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 @@ -64,12 +65,14 @@ import org.hibernate.type.TypeHelper; * * @author Gavin King */ -public class DefaultMergeEventListener extends AbstractSaveEventListener +public class DefaultMergeEventListener extends AbstractSaveEventListener implements MergeEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultMergeEventListener.class); - - protected Map getMergeMap(Object anything) { + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultMergeEventListener.class.getPackage().getName()); + + @Override + protected Map getMergeMap(Object anything) { return ( ( EventCache ) anything ).invertMap(); } @@ -98,8 +101,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener Object transientEntity = ( ( Map.Entry ) it.next() ).getKey(); String transientEntityName = event.getSession().guessEntityName( transientEntity ); transientEntityNames.add( transientEntityName ); - log.trace( "transient instance could not be processed by merge when checking nullability: " + - transientEntityName + "[" + transientEntity + "]" ); + LOG.transientInstanceNotProcessedDueToNullability(transientEntityName, transientEntity); } if ( isNullabilityCheckedGlobal( event.getSession() ) ) { throw new TransientObjectException( @@ -107,7 +109,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener transientEntityNames ); } else { - log.trace( "retry saving transient instances without checking nullability" ); + LOG.retrySavingTransientInstancesIgnoringNullability(); // failures will be detected later... retryMergeTransientEntities( event, transientCopyCache, copyCache, false ); } @@ -130,8 +132,7 @@ 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.trace( "transient instance could not be processed by merge: " + - event.getSession().guessEntityName( copy ) + "[" + entity + "]" ); + LOG.transientInstanceNotProcessed(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 @@ -182,7 +183,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } } - /** + /** * Handle the given merge event. * * @param event The merge event to be handled. @@ -200,7 +201,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( original instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) original ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { - log.trace("ignoring uninitialized proxy"); + LOG.ignoringUninitializedProxy(); event.setResult( source.load( li.getEntityName(), li.getIdentifier() ) ); return; //EARLY EXIT! } @@ -214,12 +215,12 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( copyCache.containsKey( entity ) && ( copyCache.isOperatedOn( entity ) ) ) { - log.trace("already in merge process"); - event.setResult( entity ); + LOG.alreadyInMergeProcess(); + event.setResult( entity ); } else { if ( copyCache.containsKey( entity ) ) { - log.trace("already in copyCache; setting in merge process"); + LOG.alreadyInCopyCache(); copyCache.setOperatedOn( entity, true ); } event.setEntity( entity ); @@ -249,7 +250,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener if ( entityState == -1 ) { entityState = getEntityState( entity, event.getEntityName(), entry, source ); } - + switch (entityState) { case DETACHED: entityIsDetached(event, copyCache); @@ -262,38 +263,38 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener break; default: //DELETED throw new ObjectDeletedException( - "deleted instance passed to merge", + "deleted instance passed to merge", null, getLoggableName( event.getEntityName(), entity ) - ); + ); } } - + } - + } protected void entityIsPersistent(MergeEvent event, Map copyCache) { - log.trace("ignoring persistent instance"); - + LOG.ignoringPersistentInstance(); + //TODO: check that entry.getIdentifier().equals(requestedId) - + final Object entity = event.getEntity(); final EventSource source = event.getSession(); final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); ( ( EventCache ) copyCache ).put( entity, entity, true ); //before cascade! - + cascadeOnMerge(source, persister, entity, copyCache); copyValues(persister, entity, entity, source, copyCache); - + event.setResult(entity); } protected void entityIsTransient(MergeEvent event, Map copyCache) { - - log.trace("merging transient instance"); - + + LOG.mergingTransientInstance(); + final Object entity = event.getEntity(); final EventSource source = event.getSession(); @@ -315,7 +316,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener Map copyCache, boolean isNullabilityChecked) { - log.trace("merging transient instance"); + LOG.mergingTransientInstance(); final EntityPersister persister = source.getEntityPersister( entityName, entity ); @@ -423,9 +424,9 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } } protected void entityIsDetached(MergeEvent event, Map copyCache) { - - log.trace("merging detached instance"); - + + LOG.mergingDetachedInstance(); + final Object entity = event.getEntity(); final EventSource source = event.getSession(); @@ -443,21 +444,21 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener throw new HibernateException( "merge requested with id not matching id of passed entity" ); } } - + String previousFetchProfile = source.getFetchProfile(); source.setFetchProfile("merge"); - //we must clone embedded composite identifiers, or + //we must clone embedded composite identifiers, or //we will get back the same instance that we pass in final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType() .deepCopy( id, source.getEntityMode(), source.getFactory() ); final Object result = source.get(entityName, clonedIdentifier); source.setFetchProfile(previousFetchProfile); - + if ( result == null ) { - //TODO: we should throw an exception if we really *know* for sure + //TODO: we should throw an exception if we really *know* for sure // that this is a detached instance, rather than just assuming //throw new StaleObjectStateException(entityName, id); - + // we got here because we assumed that an instance // with an assigned id was detached, when it was // really persistent @@ -465,7 +466,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } else { ( ( EventCache ) copyCache ).put( entity, result, true ); //before cascade! - + final Object target = source.getPersistenceContext().unproxy(result); if ( target == entity ) { throw new AssertionFailure("entity was not detached"); @@ -484,15 +485,15 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } throw new StaleObjectStateException( entityName, id ); } - - // cascade first, so that all unsaved objects get their + + // cascade first, so that all unsaved objects get their // copy created before we actually copy cascadeOnMerge(source, persister, entity, copyCache); copyValues(persister, entity, target, source, copyCache); - + //copyValues works by reflection, so explicitly mark the entity instance dirty markInterceptorDirty( entity, target ); - + event.setResult(result); } @@ -554,9 +555,9 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } protected void copyValues( - final EntityPersister persister, - final Object entity, - final Object target, + final EntityPersister persister, + final Object entity, + final Object target, final SessionImplementor source, final Map copyCache ) { @@ -565,7 +566,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener persister.getPropertyValues( target, source.getEntityMode() ), persister.getPropertyTypes(), source, - target, + target, copyCache ); @@ -574,8 +575,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener protected void copyValues( final EntityPersister persister, - final Object entity, - final Object target, + final Object entity, + final Object target, final SessionImplementor source, final Map copyCache, final ForeignKeyDirection foreignKeyDirection) { @@ -611,7 +612,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener persister.setPropertyValues( target, copiedValues, source.getEntityMode() ); } - /** + /** * Perform any cascades needed as part of this copy event. * * @param source The merge event being processed. @@ -636,26 +637,102 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener } - protected CascadingAction getCascadeAction() { + @Override + protected CascadingAction getCascadeAction() { return CascadingAction.MERGE; } - protected Boolean getAssumedUnsaved() { + @Override + protected Boolean getAssumedUnsaved() { return Boolean.FALSE; } - + /** * Cascade behavior is redefined by this subclass, disable superclass behavior */ - protected void cascadeAfterSave(EventSource source, EntityPersister persister, Object entity, Object anything) + @Override + protected void cascadeAfterSave(EventSource source, EntityPersister persister, Object entity, Object anything) throws HibernateException { } /** * Cascade behavior is redefined by this subclass, disable superclass behavior */ - protected void cascadeBeforeSave(EventSource source, EntityPersister persister, Object entity, Object anything) + @Override + 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 22a79602b6..0375892d2a 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,24 +23,27 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.ObjectDeletedException; import org.hibernate.PersistentObjectException; import org.hibernate.engine.CascadingAction; import org.hibernate.engine.EntityEntry; +import org.hibernate.engine.SessionImplementor; import org.hibernate.event.EventSource; import org.hibernate.event.PersistEvent; import org.hibernate.event.PersistEventListener; -import org.hibernate.engine.SessionImplementor; import org.hibernate.id.ForeignGenerator; 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 @@ -49,9 +52,11 @@ import org.hibernate.util.IdentityMap; * @author Gavin King */ public class DefaultPersistEventListener extends AbstractSaveEventListener implements PersistEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultPersistEventListener.class); - /** + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultPersistEventListener.class.getPackage().getName()); + + /** * Handle the given create event. * * @param event The create event to be handled. @@ -60,9 +65,9 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple public void onPersist(PersistEvent event) throws HibernateException { onPersist( event, IdentityMap.instantiate(10) ); } - - /** + + /** * Handle the given create event. * * @param event The create event to be handled. @@ -71,7 +76,7 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple public void onPersist(PersistEvent event, Map createCache) throws HibernateException { final SessionImplementor source = event.getSession(); final Object object = event.getObject(); - + final Object entity; if ( object instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); @@ -112,11 +117,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() ) { - if ( persister.getIdentifier( entity, source ) != null ) { - log.debug( "Resetting entity id attribute to null for foreign generator" ); - } - } + if (LOG.isDebugEnabled() && persister.getIdentifier(entity, source) != null) LOG.resettingEntityIdAttributeToNull(); persister.setIdentifier( entity, null, source ); entityState = getEntityState( entity, entityName, entityEntry, source ); } @@ -143,16 +144,16 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple } } - + protected void entityIsPersistent(PersistEvent event, Map createCache) { - log.trace("ignoring persistent instance"); + LOG.ignoringPersistentInstance(); final EventSource source = event.getSession(); - + //TODO: check that entry.getIdentifier().equals(requestedId) - + final Object entity = source.getPersistenceContext().unproxy( event.getObject() ); final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); - + if ( createCache.put(entity, entity)==null ) { //TODO: merge into one method! cascadeBeforeSave(source, persister, entity, createCache); @@ -160,33 +161,53 @@ public class DefaultPersistEventListener extends AbstractSaveEventListener imple } } - - /** + + /** * Handle the given create event. * * @param event The save event to be handled. * @throws HibernateException */ protected void entityIsTransient(PersistEvent event, Map createCache) throws HibernateException { - - log.trace("saving transient instance"); + + LOG.savingTransientInstance(); final EventSource source = event.getSession(); - + final Object entity = source.getPersistenceContext().unproxy( event.getObject() ); - + if ( createCache.put(entity, entity)==null ) { saveWithGeneratedId( entity, event.getEntityName(), createCache, source, false ); } } - protected CascadingAction getCascadeAction() { + @Override + protected CascadingAction getCascadeAction() { return CascadingAction.PERSIST; } - - protected Boolean getAssumedUnsaved() { + + @Override + 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 879968fb78..f33923796b 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,12 +23,9 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.PersistentObjectException; import org.hibernate.UnresolvableObjectException; @@ -47,6 +44,10 @@ 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 @@ -56,13 +57,14 @@ import org.hibernate.util.IdentityMap; */ public class DefaultRefreshEventListener implements RefreshEventListener { - private static final Logger log = LoggerFactory.getLogger(DefaultRefreshEventListener.class); - + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultRefreshEventListener.class.getPackage().getName()); + public void onRefresh(RefreshEvent event) throws HibernateException { onRefresh( event, IdentityMap.instantiate(10) ); } - /** + /** * Handle the given refresh event. * * @param event The refresh event to be handled. @@ -70,7 +72,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener { public void onRefresh(RefreshEvent event, Map refreshedAlready) { final EventSource source = event.getSession(); - + boolean isTransient = ! source.contains( event.getObject() ); if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) { if ( isTransient ) { @@ -82,23 +84,18 @@ public class DefaultRefreshEventListener implements RefreshEventListener { final Object object = source.getPersistenceContext().unproxyAndReassociate( event.getObject() ); if ( refreshedAlready.containsKey(object) ) { - log.trace("already refreshed"); + LOG.alreadyRefreshed(); return; } final EntityEntry e = source.getPersistenceContext().getEntry( object ); final EntityPersister persister; final Serializable id; - + if ( e == null ) { persister = source.getEntityPersister(null, object); //refresh() does not pass an entityName id = persister.getIdentifier( object, event.getSession() ); - if ( log.isTraceEnabled() ) { - log.trace( - "refreshing transient " + - MessageHelper.infoString( persister, id, source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.refreshingTransient(MessageHelper.infoString(persister, id, source.getFactory())); EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); if ( source.getPersistenceContext().getEntry(key) != null ) { throw new PersistentObjectException( @@ -108,12 +105,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener { } } else { - if ( log.isTraceEnabled() ) { - log.trace( - "refreshing " + - MessageHelper.infoString( e.getPersister(), e.getId(), source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.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" ); } @@ -138,14 +130,14 @@ public class DefaultRefreshEventListener implements RefreshEventListener { id, persister.getIdentifierType(), persister.getRootEntityName(), - source.getEntityMode(), + source.getEntityMode(), source.getFactory() ); persister.getCacheAccessStrategy().evict( ck ); } - + evictCachedCollections( persister, id, source.getFactory() ); - + String previousFetchProfile = source.getFetchProfile(); source.setFetchProfile("refresh"); Object result = persister.load( id, object, event.getLockOptions(), source ); @@ -161,7 +153,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener { } } source.setFetchProfile(previousFetchProfile); - + UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() ); } @@ -183,4 +175,22 @@ 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 3d9b3aaf63..7c51f1cc10 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,26 +24,27 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; +import java.io.Serializable; import org.hibernate.HibernateException; -import org.hibernate.TransientObjectException; -import org.hibernate.ReplicationMode; import org.hibernate.LockMode; +import org.hibernate.ReplicationMode; +import org.hibernate.TransientObjectException; import org.hibernate.engine.Cascade; import org.hibernate.engine.CascadingAction; import org.hibernate.engine.EntityKey; +import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.Status; import org.hibernate.event.EventSource; import org.hibernate.event.ReplicateEvent; import org.hibernate.event.ReplicateEventListener; -import org.hibernate.engine.SessionImplementor; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; import org.hibernate.type.Type; - -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -53,7 +54,8 @@ import org.slf4j.LoggerFactory; */ public class DefaultReplicateEventListener extends AbstractSaveEventListener implements ReplicateEventListener { - private static final Logger log = LoggerFactory.getLogger( DefaultReplicateEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultReplicateEventListener.class.getPackage().getName()); /** * Handle the given replicate event. @@ -65,14 +67,14 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp public void onReplicate(ReplicateEvent event) { final EventSource source = event.getSession(); if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) { - log.trace( "uninitialized proxy passed to replicate()" ); + LOG.uninitializedProxy(); return; } Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() ); if ( source.getPersistenceContext().isEntryFor( entity ) ) { - log.trace( "ignoring persistent instance passed to replicate()" ); + LOG.ignoringPersistentInstance(); //hum ... should we cascade anyway? throw an exception? fine like it is? return; } @@ -97,20 +99,15 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp } else { //what is the version on the database? - oldVersion = persister.getCurrentVersion( id, source ); + oldVersion = persister.getCurrentVersion( id, source ); } - if ( oldVersion != null ) { - if ( log.isTraceEnabled() ) { - log.trace( - "found existing row for " + - MessageHelper.infoString( persister, id, source.getFactory() ) - ); - } + if ( oldVersion != null ) { + if (LOG.isTraceEnabled()) LOG.foundExistingRow(MessageHelper.infoString(persister, id, source.getFactory())); /// HHH-2378 final Object realOldVersion = persister.isVersioned() ? oldVersion : null; - + boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion( entity, realOldVersion, @@ -118,25 +115,16 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp persister.getVersionType() ); - if ( canReplicate ) { - //will result in a SQL UPDATE: - performReplication( entity, id, realOldVersion, persister, replicationMode, source ); - } - else { - //else do nothing (don't even reassociate object!) - log.trace( "no need to replicate" ); - } + // 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(); //TODO: would it be better to do a refresh from db? } else { // no existing row - do an insert - if ( log.isTraceEnabled() ) { - log.trace( - "no existing row, replicating new instance " + - MessageHelper.infoString( persister, id, source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.noExistingRow(MessageHelper.infoString(persister, id, source.getFactory())); final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity! final EntityKey key = regenerate ? @@ -155,14 +143,16 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp } } - protected boolean visitCollectionsBeforeSave(Object entity, Serializable id, Object[] values, Type[] types, EventSource source) { + @Override + protected boolean visitCollectionsBeforeSave(Object entity, Serializable id, Object[] values, Type[] types, EventSource source) { //TODO: we use two visitors here, inefficient! OnReplicateVisitor visitor = new OnReplicateVisitor( source, id, entity, false ); visitor.processEntityPropertyValues( values, types ); return super.visitCollectionsBeforeSave( entity, id, values, types, source ); } - protected boolean substituteValuesIfNecessary( + @Override + protected boolean substituteValuesIfNecessary( Object entity, Serializable id, Object[] values, @@ -171,7 +161,8 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp return false; } - protected boolean isVersionIncrementDisabled() { + @Override + protected boolean isVersionIncrementDisabled() { return true; } @@ -183,12 +174,7 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp ReplicationMode replicationMode, EventSource source) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( - "replicating changes to " + - MessageHelper.infoString( persister, id, source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.replicatingChanges(MessageHelper.infoString(persister, id, source.getFactory())); new OnReplicateVisitor( source, id, entity, true ).process( entity, persister ); @@ -223,7 +209,39 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp } } - protected CascadingAction getCascadeAction() { + @Override + 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 5b228e7c94..8d189c15b1 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,13 +24,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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; -import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.PersistentObjectException; @@ -43,12 +40,17 @@ import org.hibernate.engine.EntityKey; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.Status; +import org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl; import org.hibernate.event.EventSource; import org.hibernate.event.SaveOrUpdateEvent; 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 @@ -59,7 +61,8 @@ import org.hibernate.proxy.HibernateProxy; */ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener implements SaveOrUpdateEventListener { - private static final Logger log = LoggerFactory.getLogger( DefaultSaveOrUpdateEventListener.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractBatchImpl.class.getPackage().getName()); /** * Handle the given update event. @@ -79,11 +82,8 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } } - if ( reassociateIfUninitializedProxy( object, source ) ) { - log.trace( "reassociated uninitialized proxy" ); - // an uninitialized proxy, noop, don't even need to - // return an id, since it is never a save() - } + // 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(); else { //initialize properties of the event: final Object entity = source.getPersistenceContext().unproxyAndReassociate( object ); @@ -119,7 +119,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException { - log.trace( "ignoring persistent instance" ); + LOG.ignoringPersistentInstance(); EntityEntry entityEntry = event.getEntry(); if ( entityEntry == null ) { @@ -155,12 +155,9 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } - if ( log.isTraceEnabled() ) { - log.trace( - "object already associated with session: " + - MessageHelper.infoString( entityEntry.getPersister(), savedId, factory ) - ); - } + if (LOG.isTraceEnabled()) LOG.objectAlreadyAssociatedWithSession(MessageHelper.infoString(entityEntry.getPersister(), + savedId, + factory)); return savedId; @@ -178,7 +175,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener */ protected Serializable entityIsTransient(SaveOrUpdateEvent event) { - log.trace( "saving transient instance" ); + LOG.savingTransientInstance(); final EventSource source = event.getSession(); @@ -225,7 +222,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener */ protected void entityIsDetached(SaveOrUpdateEvent event) { - log.trace( "updating detached instance" ); + LOG.updatingDetachedInstance(); if ( event.getSession().getPersistenceContext().isEntryFor( event.getEntity() ) ) { @@ -285,76 +282,61 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener Object entity, EntityPersister persister) throws HibernateException { - if ( !persister.isMutable() ) { - log.trace( "immutable instance passed to performUpdate()" ); - } + if (!persister.isMutable()) LOG.immutableInstancePassedToPerformUpdate(); - if ( log.isTraceEnabled() ) { - log.trace( - "updating " + - MessageHelper.infoString( - persister, event.getRequestedId(), event.getSession().getFactory() - ) - ); - } + if (LOG.isTraceEnabled()) LOG.updating(MessageHelper.infoString(persister, + event.getRequestedId(), + event.getSession().getFactory())); - final EventSource source = event.getSession(); + final EventSource source = event.getSession(); - EntityKey key = new EntityKey( event.getRequestedId(), persister, source.getEntityMode() ); + EntityKey key = new EntityKey(event.getRequestedId(), persister, source.getEntityMode()); - source.getPersistenceContext().checkUniqueness( key, entity ); + source.getPersistenceContext().checkUniqueness(key, entity); - if ( invokeUpdateLifecycle( entity, persister, source ) ) { - reassociate( event, event.getObject(), event.getRequestedId(), persister ); - return; - } + if (invokeUpdateLifecycle(entity, persister, source)) { + reassociate(event, event.getObject(), event.getRequestedId(), persister); + return; + } - // this is a transient object with existing persistent state not loaded by the session + // this is a transient object with existing persistent state not loaded by the session - new OnUpdateVisitor( source, event.getRequestedId(), entity ).process( entity, persister ); + new OnUpdateVisitor(source, event.getRequestedId(), entity).process(entity, persister); - //TODO: put this stuff back in to read snapshot from - // the second-level cache (needs some extra work) - /*Object[] cachedState = null; + // TODO: put this stuff back in to read snapshot from + // the second-level cache (needs some extra work) + /*Object[] cachedState = null; - if ( persister.hasCache() ) { - CacheEntry entry = (CacheEntry) persister.getCache() - .get( event.getRequestedId(), source.getTimestamp() ); - cachedState = entry==null ? - null : - entry.getState(); //TODO: half-assemble this stuff - }*/ + if ( persister.hasCache() ) { + CacheEntry entry = (CacheEntry) persister.getCache() + .get( event.getRequestedId(), source.getTimestamp() ); + cachedState = entry==null ? + null : + entry.getState(); //TODO: half-assemble this stuff + }*/ - source.getPersistenceContext().addEntity( - entity, - ( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ), - null, //cachedState, - key, - persister.getVersion( entity, source.getEntityMode() ), - LockMode.NONE, - true, - persister, - false, - true //assume true, since we don't really know, and it doesn't matter - ); + source.getPersistenceContext().addEntity(entity, (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY), null, // cachedState, + key, + persister.getVersion(entity, source.getEntityMode()), + LockMode.NONE, + true, + persister, + false, + true // assume true, since we don't really know, and it doesn't matter + ); - persister.afterReassociate( entity, source ); + persister.afterReassociate(entity, source); - if ( log.isTraceEnabled() ) { - log.trace( - "updating " + - MessageHelper.infoString( persister, event.getRequestedId(), source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.updating(MessageHelper.infoString(persister, event.getRequestedId(), source.getFactory())); - cascadeOnUpdate( event, persister, entity ); + cascadeOnUpdate(event, persister, entity); } protected boolean invokeUpdateLifecycle(Object entity, EntityPersister persister, EventSource source) { if ( persister.implementsLifecycle( source.getEntityMode() ) ) { - log.debug( "calling onUpdate()" ); + LOG.callingOnUpdate(); if ( ( ( Lifecycle ) entity ).onUpdate( source ) ) { - log.debug( "update vetoed by onUpdate()" ); + LOG.updateVetoedByOnUpdate(); return true; } } @@ -381,7 +363,51 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener } } - protected CascadingAction getCascadeAction() { + @Override + 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 76610e7c55..f56f056094 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,8 +24,7 @@ */ package org.hibernate.event.def; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.HibernateException; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.CollectionEntry; @@ -33,6 +32,10 @@ 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. @@ -42,14 +45,16 @@ import org.hibernate.type.CollectionType; * @author Gavin King */ public class EvictVisitor extends AbstractVisitor { - - private static final Logger log = LoggerFactory.getLogger(EvictVisitor.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + EvictVisitor.class.getPackage().getName()); EvictVisitor(EventSource session) { super(session); } - Object processCollection(Object collection, CollectionType type) + @Override + Object processCollection(Object collection, CollectionType type) throws HibernateException { if (collection!=null) evictCollection(collection, type); @@ -75,17 +80,25 @@ public class EvictVisitor extends AbstractVisitor { private void evictCollection(PersistentCollection collection) { CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection); - if ( log.isDebugEnabled() ) - log.debug( - "evicting collection: " + - MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getFactory() ) - ); + if (LOG.isDebugEnabled()) LOG.evictingCollection(MessageHelper.collectionInfoString(ce.getLoadedPersister(), + ce.getLoadedKey(), + getSession().getFactory())); if ( ce.getLoadedPersister() != null && ce.getLoadedKey() != null ) { //TODO: is this 100% correct? - getSession().getPersistenceContext().getCollectionsByKey().remove( - new CollectionKey( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getEntityMode() ) + getSession().getPersistenceContext().getCollectionsByKey().remove( + new CollectionKey( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getEntityMode() ) ); } } + /** + * 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 f89151e3fe..67428a5ac4 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,10 +23,8 @@ */ package org.hibernate.event.def; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.action.CollectionRemoveAction; import org.hibernate.event.EventSource; @@ -34,6 +32,10 @@ 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. @@ -42,7 +44,8 @@ import org.hibernate.type.Type; */ public abstract class ReattachVisitor extends ProxyVisitor { - private static final Logger log = LoggerFactory.getLogger( ReattachVisitor.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ReattachVisitor.class.getPackage().getName()); private final Serializable ownerIdentifier; private final Object owner; @@ -74,7 +77,8 @@ public abstract class ReattachVisitor extends ProxyVisitor { /** * {@inheritDoc} */ - Object processComponent(Object component, CompositeType componentType) throws HibernateException { + @Override + Object processComponent(Object component, CompositeType componentType) throws HibernateException { Type[] types = componentType.getSubtypes(); if ( component == null ) { processValues( new Object[types.length], types ); @@ -95,12 +99,9 @@ public abstract class ReattachVisitor extends ProxyVisitor { * @throws HibernateException */ void removeCollection(CollectionPersister role, Serializable collectionKey, EventSource source) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( - "collection dereferenced while transient " + - MessageHelper.collectionInfoString( role, ownerIdentifier, source.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.collectionDereferencedWhileTransient(MessageHelper.collectionInfoString(role, + ownerIdentifier, + source.getFactory())); source.getActionQueue().addAction( new CollectionRemoveAction( owner, role, collectionKey, false, source ) ); } @@ -114,12 +115,20 @@ public abstract class ReattachVisitor extends ProxyVisitor { * @return */ final Serializable extractCollectionKeyFromOwner(CollectionPersister role) { - if ( role.getCollectionType().useLHSPrimaryKey() ) { - return ownerIdentifier; - } - else { - return ( Serializable ) role.getOwnerEntityPersister().getPropertyValue( owner, role.getCollectionType().getLHSPropertyName(), getSession().getEntityMode() ); - } - + if (role.getCollectionType().useLHSPrimaryKey()) return ownerIdentifier; + return (Serializable)role.getOwnerEntityPersister().getPropertyValue(owner, + 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 e1c7764eee..afb1d8e1a3 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,8 +23,7 @@ */ package org.hibernate.event.def; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.TRACE; import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.collection.PersistentCollection; @@ -36,6 +35,10 @@ 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 @@ -44,7 +47,8 @@ import org.hibernate.type.Type; */ public class WrapVisitor extends ProxyVisitor { - private static final Logger log = LoggerFactory.getLogger(WrapVisitor.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + WrapVisitor.class.getPackage().getName()); boolean substitute = false; @@ -56,7 +60,8 @@ public class WrapVisitor extends ProxyVisitor { super(session); } - Object processCollection(Object collection, CollectionType collectionType) + @Override + Object processCollection(Object collection, CollectionType collectionType) throws HibernateException { if ( collection!=null && (collection instanceof PersistentCollection) ) { @@ -90,7 +95,7 @@ public class WrapVisitor extends ProxyVisitor { final PersistenceContext persistenceContext = session.getPersistenceContext(); //TODO: move into collection type, so we can use polymorphism! if ( collectionType.hasHolder( session.getEntityMode() ) ) { - + if (collection==CollectionType.UNFETCHED_COLLECTION) return null; PersistentCollection ah = persistenceContext.getCollectionHolder(collection); @@ -106,7 +111,7 @@ public class WrapVisitor extends ProxyVisitor { PersistentCollection persistentCollection = collectionType.wrap(session, collection); persistenceContext.addNewCollection( persister, persistentCollection ); - if ( log.isTraceEnabled() ) log.trace( "Wrapped collection in role: " + collectionType.getRole() ); + if (LOG.isTraceEnabled()) LOG.wrappedCollectionInRole(collectionType.getRole()); return persistentCollection; //Force a substitution! @@ -116,7 +121,8 @@ public class WrapVisitor extends ProxyVisitor { } - void processValue(int i, Object[] values, Type[] types) { + @Override + void processValue(int i, Object[] values, Type[] types) { Object result = processValue( values[i], types[i] ); if (result!=null) { substitute = true; @@ -124,7 +130,8 @@ public class WrapVisitor extends ProxyVisitor { } } - Object processComponent(Object component, CompositeType componentType) + @Override + Object processComponent(Object component, CompositeType componentType) throws HibernateException { if (component!=null) { @@ -146,7 +153,8 @@ public class WrapVisitor extends ProxyVisitor { return null; } - void process(Object object, EntityPersister persister) throws HibernateException { + @Override + void process(Object object, EntityPersister persister) throws HibernateException { EntityMode entityMode = getSession().getEntityMode(); Object[] values = persister.getPropertyValues( object, entityMode ); Type[] types = persister.getPropertyTypes(); @@ -156,4 +164,14 @@ public class WrapVisitor extends ProxyVisitor { } } + /** + * 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 b5d52b9607..280e41d061 100644 --- a/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/exception/SQLExceptionConverterFactory.java @@ -24,18 +24,21 @@ */ package org.hibernate.exception; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.util.ReflectHelper; import org.hibernate.util.StringHelper; - -import java.lang.reflect.Constructor; -import java.sql.SQLException; -import java.util.Properties; +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. @@ -44,7 +47,8 @@ import java.util.Properties; */ public class SQLExceptionConverterFactory { - private static final Logger log = LoggerFactory.getLogger( SQLExceptionConverterFactory.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLExceptionConverterFactory.class.getPackage().getName()); private SQLExceptionConverterFactory() { // Private constructor - stops checkstyle from complaining. @@ -72,7 +76,7 @@ public class SQLExceptionConverterFactory { } if ( converter == null ) { - log.trace( "Using dialect defined converter" ); + LOG.usingDialectDefinedConverter(); converter = dialect.buildSQLExceptionConverter(); } @@ -81,7 +85,7 @@ public class SQLExceptionConverterFactory { ( ( Configurable ) converter ).configure( properties ); } catch ( HibernateException e ) { - log.warn( "Unable to configure SQLExceptionConverter", e ); + LOG.unableToConfigureSqlExceptionConverter(e); throw e; } } @@ -105,7 +109,7 @@ public class SQLExceptionConverterFactory { private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) { try { - log.trace( "Attempting to construct instance of specified SQLExceptionConverter [" + converterClassName + "]" ); + LOG.attemptingToConstructSqlExceptionConverter(converterClassName); Class converterClass = ReflectHelper.classForName( converterClassName ); // First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param... @@ -129,9 +133,32 @@ public class SQLExceptionConverterFactory { } catch ( Throwable t ) { - log.warn( "Unable to construct instance of specified SQLExceptionConverter", t ); + LOG.unableToConstructSqlExceptionConverter(t); } 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 37b8f85aa1..304690879e 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/QuerySplitter.java @@ -24,16 +24,18 @@ */ package org.hibernate.hql; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.WARN; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; import org.hibernate.MappingException; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.classic.ParserHelper; import org.hibernate.util.StringHelper; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; +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. @@ -44,7 +46,8 @@ import java.util.Set; */ public final class QuerySplitter { - private static final Logger log = LoggerFactory.getLogger( QuerySplitter.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QuerySplitter.class.getPackage().getName()); private static final Set BEFORE_CLASS_TOKENS = new HashSet(); private static final Set NOT_AFTER_CLASS_TOKENS = new HashSet(); @@ -93,7 +96,7 @@ public final class QuerySplitter { templateQuery.append( tokens[0] ); if ( "select".equals( tokens[0].toLowerCase() ) ) isSelectClause = true; - + for ( int i = 1; i < tokens.length; i++ ) { //update last non-whitespace token, if necessary @@ -113,10 +116,10 @@ public final class QuerySplitter { } } - boolean process = !isSelectClause && - isJavaIdentifier( token ) && + boolean process = !isSelectClause && + isJavaIdentifier( token ) && isPossiblyClassName( last, next ); - + if (process) { String importedClassName = getImportedClass( token, factory ); if ( importedClassName != null ) { @@ -136,14 +139,14 @@ public final class QuerySplitter { } String[] results = StringHelper.multiply( templateQuery.toString(), placeholders.iterator(), replacements.iterator() ); - if ( results.length == 0 ) log.warn( "no persistent classes found for query class: " + query ); + if (results.length == 0) LOG.noPersistentClassesFound(query); return results; } private static boolean isPossiblyClassName(String last, String next) { - return "class".equals( last ) || ( - BEFORE_CLASS_TOKENS.contains( last ) && - !NOT_AFTER_CLASS_TOKENS.contains( next ) + return "class".equals( last ) || ( + BEFORE_CLASS_TOKENS.contains( last ) && + !NOT_AFTER_CLASS_TOKENS.contains( next ) ); } @@ -154,4 +157,15 @@ 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 d1ca8b2ccd..995521c30a 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,14 +24,16 @@ */ package org.hibernate.hql.ast; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.INFO; +import java.util.Map; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.FilterTranslator; import org.hibernate.hql.QueryTranslator; import org.hibernate.hql.QueryTranslatorFactory; - -import java.util.Map; +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 @@ -41,10 +43,11 @@ import java.util.Map; */ public class ASTQueryTranslatorFactory implements QueryTranslatorFactory { - private static final Logger log = LoggerFactory.getLogger( ASTQueryTranslatorFactory.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ASTQueryTranslatorFactory.class.getPackage().getName()); public ASTQueryTranslatorFactory() { - log.info( "Using ASTQueryTranslatorFactory" ); + LOG.usingAstQueryTranslatorFactory(); } /** @@ -69,4 +72,14 @@ public class ASTQueryTranslatorFactory implements QueryTranslatorFactory { 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 6a77babd7f..e78bd8cbeb 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,21 +24,24 @@ */ package org.hibernate.hql.ast; -import antlr.RecognitionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.QueryException; - +import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +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; /** * An error handler that counts parsing errors and warnings. */ public class ErrorCounter implements ParseErrorHandler { - private Logger log = LoggerFactory.getLogger( ErrorCounter.class ); - private Logger hqlLog = LoggerFactory.getLogger( "org.hibernate.hql.PARSER" ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ErrorCounter.class.getPackage().getName()); private List errorList = new ArrayList(); private List warningList = new ArrayList(); @@ -47,13 +50,11 @@ public class ErrorCounter implements ParseErrorHandler { public void reportError(RecognitionException e) { reportError( e.toString() ); recognitionExceptions.add( e ); - if ( log.isDebugEnabled() ) { - log.debug( e.toString(), e ); - } + LOG.error(e.toString(), e); } public void reportError(String message) { - hqlLog.error( message ); + LOG.error(message); errorList.add( message ); } @@ -62,7 +63,7 @@ public class ErrorCounter implements ParseErrorHandler { } public void reportWarning(String message) { - hqlLog.debug( message ); + LOG.debug(message); warningList.add( message ); } @@ -78,18 +79,20 @@ public class ErrorCounter implements ParseErrorHandler { public void throwQueryException() throws QueryException { if ( getErrorCount() > 0 ) { - if ( recognitionExceptions.size() > 0 ) { - throw QuerySyntaxException.convert( ( RecognitionException ) recognitionExceptions.get( 0 ) ); - } - else { - throw new QueryException( getErrorString() ); - } - } - else { - // all clear - if ( log.isDebugEnabled() ) { - log.debug( "throwQueryException() : no errors" ); - } - } + if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert((RecognitionException)recognitionExceptions.get(0)); + throw new QueryException(getErrorString()); + } + LOG.throwQueryException(); } + + /** + * 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 a7bea13c04..f0b3170c78 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,10 +24,21 @@ */ 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.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; @@ -35,14 +46,6 @@ import antlr.Token; import antlr.TokenStream; import antlr.TokenStreamException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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.QueryException; -import org.hibernate.util.StringHelper; /** * Implements the semantic action methods defined in the HQL base parser to keep the grammar @@ -51,10 +54,9 @@ import org.hibernate.util.StringHelper; * @author Joshua Davis (pgmjsd@sourceforge.net) */ public final class HqlParser extends HqlBaseParser { - /** - * A logger for this class. - */ - private static final Logger log = LoggerFactory.getLogger( HqlParser.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HqlBaseParser.class.getPackage().getName()); private ParseErrorHandler parseErrorHandler; private ASTPrinter printer = getASTPrinter(); @@ -80,31 +82,32 @@ public final class HqlParser extends HqlBaseParser { private int traceDepth = 0; - public void traceIn(String ruleName) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceIn(String ruleName) { + if (inputState.guessing > 0) return; String prefix = StringHelper.repeat( '-', (traceDepth++ * 2) ) + "-> "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } - public void traceOut(String ruleName) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceOut(String ruleName) { + if (inputState.guessing > 0) return; String prefix = "<-" + StringHelper.repeat( '-', (--traceDepth * 2) ) + " "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } - public void reportError(RecognitionException e) { + @Override + public void reportError(RecognitionException e) { parseErrorHandler.reportError( e ); // Use the delegate. } - public void reportError(String s) { + @Override + public void reportError(String s) { parseErrorHandler.reportError( s ); // Use the delegate. } - public void reportWarning(String s) { + @Override + public void reportWarning(String s) { parseErrorHandler.reportWarning( s ); } @@ -121,7 +124,8 @@ public final class HqlParser extends HqlBaseParser { * @throws antlr.RecognitionException if the substitution was not possible. * @throws antlr.TokenStreamException if the substitution was not possible. */ - public AST handleIdentifierError(Token token, RecognitionException ex) throws RecognitionException, TokenStreamException { + @Override + public AST handleIdentifierError(Token token, RecognitionException ex) throws RecognitionException, TokenStreamException { // If the token can tell us if it could be an identifier... if ( token instanceof HqlToken ) { HqlToken hqlToken = ( HqlToken ) token; @@ -157,8 +161,9 @@ public final class HqlParser extends HqlBaseParser { * @param x The sub tree to transform, the parent is assumed to be NOT. * @return AST - The equivalent sub-tree. */ - public AST negateNode(AST x) { - //TODO: switch statements are always evil! We already had bugs because + @Override + public AST negateNode(AST x) { + //TODO: switch statements are always evil! We already had bugs because // of forgotten token types. Use polymorphism for this! switch ( x.getType() ) { case OR: @@ -244,9 +249,10 @@ public final class HqlParser extends HqlBaseParser { * @param x The equality expression. * @return AST - The clean sub-tree. */ - public AST processEqualityExpression(AST x) { + @Override + public AST processEqualityExpression(AST x) { if ( x == null ) { - log.warn( "processEqualityExpression() : No expression to process!" ); + LOG.processEqualityExpression(); return null; } @@ -322,7 +328,8 @@ public final class HqlParser extends HqlBaseParser { setASTFactory(new HqlASTFactory()); // Create nodes that track line and column number. } - public void weakKeywords() throws TokenStreamException { + @Override + public void weakKeywords() throws TokenStreamException { int t = LA( 1 ); switch ( t ) { @@ -332,9 +339,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 ); - if ( log.isDebugEnabled() ) { - log.debug( "weakKeywords() : new LT(1) token - " + LT( 1 ) ); - } + LOG.weakKeywords( LT( 1 ) ); } break; default: @@ -343,33 +348,31 @@ public final class HqlParser extends HqlBaseParser { HqlToken hqlToken = (HqlToken)LT(1); if (hqlToken.isPossibleID()) { hqlToken.setType(IDENT); - if ( log.isDebugEnabled() ) { - log.debug( "weakKeywords() : new LT(1) token - " + LT( 1 ) ); - } + LOG.weakKeywords(LT(1)); } } break; } } + @Override public void handleDotIdent() throws TokenStreamException { // This handles HHH-354, where there is a strange property name in a where clause. // If the lookahead contains a DOT then something that isn't an IDENT... if (LA(1) == DOT && LA(2) != IDENT) { - // See if the second lookahed token can be an identifier. + // See if the second lookahead token can be an identifier. HqlToken t = (HqlToken)LT(2); if (t.isPossibleID()) { // Set it! LT( 2 ).setType( IDENT ); - if ( log.isDebugEnabled() ) { - log.debug( "handleDotIdent() : new LT(2) token - " + LT( 1 ) ); - } + LOG.handleDotIdent(LT(1)); } } } - public void processMemberOf(Token n, AST p, ASTPair currentAST) { + @Override + public void processMemberOf(Token n, AST p, ASTPair currentAST) { AST inAst = n == null ? astFactory.create( IN, "in" ) : astFactory.create( NOT_IN, "not in" ); astFactory.makeASTRoot( currentAST, inAst ); AST ast = createSubquery( p ); @@ -381,4 +384,23 @@ 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 e7f0e3964c..4514e51f5a 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,11 @@ */ 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; import java.util.Calendar; import java.util.Date; import java.util.HashMap; @@ -34,12 +37,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Arrays; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.QueryException; import org.hibernate.HibernateException; +import org.hibernate.QueryException; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.ParameterBinder; import org.hibernate.engine.SessionFactoryImplementor; @@ -56,12 +55,15 @@ import org.hibernate.hql.ast.tree.DeleteStatement; import org.hibernate.hql.ast.tree.DotNode; import org.hibernate.hql.ast.tree.FromClause; import org.hibernate.hql.ast.tree.FromElement; +import org.hibernate.hql.ast.tree.FromElementFactory; import org.hibernate.hql.ast.tree.FromReferenceNode; import org.hibernate.hql.ast.tree.IdentNode; import org.hibernate.hql.ast.tree.IndexNode; import org.hibernate.hql.ast.tree.InsertStatement; import org.hibernate.hql.ast.tree.IntoClause; import org.hibernate.hql.ast.tree.MethodNode; +import org.hibernate.hql.ast.tree.OperatorNode; +import org.hibernate.hql.ast.tree.ParameterContainer; import org.hibernate.hql.ast.tree.ParameterNode; import org.hibernate.hql.ast.tree.QueryNode; import org.hibernate.hql.ast.tree.ResolvableNode; @@ -70,37 +72,37 @@ import org.hibernate.hql.ast.tree.ResultVariableRefNode; import org.hibernate.hql.ast.tree.SelectClause; import org.hibernate.hql.ast.tree.SelectExpression; import org.hibernate.hql.ast.tree.UpdateStatement; -import org.hibernate.hql.ast.tree.OperatorNode; -import org.hibernate.hql.ast.tree.ParameterContainer; -import org.hibernate.hql.ast.tree.FromElementFactory; import org.hibernate.hql.ast.util.ASTPrinter; import org.hibernate.hql.ast.util.ASTUtil; import org.hibernate.hql.ast.util.AliasGenerator; import org.hibernate.hql.ast.util.JoinProcessor; import org.hibernate.hql.ast.util.LiteralProcessor; +import org.hibernate.hql.ast.util.NodeTraverser; import org.hibernate.hql.ast.util.SessionFactoryHelper; import org.hibernate.hql.ast.util.SyntheticAndFactory; -import org.hibernate.hql.ast.util.NodeTraverser; import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.PostInsertIdentifierGenerator; import org.hibernate.id.SequenceGenerator; +import org.hibernate.param.CollectionFilterKeyParameterSpecification; import org.hibernate.param.NamedParameterSpecification; import org.hibernate.param.ParameterSpecification; import org.hibernate.param.PositionalParameterSpecification; import org.hibernate.param.VersionTypeSeedParameterSpecification; -import org.hibernate.param.CollectionFilterKeyParameterSpecification; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.JoinFragment; import org.hibernate.type.AssociationType; +import org.hibernate.type.ComponentType; +import org.hibernate.type.DbTimestampType; import org.hibernate.type.Type; import org.hibernate.type.VersionType; -import org.hibernate.type.DbTimestampType; -import org.hibernate.type.ComponentType; 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; @@ -118,7 +120,9 @@ import antlr.collections.AST; * @see SqlASTFactory */ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, ParameterBinder.NamedParameterSource { - private static final Logger log = LoggerFactory.getLogger( HqlSqlWalker.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HqlSqlWalker.class.getPackage().getName()); private final QueryTranslatorImpl queryTranslatorImpl; private final HqlParser hqlParser; @@ -185,13 +189,12 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par private int traceDepth = 0; - public void traceIn(String ruleName, AST tree) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceIn(String ruleName, AST tree) { + if (inputState.guessing > 0) return; String prefix = StringHelper.repeat( '-', (traceDepth++ * 2) ) + "-> "; String traceText = ruleName + " (" + buildTraceNodeName(tree) + ")"; - log.trace( prefix + traceText ); + LOG.trace(prefix + traceText); } private String buildTraceNodeName(AST tree) { @@ -200,16 +203,16 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par : tree.getText() + " [" + printer.getTokenTypeName( tree.getType() ) + "]"; } - public void traceOut(String ruleName, AST tree) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceOut(String ruleName, AST tree) { + if (inputState.guessing > 0) return; String prefix = "<-" + StringHelper.repeat( '-', (--traceDepth * 2) ) + " "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } - protected void prepareFromClauseInputTree(AST fromClauseInput) { + @Override + protected void prepareFromClauseInputTree(AST fromClauseInput) { if ( !isSubQuery() ) { // // inject param specifications to account for dynamic filter param values // if ( ! getEnabledFilters().isEmpty() ) { @@ -237,7 +240,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par // } if ( isFilter() ) { - // Handle collection-fiter compilation. + // Handle collection-filter compilation. // IMPORTANT NOTE: This is modifying the INPUT (HQL) tree, not the output tree! QueryableCollection persister = sessionFactoryHelper.getCollectionPersister( collectionFilterRole ); Type collectionElementType = persister.getElementType(); @@ -251,9 +254,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par ASTUtil.createSibling( inputAstFactory, HqlTokenTypes.ALIAS, "this", fromElement ); fromClauseInput.addChild( fromElement ); // Show the modified AST. - if ( log.isDebugEnabled() ) { - log.debug( "prepareFromClauseInputTree() : Filter - Added 'this' as a from element..." ); - } + LOG.prepareFromClauseInputTree(); queryTranslatorImpl.showHqlAst( hqlParser.getAST() ); // Create a parameter specification for the collection filter... @@ -296,15 +297,18 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return parseErrorHandler; } - public void reportError(RecognitionException e) { + @Override + public void reportError(RecognitionException e) { parseErrorHandler.reportError( e ); // Use the delegate. } - public void reportError(String s) { + @Override + public void reportError(String s) { parseErrorHandler.reportError( s ); // Use the delegate. } - public void reportWarning(String s) { + @Override + public void reportWarning(String s) { parseErrorHandler.reportWarning( s ); } @@ -318,13 +322,15 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return querySpaces; } - protected AST createFromElement(String path, AST alias, AST propertyFetch) throws SemanticException { + @Override + protected AST createFromElement(String path, AST alias, AST propertyFetch) throws SemanticException { FromElement fromElement = currentFromClause.addFromElement( path, alias ); fromElement.setAllPropertyFetch(propertyFetch!=null); return fromElement; } - protected AST createFromFilterElement(AST filterEntity, AST alias) throws SemanticException { + @Override + protected AST createFromFilterElement(AST filterEntity, AST alias) throws SemanticException { FromElement fromElement = currentFromClause.addFromElement( filterEntity.getText(), alias ); FromClause fromClause = fromElement.getFromClause(); QueryableCollection persister = sessionFactoryHelper.getCollectionPersister( collectionFilterRole ); @@ -345,13 +351,12 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par join.addCondition( fkTableAlias, keyColumnNames, " = ?" ); fromElement.setJoinSequence( join ); fromElement.setFilter( true ); - if ( log.isDebugEnabled() ) { - log.debug( "createFromFilterElement() : processed filter FROM element." ); - } + LOG.createFromFilterElement(); return fromElement; } - protected void createFromJoinElement( + @Override + protected void createFromJoinElement( AST path, AST alias, int joinType, @@ -376,7 +381,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par final FromElement fromElement; if ( dot.getDataType() != null && dot.getDataType().isComponentType() ) { - FromElementFactory factory = new FromElementFactory( + FromElementFactory factory = new FromElementFactory( getCurrentFromClause(), dot.getLhs().getFromElement(), dot.getPropertyPath(), @@ -398,17 +403,13 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - if ( log.isDebugEnabled() ) { - log.debug( "createFromJoinElement() : " + getASTPrinter().showAsString( fromElement, "-- join tree --" ) ); - } + if (LOG.isDebugEnabled()) LOG.createFromJoinElement(getASTPrinter().showAsString(fromElement, LOG.joinTreeHeader())); } private void handleWithFragment(FromElement fromElement, AST hqlWithNode) throws SemanticException { try { withClause( hqlWithNode ); AST hqlSqlWithNode = returnAST; - if ( log.isDebugEnabled() ) { - log.debug( "handleWithFragment() : " + getASTPrinter().showAsString( hqlSqlWithNode, "-- with clause --" ) ); - } + if (LOG.isDebugEnabled()) LOG.handleWithFragment(getASTPrinter().showAsString(hqlSqlWithNode, LOG.withClauseHeader())); WithClauseVisitor visitor = new WithClauseVisitor( fromElement ); NodeTraverser traverser = new NodeTraverser( visitor ); traverser.traverseDepthFirst( hqlSqlWithNode ); @@ -450,7 +451,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } public void visit(AST node) { - // todo : currently expects that the individual with expressions apply to the same sql table join. + // TODO : currently expects that the individual with expressions apply to the same sql table join. // This may not be the case for joined-subclass where the property values // might be coming from different tables in the joined hierarchy. At some // point we should expand this to support that capability. However, that has @@ -471,9 +472,9 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par else { referencedFromElement = fromElement; joinAlias = extractAppliedAlias( dotNode ); - // todo : temporary + // TODO : temporary // needed because currently persister is the one that - // creates and renders the join fragments for inheritence + // creates and renders the join fragments for inheritance // hierarchies... if ( !joinAlias.equals( referencedFromElement.getTableAlias() ) ) { throw new InvalidWithClauseException( "with clause can only reference columns in the driving table" ); @@ -520,7 +521,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par * @param fromNode The new 'FROM' context. * @param inputFromNode The from node from the input AST. */ - protected void pushFromClause(AST fromNode, AST inputFromNode) { + @Override + protected void pushFromClause(AST fromNode, AST inputFromNode) { FromClause newFromClause = ( FromClause ) fromNode; newFromClause.setParentFromClause( currentFromClause ); currentFromClause = newFromClause; @@ -533,14 +535,16 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par currentFromClause = currentFromClause.getParentFromClause(); } - protected void lookupAlias(AST aliasRef) + @Override + protected void lookupAlias(AST aliasRef) throws SemanticException { FromElement alias = currentFromClause.getFromElement( aliasRef.getText() ); FromReferenceNode aliasRefNode = ( FromReferenceNode ) aliasRef; aliasRefNode.setFromElement( alias ); } - protected void setImpliedJoinType(int joinType) { + @Override + protected void setImpliedJoinType(int joinType) { impliedJoinType = JoinProcessor.toHibernateJoinType( joinType ); } @@ -548,16 +552,15 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return impliedJoinType; } - protected AST lookupProperty(AST dot, boolean root, boolean inSelect) throws SemanticException { + @Override + protected AST lookupProperty(AST dot, boolean root, boolean inSelect) throws SemanticException { DotNode dotNode = ( DotNode ) dot; FromReferenceNode lhs = dotNode.getLhs(); AST rhs = lhs.getNextSibling(); switch ( rhs.getType() ) { case SqlTokenTypes.ELEMENTS: case SqlTokenTypes.INDICES: - if ( log.isDebugEnabled() ) { - log.debug( "lookupProperty() " + dotNode.getPath() + " => " + rhs.getText() + "(" + lhs.getPath() + ")" ); - } + if (LOG.isDebugEnabled()) LOG.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 ); @@ -573,7 +576,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected boolean isNonQualifiedPropertyRef(AST ident) { + @Override + protected boolean isNonQualifiedPropertyRef(AST ident) { final String identText = ident.getText(); if ( currentFromClause.isFromElementAlias( identText ) ) { return false; @@ -583,7 +587,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par if ( fromElements.size() == 1 ) { final FromElement fromElement = ( FromElement ) fromElements.get( 0 ); try { - log.trace( "attempting to resolve property [" + identText + "] as a non-qualified ref" ); + LOG.resolvingPropertyAsNonQualifiedReference(identText); return fromElement.getPropertyMapping( identText ).toType( identText ) != null; } catch( QueryException e ) { @@ -594,7 +598,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return false; } - protected AST lookupNonQualifiedProperty(AST property) throws SemanticException { + @Override + protected AST lookupNonQualifiedProperty(AST property) throws SemanticException { final FromElement fromElement = ( FromElement ) currentFromClause.getExplicitFromElements().get( 0 ); AST syntheticDotNode = generateSyntheticDotNodeForNonQualifiedPropertyRef( property, fromElement ); return lookupProperty( syntheticDotNode, false, getCurrentClauseType() == HqlSqlTokenTypes.SELECT ); @@ -615,10 +620,9 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return dot; } - protected void processQuery(AST select, AST query) throws SemanticException { - if ( log.isDebugEnabled() ) { - log.debug( "processQuery() : " + query.toStringTree() ); - } + @Override + protected void processQuery(AST select, AST query) throws SemanticException { + LOG.processQuery(query.toStringTree()); try { QueryNode qn = ( QueryNode ) query; @@ -702,13 +706,15 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } - protected void postProcessUpdate(AST update) throws SemanticException { + @Override + protected void postProcessUpdate(AST update) throws SemanticException { UpdateStatement updateStatement = ( UpdateStatement ) update; postProcessDML( updateStatement ); } - protected void postProcessDelete(AST delete) throws SemanticException { + @Override + protected void postProcessDelete(AST delete) throws SemanticException { postProcessDML( ( DeleteStatement ) delete ); } @@ -717,7 +723,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par || PostInsertIdentifierGenerator.class.isAssignableFrom( generator.getClass() ); } - protected void postProcessInsert(AST insert) throws SemanticException, QueryException { + @Override + protected void postProcessInsert(AST insert) throws SemanticException, QueryException { InsertStatement insertStatement = ( InsertStatement ) insert; insertStatement.validate(); @@ -859,12 +866,11 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par select.setNextSibling( sibling ); selectClause = ( SelectClause ) select; selectClause.initializeDerivedSelectClause( currentFromClause ); - if ( log.isDebugEnabled() ) { - log.debug( "Derived SELECT clause created." ); - } + LOG.derivedSelectClauseCreated(); } - protected void resolve(AST node) throws SemanticException { + @Override + protected void resolve(AST node) throws SemanticException { if ( node != null ) { // This is called when it's time to fully resolve a path expression. ResolvableNode r = ( ResolvableNode ) node; @@ -877,7 +883,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected void resolveSelectExpression(AST node) throws SemanticException { + @Override + protected void resolveSelectExpression(AST node) throws SemanticException { // This is called when it's time to fully resolve a path expression. int type = node.getType(); switch ( type ) { @@ -903,7 +910,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected void beforeSelectClause() throws SemanticException { + @Override + protected void beforeSelectClause() throws SemanticException { // Turn off includeSubclasses on all FromElements. FromClause from = getCurrentFromClause(); List fromElements = from.getFromElements(); @@ -913,7 +921,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected AST generatePositionalParameter(AST inputNode) throws SemanticException { + @Override + protected AST generatePositionalParameter(AST inputNode) throws SemanticException { if ( namedParameters.size() > 0 ) { throw new SemanticException( "cannot define positional parameter after any named parameters have been defined" ); } @@ -928,7 +937,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return parameter; } - protected AST generateNamedParameter(AST delimiterNode, AST nameNode) throws SemanticException { + @Override + protected AST generateNamedParameter(AST delimiterNode, AST nameNode) throws SemanticException { String name = nameNode.getText(); trackNamedParameterPositions( name ); @@ -964,38 +974,46 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected void processConstant(AST constant) throws SemanticException { + @Override + protected void processConstant(AST constant) throws SemanticException { literalProcessor.processConstant( constant, true ); // Use the delegate, resolve identifiers as FROM element aliases. } - protected void processBoolean(AST constant) throws SemanticException { + @Override + protected void processBoolean(AST constant) throws SemanticException { literalProcessor.processBoolean( constant ); // Use the delegate. } - protected void processNumericLiteral(AST literal) { + @Override + protected void processNumericLiteral(AST literal) { literalProcessor.processNumeric( literal ); } - protected void processIndex(AST indexOp) throws SemanticException { + @Override + protected void processIndex(AST indexOp) throws SemanticException { IndexNode indexNode = ( IndexNode ) indexOp; indexNode.resolve( true, true ); } - protected void processFunction(AST functionCall, boolean inSelect) throws SemanticException { + @Override + protected void processFunction(AST functionCall, boolean inSelect) throws SemanticException { MethodNode methodNode = ( MethodNode ) functionCall; methodNode.resolve( inSelect ); } - protected void processAggregation(AST node, boolean inSelect) throws SemanticException { + @Override + protected void processAggregation(AST node, boolean inSelect) throws SemanticException { AggregateNode aggregateNode = ( AggregateNode ) node; aggregateNode.resolve(); } - protected void processConstructor(AST constructor) throws SemanticException { + @Override + protected void processConstructor(AST constructor) throws SemanticException { ConstructorNode constructorNode = ( ConstructorNode ) constructor; constructorNode.prepare(); } + @Override protected void setAlias(AST selectExpr, AST ident) { ((SelectExpression) selectExpr).setAlias(ident.getText()); // only put the alias (i.e., result variable) in selectExpressionsByResultVariable @@ -1005,7 +1023,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par } } - protected boolean isOrderExpressionResultVariableRef(AST orderExpressionNode) throws SemanticException { + @Override + protected boolean isOrderExpressionResultVariableRef(AST orderExpressionNode) throws SemanticException { // ORDER BY is not supported in a subquery // TODO: should an exception be thrown if an ORDER BY is in a subquery? if ( ! isSubQuery() && @@ -1016,7 +1035,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return false; } - protected void handleResultVariableRef(AST resultVariableRef) throws SemanticException { + @Override + protected void handleResultVariableRef(AST resultVariableRef) throws SemanticException { if ( isSubQuery() ) { throw new SemanticException( "References to result variables in subqueries are not supported." @@ -1026,7 +1046,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par selectExpressionsByResultVariable.get( resultVariableRef.getText() ) ); } - + /** * Returns the locations of all occurrences of the named parameter. */ @@ -1060,7 +1080,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par public SelectClause getSelectClause() { return selectClause; } - + public FromClause getFinalFromClause() { FromClause top = currentFromClause; while ( top.getParentFromClause() != null ) { @@ -1094,7 +1114,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return numberOfParametersInSetClause; } - protected void evaluateAssignment(AST eq) throws SemanticException { + @Override + protected void evaluateAssignment(AST eq) throws SemanticException { prepareLogicOperator( eq ); Queryable persister = getCurrentFromClause().getFromElement().getQueryable(); evaluateAssignment( eq, persister, -1 ); @@ -1118,7 +1139,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return assignmentSpecifications; } - protected AST createIntoClause(String path, AST propertySpec) throws SemanticException { + @Override + protected AST createIntoClause(String path, AST propertySpec) throws SemanticException { Queryable persister = ( Queryable ) getSessionFactoryHelper().requireClassPersister( path ); IntoClause intoClause = ( IntoClause ) getASTFactory().create( INTO, persister.getEntityName() ); @@ -1130,7 +1152,8 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return intoClause; } - protected void prepareVersioned(AST updateNode, AST versioned) throws SemanticException { + @Override + protected void prepareVersioned(AST updateNode, AST versioned) throws SemanticException { UpdateStatement updateStatement = ( UpdateStatement ) updateNode; FromClause fromClause = updateStatement.getFromClause(); if ( versioned != null ) { @@ -1190,15 +1213,18 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par return versionPropertyNode; } - protected void prepareLogicOperator(AST operator) throws SemanticException { + @Override + protected void prepareLogicOperator(AST operator) throws SemanticException { ( ( OperatorNode ) operator ).initialize(); } - protected void prepareArithmeticOperator(AST operator) throws SemanticException { + @Override + protected void prepareArithmeticOperator(AST operator) throws SemanticException { ( ( OperatorNode ) operator ).initialize(); } - protected void validateMapPropertyExpression(AST node) throws SemanticException { + @Override + protected void validateMapPropertyExpression(AST node) throws SemanticException { try { FromReferenceNode fromReferenceNode = (FromReferenceNode) node; QueryableCollection collectionPersister = fromReferenceNode.getFromElement().getQueryableCollection(); @@ -1217,4 +1243,51 @@ 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 edf4746b30..de1724c7ec 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,12 +24,14 @@ */ package org.hibernate.hql.ast; -import antlr.ANTLRException; -import antlr.RecognitionException; -import antlr.TokenStreamException; -import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.QueryException; @@ -40,8 +42,8 @@ import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.event.EventSource; import org.hibernate.hql.FilterTranslator; -import org.hibernate.hql.QueryExecutionRequestException; import org.hibernate.hql.ParameterTranslations; +import org.hibernate.hql.QueryExecutionRequestException; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.HqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; @@ -54,21 +56,22 @@ import org.hibernate.hql.ast.tree.InsertStatement; import org.hibernate.hql.ast.tree.QueryNode; import org.hibernate.hql.ast.tree.Statement; import org.hibernate.hql.ast.util.ASTPrinter; -import org.hibernate.hql.ast.util.NodeTraverser; import org.hibernate.hql.ast.util.ASTUtil; +import org.hibernate.hql.ast.util.NodeTraverser; import org.hibernate.loader.hql.QueryLoader; import org.hibernate.persister.entity.Queryable; import org.hibernate.type.Type; import org.hibernate.util.IdentitySet; -import org.hibernate.util.StringHelper; import org.hibernate.util.ReflectHelper; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.ArrayList; +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; +import antlr.collections.AST; /** * A QueryTranslator that uses an Antlr-based parser. @@ -77,8 +80,8 @@ import java.util.ArrayList; */ public class QueryTranslatorImpl implements FilterTranslator { - private static final Logger log = LoggerFactory.getLogger( QueryTranslatorImpl.class ); - private static final Logger AST_LOG = LoggerFactory.getLogger( "org.hibernate.hql.ast.AST" ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryTranslatorImpl.class.getPackage().getName()); private SessionFactoryImplementor factory; @@ -164,9 +167,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 ) { - if ( log.isDebugEnabled() ) { - log.debug( "compile() : The query is already compiled, skipping..." ); - } + LOG.compile(); return; } @@ -213,19 +214,15 @@ public class QueryTranslatorImpl implements FilterTranslator { throw qe; } catch ( RecognitionException e ) { - // we do not actually propogate ANTLRExceptions as a cause, so + // we do not actually propagate ANTLRExceptions as a cause, so // log it here for diagnostic purposes - if ( log.isTraceEnabled() ) { - log.trace( "converted antlr.RecognitionException", e ); - } + LOG.trace(LOG.convertedRecognitionException(), e); throw QuerySyntaxException.convert( e, hql ); } catch ( ANTLRException e ) { - // we do not actually propogate ANTLRExceptions as a cause, so + // we do not actually propagate ANTLRExceptions as a cause, so // log it here for diagnostic purposes - if ( log.isTraceEnabled() ) { - log.trace( "converted antlr.ANTLRException", e ); - } + LOG.trace(LOG.convertedAntlrException(), e); throw new QueryException( e.getMessage(), hql ); } @@ -237,9 +234,9 @@ public class QueryTranslatorImpl implements FilterTranslator { SqlGenerator gen = new SqlGenerator(factory); gen.statement( sqlAst ); sql = gen.getSQL(); - if ( log.isDebugEnabled() ) { - log.debug( "HQL: " + hql ); - log.debug( "SQL: " + sql ); + if (LOG.isDebugEnabled()) { + LOG.debug("HQL: " + hql); + LOG.debug("SQL: " + sql); } gen.getParseErrorHandler().throwQueryException(); collectedParameterSpecifications = gen.getCollectedParameters(); @@ -253,9 +250,9 @@ public class QueryTranslatorImpl implements FilterTranslator { // Transform the tree. w.statement( hqlAst ); - if ( AST_LOG.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { ASTPrinter printer = new ASTPrinter( SqlTokenTypes.class ); - AST_LOG.debug( printer.showAsString( w.getAST(), "--- SQL AST ---" ) ); + LOG.debug(printer.showAsString(w.getAST(), "--- SQL AST ---")); } w.getParseErrorHandler().throwQueryException(); @@ -268,9 +265,7 @@ public class QueryTranslatorImpl implements FilterTranslator { HqlParser parser = HqlParser.getInstance( hql ); parser.setFilter( filter ); - if ( log.isDebugEnabled() ) { - log.debug( "parse() - HQL: " + hql ); - } + LOG.debug("parse() - HQL: " + hql); parser.statement(); AST hqlAst = parser.getAST(); @@ -286,9 +281,9 @@ public class QueryTranslatorImpl implements FilterTranslator { } void showHqlAst(AST hqlAst) { - if ( AST_LOG.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { ASTPrinter printer = new ASTPrinter( HqlTokenTypes.class ); - AST_LOG.debug( printer.showAsString( hqlAst, "--- HQL AST ---" ) ); + LOG.debug(printer.showAsString(hqlAst, "--- HQL AST ---")); } } @@ -350,7 +345,7 @@ public class QueryTranslatorImpl implements FilterTranslator { QueryParameters queryParametersToUse; if ( hasLimit && containsCollectionFetches() ) { - log.warn( "firstResult/maxResults specified with collection fetch; applying in memory!" ); + LOG.firstOrMaxResultsSpecifiedWithCollectionFetch(); RowSelection selection = new RowSelection(); selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() ); selection.setTimeout( queryParameters.getRowSelection().getTimeout() ); @@ -579,14 +574,9 @@ public class QueryTranslatorImpl implements FilterTranslator { public void visit(AST node) { if ( dotRoot != null ) { // we are already processing a dot-structure - if ( ASTUtil.isSubtreeChild( dotRoot, node ) ) { - // ignore it... - return; - } - else { - // we are now at a new tree level - dotRoot = null; - } + if (ASTUtil.isSubtreeChild(dotRoot, node)) return; + // we are now at a new tree level + dotRoot = null; } if ( dotRoot == null && node.getType() == HqlTokenTypes.DOT ) { @@ -604,4 +594,25 @@ 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 27872ff3e1..b58028cdcd 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,32 +24,31 @@ */ 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 java.util.Arrays; - -import antlr.RecognitionException; -import antlr.collections.AST; import org.hibernate.QueryException; -import org.hibernate.hql.ast.tree.FunctionNode; -import org.hibernate.hql.ast.tree.SqlNode; -import org.hibernate.type.Type; -import org.hibernate.util.StringHelper; -import org.hibernate.param.ParameterSpecification; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.antlr.SqlGeneratorBase; import org.hibernate.hql.antlr.SqlTokenTypes; -import org.hibernate.hql.ast.tree.MethodNode; import org.hibernate.hql.ast.tree.FromElement; +import org.hibernate.hql.ast.tree.FunctionNode; import org.hibernate.hql.ast.tree.Node; -import org.hibernate.hql.ast.tree.ParameterNode; import org.hibernate.hql.ast.tree.ParameterContainer; +import org.hibernate.hql.ast.tree.ParameterNode; import org.hibernate.hql.ast.util.ASTPrinter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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; /** * Generates SQL by overriding callback methods in the base class, which does @@ -59,7 +58,9 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { - private static final Logger log = LoggerFactory.getLogger( SqlGenerator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SqlGenerator.class.getPackage().getName()); public static boolean REGRESSION_STYLE_CROSS_JOINS = false; @@ -83,13 +84,12 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { private int traceDepth = 0; - public void traceIn(String ruleName, AST tree) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceIn(String ruleName, AST tree) { + if (inputState.guessing > 0) return; String prefix = StringHelper.repeat( '-', (traceDepth++ * 2) ) + "-> "; String traceText = ruleName + " (" + buildTraceNodeName(tree) + ")"; - log.trace( prefix + traceText ); + LOG.trace(prefix + traceText); } private String buildTraceNodeName(AST tree) { @@ -98,23 +98,24 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { : tree.getText() + " [" + printer.getTokenTypeName( tree.getType() ) + "]"; } - public void traceOut(String ruleName, AST tree) { - if ( inputState.guessing > 0 ) { - return; - } + @Override + public void traceOut(String ruleName, AST tree) { + if (inputState.guessing > 0) return; String prefix = "<-" + StringHelper.repeat( '-', (--traceDepth * 2) ) + " "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } public List getCollectedParameters() { return collectedParameters; } - protected void out(String s) { + @Override + protected void out(String s) { writer.clause( s ); } - protected void out(AST n) { + @Override + protected void out(AST n) { if ( n instanceof Node ) { out( ( ( Node ) n ).getRenderText( sessionFactory ) ); } @@ -135,19 +136,23 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { } } - protected void commaBetweenParameters(String comma) { + @Override + protected void commaBetweenParameters(String comma) { writer.commaBetweenParameters( comma ); } - public void reportError(RecognitionException e) { + @Override + public void reportError(RecognitionException e) { parseErrorHandler.reportError( e ); // Use the delegate. } - public void reportError(String s) { + @Override + public void reportError(String s) { parseErrorHandler.reportError( s ); // Use the delegate. } - public void reportWarning(String s) { + @Override + public void reportWarning(String s) { parseErrorHandler.reportWarning( s ); } @@ -165,7 +170,8 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { return getStringBuffer().toString(); } - protected void optionalSpace() { + @Override + protected void optionalSpace() { int c = getLastChar(); switch ( c ) { case -1: @@ -181,7 +187,8 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { } } - protected void beginFunctionTemplate(AST node, AST nameNode) { + @Override + protected void beginFunctionTemplate(AST node, AST nameNode) { // NOTE for AGGREGATE both nodes are the same; for METHOD the first is the METHOD, the second is the // METHOD_NAME FunctionNode functionNode = ( FunctionNode ) node; @@ -197,7 +204,8 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { } } - protected void endFunctionTemplate(AST node) { + @Override + protected void endFunctionTemplate(AST node) { FunctionNode functionNode = ( FunctionNode ) node; SQLFunction sqlFunction = functionNode.getSQLFunction(); if ( sqlFunction == null ) { @@ -273,7 +281,8 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { throw new QueryException( "TreeWalker: panic" ); } - protected void fromFragmentSeparator(AST a) { + @Override + protected void fromFragmentSeparator(AST a) { // check two "adjecent" nodes at the top of the from-clause tree AST next = a.getNextSibling(); if ( next == null || !hasText( a ) ) { @@ -330,7 +339,8 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { } } - protected void nestedFromFragment(AST d, AST parent) { + @Override + protected void nestedFromFragment(AST d, AST parent) { // check a set of parent/child nodes in the from-clause tree // to determine if a comma is required between them if ( d != null && hasText( d ) ) { @@ -357,4 +367,14 @@ public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter { } } + /** + * 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 50f486cd0d..f782e7c531 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 @@ -23,19 +23,18 @@ */ package org.hibernate.hql.ast.exec; -import java.sql.PreparedStatement; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLWarning; import java.sql.Statement; -import java.util.List; import java.util.Collections; - +import java.util.List; import org.hibernate.HibernateException; import org.hibernate.action.BulkOperationCleanupAction; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; -import org.hibernate.engine.transaction.Isolater; import org.hibernate.engine.transaction.IsolatedWork; +import org.hibernate.engine.transaction.Isolater; import org.hibernate.event.EventSource; import org.hibernate.hql.ast.HqlSqlWalker; import org.hibernate.hql.ast.SqlGenerator; @@ -45,28 +44,25 @@ import org.hibernate.sql.Select; import org.hibernate.sql.SelectFragment; import org.hibernate.util.JDBCExceptionReporter; import org.hibernate.util.StringHelper; - import antlr.RecognitionException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Implementation of AbstractStatementExecutor. * * @author Steve Ebersole */ public abstract class AbstractStatementExecutor implements StatementExecutor { - private static final Logger LOG = LoggerFactory.getLogger( AbstractStatementExecutor.class ); - private final Logger log; + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractStatementExecutor.class.getPackage().getName()); + private final HqlSqlWalker walker; private List idSelectParameterSpecifications = Collections.EMPTY_LIST; - public AbstractStatementExecutor(HqlSqlWalker walker, Logger log) { + public AbstractStatementExecutor( HqlSqlWalker walker, + Logger log ) { this.walker = walker; - this.log = log; } protected HqlSqlWalker getWalker() { @@ -160,7 +156,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { } } catch( Exception e ) { - log.debug( "unable to create temporary id table [" + e.getMessage() + "]" ); + LOG.unableToCreateTemporaryIdTable(e.getMessage()); } } }; @@ -184,7 +180,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { } public void prepare(SQLWarning warning) { - LOG.debug( "Warnings creating temp table", warning ); + LOG.warningsCreatingTempTable(warning); } @Override @@ -216,7 +212,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { } } catch( Exception e ) { - log.warn( "unable to drop temporary id table after use [" + e.getMessage() + "]" ); + LOG.unableToDropTemporaryIdTable(e.getMessage()); } } }; @@ -244,7 +240,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { ps.executeUpdate(); } catch( Throwable t ) { - log.warn( "unable to cleanup temporary id table after use [" + t + "]" ); + LOG.unableToCleanupTemporaryIdTable(t); } finally { if ( ps != null ) { @@ -273,11 +269,7 @@ public abstract class AbstractStatementExecutor implements StatementExecutor { @SuppressWarnings({ "UnnecessaryUnboxing" }) protected boolean shouldIsolateTemporaryTableDDL() { Boolean dialectVote = getFactory().getDialect().performTemporaryTableDDLInIsolation(); - if ( dialectVote != null ) { - return dialectVote.booleanValue(); - } - else { - return getFactory().getSettings().isDataDefinitionImplicitCommit(); - } + if (dialectVote != null) return dialectVote.booleanValue(); + return getFactory().getSettings().isDataDefinitionImplicitCommit(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/BasicExecutor.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/BasicExecutor.java index 53c0aeee67..6e3cf3d523 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/BasicExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/ast/exec/BasicExecutor.java @@ -28,7 +28,6 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import java.util.List; - import org.hibernate.HibernateException; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.RowSelection; @@ -38,26 +37,21 @@ import org.hibernate.hql.ast.QuerySyntaxException; import org.hibernate.hql.ast.SqlGenerator; import org.hibernate.param.ParameterSpecification; import org.hibernate.persister.entity.Queryable; - import antlr.RecognitionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Implementation of BasicExecutor. * * @author Steve Ebersole */ public class BasicExecutor extends AbstractStatementExecutor { - private static final Logger log = LoggerFactory.getLogger( BasicExecutor.class ); private final Queryable persister; private final String sql; private final List parameterSpecifications; public BasicExecutor(HqlSqlWalker walker, Queryable persister) { - super( walker, log ); + super(walker, null); this.persister = persister; try { SqlGenerator gen = new SqlGenerator( getFactory() ); @@ -114,7 +108,8 @@ public class BasicExecutor extends AbstractStatementExecutor { } } - protected Queryable[] getAffectedQueryables() { + @Override + protected Queryable[] getAffectedQueryables() { return new Queryable[] { persister }; } } 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 4290cb2ef4..836682f7e6 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 @@ -27,7 +27,6 @@ package org.hibernate.hql.ast.exec; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; - import org.hibernate.HibernateException; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionImplementor; @@ -39,23 +38,22 @@ import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.Delete; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Implementation of MultiTableDeleteExecutor. * * @author Steve Ebersole */ public class MultiTableDeleteExecutor extends AbstractStatementExecutor { - private static final Logger log = LoggerFactory.getLogger( MultiTableDeleteExecutor.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + MultiTableDeleteExecutor.class.getPackage().getName()); private final Queryable persister; private final String idInsertSelect; private final String[] deletes; public MultiTableDeleteExecutor(HqlSqlWalker walker) { - super( walker, log ); + super(walker, null); if ( !walker.getSessionFactoryHelper().getFactory().getDialect().supportsTemporaryTables() ) { throw new HibernateException( "cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables" ); @@ -67,7 +65,7 @@ public class MultiTableDeleteExecutor extends AbstractStatementExecutor { this.persister = fromElement.getQueryable(); this.idInsertSelect = generateIdInsertSelect( persister, bulkTargetAlias, deleteStatement.getWhereClause() ); - log.trace( "Generated ID-INSERT-SELECT SQL (multi-table delete) : " + idInsertSelect ); + LOG.generatedIdInsertSelectDelete(idInsertSelect); String[] tableNames = persister.getConstraintOrderedTableNameClosure(); String[][] columnNames = persister.getContraintOrderedTableKeyColumnClosure(); @@ -157,7 +155,8 @@ public class MultiTableDeleteExecutor extends AbstractStatementExecutor { } } - protected Queryable[] getAffectedQueryables() { + @Override + protected Queryable[] getAffectedQueryables() { return new Queryable[] { persister }; } } 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 17f4cfc2a0..d91c74a254 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 @@ -29,7 +29,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - import org.hibernate.HibernateException; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionImplementor; @@ -42,16 +41,15 @@ import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.Update; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Implementation of MultiTableUpdateExecutor. * * @author Steve Ebersole */ public class MultiTableUpdateExecutor extends AbstractStatementExecutor { - private static final Logger log = LoggerFactory.getLogger( MultiTableUpdateExecutor.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + MultiTableUpdateExecutor.class.getPackage().getName()); private final Queryable persister; private final String idInsertSelect; @@ -59,7 +57,7 @@ public class MultiTableUpdateExecutor extends AbstractStatementExecutor { private final ParameterSpecification[][] hqlParameters; public MultiTableUpdateExecutor(HqlSqlWalker walker) { - super( walker, log ); + super(walker, null); if ( !walker.getSessionFactoryHelper().getFactory().getDialect().supportsTemporaryTables() ) { throw new HibernateException( "cannot doAfterTransactionCompletion multi-table updates using dialect not supporting temp tables" ); @@ -71,7 +69,7 @@ public class MultiTableUpdateExecutor extends AbstractStatementExecutor { this.persister = fromElement.getQueryable(); this.idInsertSelect = generateIdInsertSelect( persister, bulkTargetAlias, updateStatement.getWhereClause() ); - log.trace( "Generated ID-INSERT-SELECT SQL (multi-table update) : " + idInsertSelect ); + LOG.generatedIdInsertSelectUpdate(idInsertSelect); String[] tableNames = persister.getConstraintOrderedTableNameClosure(); String[][] columnNames = persister.getContraintOrderedTableKeyColumnClosure(); @@ -192,7 +190,8 @@ public class MultiTableUpdateExecutor extends AbstractStatementExecutor { } } - protected Queryable[] getAffectedQueryables() { + @Override + protected Queryable[] getAffectedQueryables() { return new Queryable[] { persister }; } } 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 73cb04c6a6..e45226ce7d 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 @@ -26,11 +26,8 @@ package org.hibernate.hql.ast.tree; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; - import antlr.collections.AST; -import org.slf4j.Logger; - /** * Convenience implementation of {@link RestrictableStatement} * to centralize common functionality. @@ -43,7 +40,8 @@ public abstract class AbstractRestrictableStatement extends AbstractStatement im private AST whereClause; protected abstract int getWhereClauseParentTokenType(); - protected abstract Logger getLog(); + + protected abstract Logger getLog(); /** * @see org.hibernate.hql.ast.tree.RestrictableStatement#getFromClause 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 40cd73af5d..12b29b6e06 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,17 @@ */ package org.hibernate.hql.ast.tree; +import static org.jboss.logging.Logger.Level.INFO; 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Represents an aggregate function i.e. min, max, sum, avg. @@ -39,7 +41,9 @@ import org.slf4j.LoggerFactory; * @author Joshua Davis */ public class AggregateNode extends AbstractSelectExpression implements SelectExpression, FunctionNode { - private static final Logger log = LoggerFactory.getLogger( AggregateNode.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AggregateNode.class.getPackage().getName()); private SQLFunction sqlFunction; @@ -56,7 +60,7 @@ public class AggregateNode extends AbstractSelectExpression implements SelectExp final String name = getText(); sqlFunction = getSessionFactoryHelper().findSQLFunction( getText() ); if ( sqlFunction == null ) { - log.info( "Could not resolve aggregate function {}; using standard definition", name ); + LOG.unableToResolveAggregateFunction(name); sqlFunction = new StandardSQLFunction( name ); } } @@ -77,7 +81,8 @@ public class AggregateNode extends AbstractSelectExpression implements SelectExp return null; } - public Type getDataType() { + @Override + public Type getDataType() { // Get the function return value type, based on the type of the first argument. return getSessionFactoryHelper().findFunctionReturnType( getText(), resolveFunction(), getFirstChild() ); } @@ -86,8 +91,20 @@ public class AggregateNode extends AbstractSelectExpression implements SelectExp ColumnHelper.generateSingleScalarColumn( this, i ); } - public boolean isScalar() throws SemanticException { + @Override + public boolean isScalar() throws SemanticException { // 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 88ad515c2c..e89417973a 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 @@ -27,9 +27,6 @@ package org.hibernate.hql.ast.tree; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Defines a top-level AST node representing an HQL delete statement. * @@ -37,7 +34,8 @@ import org.slf4j.LoggerFactory; */ public class DeleteStatement extends AbstractRestrictableStatement { - private static final Logger log = LoggerFactory.getLogger( DeleteStatement.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DeleteStatement.class.getPackage().getName()); /** * @see org.hibernate.hql.ast.tree.Statement#getStatementType() @@ -53,11 +51,13 @@ public class DeleteStatement extends AbstractRestrictableStatement { return true; } - protected int getWhereClauseParentTokenType() { + @Override + protected int getWhereClauseParentTokenType() { return SqlTokenTypes.FROM; } - protected Logger getLog() { - return log; + @Override + protected Logger getLog() { + return LOG; } } 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 784e1bb234..4a26109312 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 @@ -37,13 +37,9 @@ import org.hibernate.type.CollectionType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; - import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents a reference to a property or alias expression. This should duplicate the relevant behaviors in * PathExpressionParser. @@ -71,7 +67,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec public static IllegalCollectionDereferenceExceptionBuilder ILLEGAL_COLL_DEREF_EXCP_BUILDER = DEF_ILLEGAL_COLL_DEREF_EXCP_BUILDER; /////////////////////////////////////////////////////////////////////////// - private static final Logger log = LoggerFactory.getLogger( DotNode.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, DotNode.class.getPackage().getName()); private static final int DEREF_UNKNOWN = 0; private static final int DEREF_ENTITY = 1; @@ -135,7 +131,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec return columns; } - public String getDisplayText() { + @Override + public String getDisplayText() { StringBuffer buf = new StringBuffer(); FromElement fromElement = getFromElement(); buf.append( "{propertyName=" ).append( propertyName ); @@ -159,7 +156,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec * * @throws SemanticException */ - public void resolveFirstChild() throws SemanticException { + @Override + public void resolveFirstChild() throws SemanticException { FromReferenceNode lhs = ( FromReferenceNode ) getFirstChild(); SqlNode property = ( SqlNode ) lhs.getNextSibling(); @@ -178,7 +176,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec checkSubclassOrSuperclassPropertyReference( lhs, propName ); } - public void resolveInFunctionCall(boolean generateJoin, boolean implicitJoin) throws SemanticException { + @Override + public void resolveInFunctionCall(boolean generateJoin, boolean implicitJoin) throws SemanticException { if ( isResolved() ) { return; } @@ -302,9 +301,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec ); FromElement elem = factory.createCollection( queryableCollection, role, joinType, fetch, indexed ); - if ( log.isDebugEnabled() ) { - log.debug( "dereferenceCollection() : Created new FROM element for " + propName + " : " + elem ); - } + LOG.dereferenceCollection(propName, elem); setImpliedJoin( elem ); setFromElement( elem ); // This 'dot' expression now refers to the resulting from element. @@ -385,13 +382,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.debug( "dereferenceEntityJoin() : generating join for " + propertyName + " in " - + getFromElement().getClassName() + " " - + ( ( classAlias == null ) ? "{no alias}" : "(" + classAlias + ")" ) - + " parent = " + ASTUtil.getDebugString( parent ) - ); - } + if (LOG.isDebugEnabled()) LOG.dereferenceEntityJoin(propertyName, + getFromElement().getClassName(), + (classAlias == null) ? LOG.noAlias() : classAlias, + ASTUtil.getDebugString(parent)); // Create a new FROM node for the referenced class. String associatedEntityName = propertyType.getAssociatedEntityName(); String tableAlias = getAliasGenerator().createName( associatedEntityName ); @@ -497,7 +491,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec } } - public FromElement getImpliedJoin() { + @Override + public FromElement getImpliedJoin() { return impliedJoin; } @@ -541,11 +536,7 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec } private void checkForCorrelatedSubquery(String methodName) { - if ( isCorrelatedSubselect() ) { - if ( log.isDebugEnabled() ) { - log.debug( methodName + "() : correlated subquery" ); - } - } + if (isCorrelatedSubselect()) LOG.correlatedSubquery(methodName); } private boolean isCorrelatedSubselect() { @@ -566,11 +557,7 @@ 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 - if ( log.isDebugEnabled() ) { - log.debug( "dereferenceShortcut() : property " + - propertyName + " in " + getFromElement().getClassName() + - " does not require a join." ); - } + LOG.dereferenceShortcut(propertyName, getFromElement().getClassName()); initText(); setPropertyNameAndPath( dotParent ); // Set the unresolved path in this node and the parent. @@ -590,28 +577,18 @@ 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; - if ( log.isDebugEnabled() ) { - log.debug( "Unresolved property path is now '" + dotNode.propertyPath + "'" ); - } - } - else { - if ( log.isDebugEnabled() ) { - log.debug( "terminal propertyPath = [" + propertyPath + "]" ); - } - } + LOG.unresolvedPropertyPathIsNow(dotNode.propertyPath); + } else LOG.terminalPropertyPath(propertyPath); } - public Type getDataType() { + @Override + public Type getDataType() { if ( super.getDataType() == null ) { FromElement fromElement = getLhs().getFromElement(); - if ( fromElement == null ) { - return null; - } + if (fromElement == null) return null; // If the lhs is a collection, use CollectionPropertyMapping Type propertyType = fromElement.getPropertyType( propertyName, propertyPath ); - if ( log.isDebugEnabled() ) { - log.debug( "getDataType() : " + propertyPath + " -> " + propertyType ); - } + LOG.getDataType(propertyPath, propertyType); super.setDataType( propertyType ); } return super.getDataType(); @@ -638,7 +615,8 @@ public class DotNode extends FromReferenceNode implements DisplayableNode, Selec * * @return the full path of the node. */ - public String getPath() { + @Override + public String getPath() { if ( path == null ) { FromReferenceNode lhs = getLhs(); if ( lhs == null ) { 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 1dbc5a4c24..bb84de9dc4 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,13 +31,9 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.ast.util.ASTIterator; import org.hibernate.hql.ast.util.ASTUtil; - import antlr.SemanticException; import antlr.collections.AST; @@ -47,7 +43,9 @@ import antlr.collections.AST; * @author josh */ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, DisplayableNode { - private static Logger log = LoggerFactory.getLogger( FromClause.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FromClause.class.getPackage().getName()); public static final int ROOT_LEVEL = 1; private int level = ROOT_LEVEL; @@ -193,7 +191,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di public List getFromElements() { return ASTUtil.collectChildren( this, fromElementPredicate ); } - + public FromElement getFromElement() { // TODO: not sure about this one // List fromElements = getFromElements(); @@ -225,28 +223,32 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } private static ASTUtil.FilterPredicate fromElementPredicate = new ASTUtil.IncludePredicate() { - public boolean include(AST node) { + @Override + public boolean include(AST node) { FromElement fromElement = ( FromElement ) node; return fromElement.isFromOrJoinFragment(); } }; private static ASTUtil.FilterPredicate projectionListPredicate = new ASTUtil.IncludePredicate() { - public boolean include(AST node) { + @Override + public boolean include(AST node) { FromElement fromElement = ( FromElement ) node; return fromElement.inProjectionList(); } }; private static ASTUtil.FilterPredicate collectionFetchPredicate = new ASTUtil.IncludePredicate() { - public boolean include(AST node) { + @Override + public boolean include(AST node) { FromElement fromElement = ( FromElement ) node; return fromElement.isFetch() && fromElement.getQueryableCollection() != null; } }; private static ASTUtil.FilterPredicate explicitFromPredicate = new ASTUtil.IncludePredicate() { - public boolean include(AST node) { + @Override + public boolean include(AST node) { final FromElement fromElement = ( FromElement ) node; return !fromElement.isImplied(); } @@ -274,9 +276,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } void addJoinByPathMap(String path, FromElement destination) { - if ( log.isDebugEnabled() ) { - log.debug( "addJoinByPathMap() : " + path + " -> " + destination.getDisplayText() ); - } + LOG.addJoinByPathMap(path, destination.getDisplayText()); fromElementsByPath.put( path, destination ); } @@ -346,9 +346,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } public void promoteJoin(FromElement elem) { - if ( log.isDebugEnabled() ) { - log.debug( "Promoting [" + elem + "] to [" + this + "]" ); - } + LOG.promoting(elem, 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 @@ -364,9 +362,7 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di } void addCollectionJoinFromElementByPath(String path, FromElement destination) { - if ( log.isDebugEnabled() ) { - log.debug( "addCollectionJoinFromElementByPath() : " + path + " -> " + destination ); - } + LOG.addCollectionJoinFromElementByPath(path, destination); collectionJoinFromElementsByPath.put( path, destination ); // Add the new node to the map so that we don't create it twice. } @@ -401,7 +397,8 @@ public class FromClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes, Di impliedElements.add( element ); } - public String toString() { + @Override + public String toString() { return "FromClause{" + "level=" + level + "}"; 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 4d59be4616..b4a873ca65 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 @@ -24,19 +24,18 @@ */ package org.hibernate.hql.ast.tree; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import java.util.ArrayList; - import org.hibernate.QueryException; -import org.hibernate.hql.ast.TypeDiscriminatorMetadata; -import org.hibernate.param.ParameterSpecification; import org.hibernate.engine.JoinSequence; -import org.hibernate.hql.QueryTranslator; import org.hibernate.hql.CollectionProperties; +import org.hibernate.hql.QueryTranslator; +import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; +import org.hibernate.hql.ast.TypeDiscriminatorMetadata; import org.hibernate.hql.ast.util.ASTUtil; -import org.hibernate.hql.ast.HqlSqlWalker; +import org.hibernate.param.ParameterSpecification; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.persister.entity.DiscriminatorMetadata; import org.hibernate.persister.entity.EntityPersister; @@ -46,9 +45,6 @@ import org.hibernate.type.EntityType; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents a single mapped class mentioned in an HQL FROM clause. Each * class reference will have the following symbols: @@ -62,7 +58,9 @@ import org.slf4j.LoggerFactory; * @author josh */ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, ParameterContainer { - private static final Logger log = LoggerFactory.getLogger( FromElement.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FromElement.class.getPackage().getName()); private String className; private String classAlias; @@ -153,17 +151,15 @@ 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 ); - if ( log.isDebugEnabled() ) { - log.debug( fromClause + " : " + className + " (" - + ( classAlias == null ? "no alias" : classAlias ) + ") -> " + tableAlias ); - } + LOG.fromClause(fromClause, className, classAlias == null ? LOG.noAlias() : classAlias, tableAlias); } public EntityPersister getEntityPersister() { return elementType.getEntityPersister(); } - public Type getDataType() { + @Override + public Type getDataType() { return elementType.getDataType(); } @@ -292,11 +288,13 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa buf.append( "}" ); } - public int hashCode() { + @Override + public int hashCode() { return super.hashCode(); } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) { return super.equals( obj ); } @@ -310,11 +308,8 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa } public void setIncludeSubclasses(boolean includeSubclasses) { - if ( isDereferencedBySuperclassOrSubclassProperty() ) { - if ( !includeSubclasses && log.isTraceEnabled() ) { - log.trace( "attempt to disable subclass-inclusions", new Exception( "stack-trace source" ) ); - } - } + if (LOG.isTraceEnabled() && isDereferencedBySuperclassOrSubclassProperty() && !includeSubclasses) LOG.attemptToDisableSubclassInclusions(new Exception( + LOG.stackTraceSource())); this.includeSubclasses = includeSubclasses; } @@ -341,7 +336,7 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa else { propertyName = EntityPersister.ENTITY_ID; } - if ( getWalker().getStatementType() == HqlSqlWalker.SELECT ) { + if ( getWalker().getStatementType() == HqlSqlTokenTypes.SELECT ) { cols = getPropertyMapping( propertyName ).toColumns( table, propertyName ); } else { @@ -622,9 +617,7 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa if ( persister != null ) { try { Queryable.Declarer propertyDeclarer = persister.getSubclassPropertyDeclarer( propertyName ); - if ( log.isTraceEnabled() ) { - log.trace( "handling property dereference [" + persister.getEntityName() + " (" + getClassAlias() + ") -> " + propertyName + " (" + propertyDeclarer + ")]" ); - } + LOG.handlingPropertyDereference(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 b3c6fa2cc0..5cb0a925cd 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 @@ -37,18 +37,14 @@ import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.JoinFragment; import org.hibernate.type.AssociationType; import org.hibernate.type.CollectionType; +import org.hibernate.type.ComponentType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.hibernate.type.ComponentType; import org.hibernate.util.StringHelper; - import antlr.ASTFactory; import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Encapsulates the creation of FromElements and JoinSequences. * @@ -56,7 +52,8 @@ import org.slf4j.LoggerFactory; */ public class FromElementFactory implements SqlTokenTypes { - private static final Logger log = LoggerFactory.getLogger( FromElementFactory.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FromElementFactory.class.getPackage().getName()); private FromClause fromClause; private FromElement origin; @@ -127,14 +124,12 @@ public class FromElementFactory implements SqlTokenTypes { String pathAlias, FromElement parentFromElement, String classAlias) throws SemanticException { - if ( log.isDebugEnabled() ) { - log.debug( "createFromElementInSubselect() : path = " + path ); - } + LOG.createFromElementInSubselect(path); // Create an DotNode AST for the path and resolve it. FromElement fromElement = evaluateFromElementPath( path, classAlias ); EntityPersister entityPersister = fromElement.getEntityPersister(); - // If the first identifier in the path referrs to the class alias (not the class name), then this + // If the first identifier in the path refers to the class alias (not the class name), then this // is a correlated subselect. If it's a correlated sub-select, use the existing table alias. Otherwise // generate a new one. String tableAlias = null; @@ -148,9 +143,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 ) { - if ( log.isDebugEnabled() ) { - log.debug( "createFromElementInSubselect() : creating a new FROM element..." ); - } + LOG.createFromElementInSubselect(); fromElement = createFromElement( entityPersister ); initializeAndAddFromElement( fromElement, path, @@ -160,9 +153,7 @@ public class FromElementFactory implements SqlTokenTypes { tableAlias ); } - if ( log.isDebugEnabled() ) { - log.debug( "createFromElementInSubselect() : " + path + " -> " + fromElement ); - } + LOG.createFromElementInSubselect(path, fromElement); return fromElement; } @@ -174,12 +165,8 @@ public class FromElementFactory implements SqlTokenTypes { classAlias, null ); - if ( pathNode.getImpliedJoin() != null ) { - return pathNode.getImpliedJoin(); - } - else { - return pathNode.getFromElement(); - } + if (pathNode.getImpliedJoin() != null) return pathNode.getImpliedJoin(); + return pathNode.getFromElement(); } FromElement createCollectionElementsJoin( @@ -265,9 +252,7 @@ public class FromElementFactory implements SqlTokenTypes { EntityPersister entityPersister = elem.getEntityPersister(); int numberOfTables = entityPersister.getQuerySpaces().length; if ( numberOfTables > 1 && implied && !elem.useFromFragment() ) { - if ( log.isDebugEnabled() ) { - log.debug( "createEntityJoin() : Implied multi-table entity join" ); - } + LOG.createEntityJoin(); elem.setUseFromFragment( true ); } @@ -320,7 +305,7 @@ public class FromElementFactory implements SqlTokenTypes { String associatedEntityName = entityPersister.getEntityName(); EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName ); // Create the FROM element for the target (the elements of the collection). - destination = createAndAddFromElement( + destination = createAndAddFromElement( associatedEntityName, classAlias, targetEntityPersister, @@ -386,17 +371,13 @@ public class FromElementFactory implements SqlTokenTypes { String associatedEntityName = entityPersister.getEntityName(); // Get the class name of the associated entity. if ( queryableCollection.isOneToMany() ) { - if ( log.isDebugEnabled() ) { - log.debug( "createEntityAssociation() : One to many - path = " + path + " role = " + role + " associatedEntityName = " + associatedEntityName ); - } + LOG.createEntityAssociation(path, role, associatedEntityName); JoinSequence joinSequence = createJoinSequence( roleAlias, joinType ); elem = createJoin( associatedEntityName, roleAlias, joinSequence, ( EntityType ) queryableCollection.getElementType(), false ); } else { - if ( log.isDebugEnabled() ) { - log.debug( "createManyToMany() : path = " + path + " role = " + role + " associatedEntityName = " + associatedEntityName ); - } + LOG.createManyToMany(path, role, associatedEntityName); elem = createManyToMany( role, associatedEntityName, roleAlias, entityPersister, ( EntityType ) queryableCollection.getElementType(), joinType ); fromClause.getWalker().addQuerySpaces( queryableCollection.getCollectionSpaces() ); @@ -436,8 +417,8 @@ public class FromElementFactory implements SqlTokenTypes { elem = createJoin( associatedEntityName, roleAlias, joinSequence, type, true ); } else { - // For an explicit many-to-many relationship, add a second join from the intermediate - // (many-to-many) table to the destination table. Also, make sure that the from element's + // For an explicit many-to-many relationship, add a second join from the intermediate + // (many-to-many) table to the destination table. Also, make sure that the from element's // idea of the destination is the destination table. String tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() ); String[] secondJoinColumns = sfh.getCollectionElementColumns( role, roleAlias ); 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 19b5186e37..6204681ad5 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 @@ -24,22 +24,18 @@ */ package org.hibernate.hql.ast.tree; -import java.util.Iterator; import java.util.List; import java.util.Map; - import org.hibernate.MappingException; import org.hibernate.QueryException; -import org.hibernate.param.ParameterSpecification; -import org.hibernate.persister.collection.CollectionPropertyNames; -import org.hibernate.type.CollectionType; -import org.hibernate.util.ArrayHelper; import org.hibernate.engine.JoinSequence; import org.hibernate.hql.CollectionProperties; import org.hibernate.hql.CollectionSubqueryFactory; import org.hibernate.hql.NameGenerator; import org.hibernate.hql.antlr.HqlSqlTokenTypes; +import org.hibernate.param.ParameterSpecification; import org.hibernate.persister.collection.CollectionPropertyMapping; +import org.hibernate.persister.collection.CollectionPropertyNames; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.Joinable; @@ -47,10 +43,7 @@ import org.hibernate.persister.entity.PropertyMapping; import org.hibernate.persister.entity.Queryable; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.hibernate.type.TypeFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.util.ArrayHelper; /** * Delegate that handles the type and join sequence information for a FromElement. @@ -58,7 +51,9 @@ import org.slf4j.LoggerFactory; * @author josh */ class FromElementType { - private static final Logger log = LoggerFactory.getLogger( FromElementType.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FromElementType.class.getPackage().getName()); private FromElement fromElement; private EntityType entityType; @@ -344,53 +339,39 @@ class FromElementType { enabledFilters, propertyMapping.toColumns( tableAlias, path ) ); - if ( log.isDebugEnabled() ) { - log.debug( "toColumns(" + tableAlias + "," + path + ") : subquery = " + subquery ); - } + LOG.toColumns(tableAlias, path, subquery); return new String[]{"(" + subquery + ")"}; } - else { - if ( forceAlias ) { - return propertyMapping.toColumns( tableAlias, path ); + if (forceAlias) { + return propertyMapping.toColumns(tableAlias, path); + } else if (fromElement.getWalker().getStatementType() == HqlSqlTokenTypes.SELECT) { + return propertyMapping.toColumns(tableAlias, path); + } else if (fromElement.getWalker().getCurrentClauseType() == HqlSqlTokenTypes.SELECT) { + return propertyMapping.toColumns(tableAlias, path); + } else if (fromElement.getWalker().isSubQuery()) { + // for a subquery, the alias to use depends on a few things (we + // already know this is not an overall SELECT): + // 1) if this FROM_ELEMENT represents a correlation to the + // outer-most query + // A) if the outer query represents a multi-table + // persister, we need to use the given alias + // in anticipation of one of the multi-table + // executors being used (as this subquery will + // actually be used in the "id select" phase + // of that multi-table executor) + // B) otherwise, we need to use the persister's + // table name as the column qualification + // 2) otherwise (not correlated), use the given alias + if (isCorrelation()) { + if (isMultiTable()) return propertyMapping.toColumns(tableAlias, path); + return propertyMapping.toColumns(extractTableName(), path); } - else if ( fromElement.getWalker().getStatementType() == HqlSqlTokenTypes.SELECT ) { - return propertyMapping.toColumns( tableAlias, path ); - } - else if ( fromElement.getWalker().getCurrentClauseType() == HqlSqlTokenTypes.SELECT ) { - return propertyMapping.toColumns( tableAlias, path ); - } - else if ( fromElement.getWalker().isSubQuery() ) { - // for a subquery, the alias to use depends on a few things (we - // already know this is not an overall SELECT): - // 1) if this FROM_ELEMENT represents a correlation to the - // outer-most query - // A) if the outer query represents a multi-table - // persister, we need to use the given alias - // in anticipation of one of the multi-table - // executors being used (as this subquery will - // actually be used in the "id select" phase - // of that multi-table executor) - // B) otherwise, we need to use the persister's - // table name as the column qualification - // 2) otherwise (not correlated), use the given alias - if ( isCorrelation() ) { - if ( isMultiTable() ) { - return propertyMapping.toColumns( tableAlias, path ); - } - else { - return propertyMapping.toColumns( extractTableName(), path ); - } - } - else { - return propertyMapping.toColumns( tableAlias, path ); - } - } - else { - String[] columns = propertyMapping.toColumns( path ); - log.trace( "Using non-qualified column reference [" + path + " -> (" + ArrayHelper.toString( columns ) + ")]" ); - return columns; - } - } + return propertyMapping.toColumns(tableAlias, path); + } else { + String[] columns = propertyMapping.toColumns(path); + LOG.usingNonQualifiedColumnReference(path, ArrayHelper.toString(columns)); + return columns; + } } private boolean isCorrelation() { 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 2dc1fac0fe..68edac95a7 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 @@ -27,9 +27,6 @@ package org.hibernate.hql.ast.tree; import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents a reference to a FROM element, for example a class alias in a WHERE clause. * @@ -38,13 +35,15 @@ import org.slf4j.LoggerFactory; public abstract class FromReferenceNode extends AbstractSelectExpression implements ResolvableNode, DisplayableNode, InitializeableNode, PathNode { - private static final Logger log = LoggerFactory.getLogger( FromReferenceNode.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + FromReferenceNode.class.getPackage().getName()); private FromElement fromElement; private boolean resolved = false; public static final int ROOT_LEVEL = 0; - public FromElement getFromElement() { + @Override + public FromElement getFromElement() { return fromElement; } @@ -70,9 +69,7 @@ public abstract class FromReferenceNode extends AbstractSelectExpression public void setResolved() { this.resolved = true; - if ( log.isDebugEnabled() ) { - log.debug( "Resolved : " + this.getPath() + " -> " + this.getText() ); - } + LOG.resolved(this.getPath(), this.getText()); } public String getDisplayText() { @@ -101,7 +98,8 @@ public abstract class FromReferenceNode extends AbstractSelectExpression resolve( true, impliedJoin, classAlias, parent ); } - public boolean isReturnableEntity() throws SemanticException { + @Override + public boolean isReturnableEntity() throws SemanticException { return !isScalar() && fromElement.isEntity(); } 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 66b9d53d69..f9543be22c 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 @@ -24,29 +24,24 @@ */ package org.hibernate.hql.ast.tree; -import java.util.List; -import java.util.Iterator; import java.sql.PreparedStatement; import java.sql.SQLException; - +import java.util.Iterator; +import java.util.List; import org.hibernate.QueryException; -import org.hibernate.param.ParameterSpecification; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionImplementor; import org.hibernate.hql.ast.SqlGenerator; import org.hibernate.hql.ast.util.SessionFactoryHelper; +import org.hibernate.param.ParameterSpecification; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.type.CollectionType; import org.hibernate.type.Type; - import antlr.RecognitionException; import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents the [] operator and provides it's semantics. * @@ -54,13 +49,15 @@ import org.slf4j.LoggerFactory; */ public class IndexNode extends FromReferenceNode { - private static final Logger log = LoggerFactory.getLogger( IndexNode.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + IndexNode.class.getPackage().getName()); public void setScalarColumnText(int i) throws SemanticException { throw new UnsupportedOperationException( "An IndexNode cannot generate column text!" ); } - public void prepareForDot(String propertyName) throws SemanticException { + @Override + public void prepareForDot(String propertyName) throws SemanticException { FromElement fromElement = getFromElement(); if ( fromElement == null ) { throw new IllegalStateException( "No FROM element for index operator!" ); @@ -70,9 +67,7 @@ public class IndexNode extends FromReferenceNode { FromReferenceNode collectionNode = ( FromReferenceNode ) getFirstChild(); String path = collectionNode.getPath() + "[]." + propertyName; - if ( log.isDebugEnabled() ) { - log.debug( "Creating join for many-to-many elements for " + path ); - } + LOG.creatingJoinForManyToManyElements(path); FromElementFactory factory = new FromElementFactory( fromElement.getFromClause(), fromElement, path ); // This will add the new from element to the origin. FromElement elementJoin = factory.createElementJoin( queryableCollection ); @@ -84,7 +79,7 @@ public class IndexNode extends FromReferenceNode { throw new UnsupportedOperationException(); } - public void resolve(boolean generateJoin, boolean implicitJoin, String classAlias, AST parent) + public void resolve(boolean generateJoin, boolean implicitJoin, String classAlias, AST parent) throws SemanticException { if ( isResolved() ) { return; @@ -113,16 +108,8 @@ public class IndexNode extends FromReferenceNode { if ( elem == null ) { FromElementFactory factory = new FromElementFactory( fromClause, fromElement, path ); elem = factory.createCollectionElementsJoin( queryableCollection, elementTable ); - if ( log.isDebugEnabled() ) { - log.debug( "No FROM element found for the elements of collection join path " + path - + ", created " + elem ); - } - } - else { - if ( log.isDebugEnabled() ) { - log.debug( "FROM element found for collection join path " + path ); - } - } + LOG.noFromElementFound(path, elem); + } else LOG.fromElementFound(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/MethodNode.java b/hibernate-core/src/main/java/org/hibernate/hql/ast/tree/MethodNode.java index 9d857a6e7b..7186e2bfce 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,7 +25,6 @@ package org.hibernate.hql.ast.tree; import java.util.Arrays; - import org.hibernate.dialect.function.SQLFunction; import org.hibernate.hql.CollectionProperties; import org.hibernate.hql.antlr.SqlTokenTypes; @@ -35,21 +34,18 @@ import org.hibernate.hql.ast.util.ColumnHelper; import org.hibernate.persister.collection.CollectionPropertyNames; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.type.Type; - import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents a method call. * * @author josh */ -public class MethodNode extends AbstractSelectExpression implements SelectExpression, FunctionNode { +public class MethodNode extends AbstractSelectExpression implements FunctionNode { - private static final Logger log = LoggerFactory.getLogger( MethodNode.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + MethodNode.class.getPackage().getName()); private String methodName; private FromElement fromElement; @@ -146,14 +142,13 @@ public class MethodNode extends AbstractSelectExpression implements SelectExpres SqlNode expr = ( SqlNode ) path; Type type = expr.getDataType(); - if ( log.isDebugEnabled() ) { - log.debug( "collectionProperty() : name=" + name + " type=" + type ); - } + LOG.collectionProperty(name, type); resolveCollectionProperty( expr ); } - public boolean isScalar() throws SemanticException { + @Override + public boolean isScalar() throws SemanticException { // Method expressions in a SELECT should always be considered scalar. return true; } @@ -184,9 +179,9 @@ public class MethodNode extends AbstractSelectExpression implements SelectExpres setType( SqlTokenTypes.SQL_TOKEN ); } else { - throw new SemanticException( - "Unexpected expression " + expr + - " found for collection function " + propertyName + throw new SemanticException( + "Unexpected expression " + expr + + " found for collection function " + propertyName ); } } @@ -209,7 +204,7 @@ public class MethodNode extends AbstractSelectExpression implements SelectExpres QueryableCollection queryableCollection = collectionFromElement.getQueryableCollection(); String path = collectionNode.getPath() + "[]." + propertyName; - log.debug( "Creating elements for " + path ); + LOG.creatingElements(path); fromElement = collectionFromElement; if ( !collectionFromElement.isCollectionOfValuesOrComponents() ) { @@ -232,14 +227,15 @@ public class MethodNode extends AbstractSelectExpression implements SelectExpres protected void prepareSelectColumns(String[] columns) { } - public FromElement getFromElement() { + @Override + public FromElement getFromElement() { return fromElement; } public String getDisplayText() { return "{" + "method=" + getMethodName() + - ",selectColumns=" + ( selectColumns == null ? + ",selectColumns=" + ( selectColumns == null ? null : Arrays.asList( selectColumns ) ) + ",fromElement=" + fromElement.getTableAlias() + "}"; 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 ed808fdcec..f143e79817 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 @@ -29,13 +29,9 @@ import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; import org.hibernate.hql.ast.util.ColumnHelper; import org.hibernate.type.Type; - import antlr.SemanticException; import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Defines a top-level AST node representing an HQL select statement. * @@ -43,13 +39,14 @@ import org.slf4j.LoggerFactory; */ public class QueryNode extends AbstractRestrictableStatement implements SelectExpression { - private static final Logger log = LoggerFactory.getLogger( QueryNode.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryNode.class.getPackage().getName()); private OrderByClause orderByClause; private int scalarColumnIndex = -1; /** - * @see Statement#getStatementType() + * @see Statement#getStatementType() */ public int getStatementType() { return HqlSqlTokenTypes.QUERY; @@ -62,12 +59,14 @@ public class QueryNode extends AbstractRestrictableStatement implements SelectEx return false; } - protected int getWhereClauseParentTokenType() { + @Override + protected int getWhereClauseParentTokenType() { return SqlTokenTypes.FROM; } - protected Logger getLog() { - return log; + @Override + protected Logger getLog() { + return LOG; } /** @@ -98,7 +97,7 @@ public class QueryNode extends AbstractRestrictableStatement implements SelectEx // if there is no order by, make one if ( orderByClause == null ) { - log.debug( "getOrderByClause() : Creating a new ORDER BY clause" ); + LOG.getOrderByClause(); orderByClause = ( OrderByClause ) ASTUtil.create( getWalker().getASTFactory(), SqlTokenTypes.ORDER, "ORDER" ); // Find the WHERE; if there is no WHERE, find the FROM... @@ -118,8 +117,8 @@ public class QueryNode extends AbstractRestrictableStatement implements SelectEx private OrderByClause locateOrderByClause() { return ( OrderByClause ) ASTUtil.findTypeInChildren( this, SqlTokenTypes.ORDER ); } - - + + private String alias; public String getAlias() { @@ -159,7 +158,8 @@ public class QueryNode extends AbstractRestrictableStatement implements SelectEx ColumnHelper.generateSingleScalarColumn( this, i ); } - public Type getDataType() { + @Override + public Type getDataType() { return ( (SelectExpression) getSelectClause().getFirstSelectExpression() ).getDataType(); } 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 aea75473c9..98e9e484f6 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 @@ -27,12 +27,8 @@ package org.hibernate.hql.ast.tree; import org.hibernate.hql.antlr.HqlSqlTokenTypes; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.util.ASTUtil; - import antlr.collections.AST; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Defines a top-level AST node representing an HQL update statement. * @@ -40,7 +36,8 @@ import org.slf4j.LoggerFactory; */ public class UpdateStatement extends AbstractRestrictableStatement { - private static final Logger log = LoggerFactory.getLogger( UpdateStatement.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + UpdateStatement.class.getPackage().getName()); /** * @see org.hibernate.hql.ast.tree.Statement#getStatementType() @@ -56,12 +53,14 @@ public class UpdateStatement extends AbstractRestrictableStatement { return true; } - protected int getWhereClauseParentTokenType() { + @Override + protected int getWhereClauseParentTokenType() { return SqlTokenTypes.SET; } - protected Logger getLog() { - return log; + @Override + protected Logger getLog() { + return LOG; } public AST getSetClause() { 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 99cf775508..310ee44ad2 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,37 +24,36 @@ */ 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.Iterator; -import java.util.ListIterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; import java.util.Collection; - +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.StringTokenizer; import org.hibernate.AssertionFailure; import org.hibernate.dialect.Dialect; -import org.hibernate.impl.FilterImpl; -import org.hibernate.type.Type; -import org.hibernate.param.DynamicFilterParameterSpecification; -import org.hibernate.param.CollectionFilterKeyParameterSpecification; import org.hibernate.engine.JoinSequence; -import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.hql.antlr.SqlTokenTypes; import org.hibernate.hql.ast.HqlSqlWalker; +import org.hibernate.hql.ast.tree.DotNode; import org.hibernate.hql.ast.tree.FromClause; import org.hibernate.hql.ast.tree.FromElement; -import org.hibernate.hql.ast.tree.QueryNode; -import org.hibernate.hql.ast.tree.DotNode; import org.hibernate.hql.ast.tree.ParameterContainer; +import org.hibernate.hql.ast.tree.QueryNode; import org.hibernate.hql.classic.ParserHelper; +import org.hibernate.impl.FilterImpl; +import org.hibernate.param.DynamicFilterParameterSpecification; import org.hibernate.sql.JoinFragment; -import org.hibernate.util.StringHelper; +import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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. @@ -65,7 +64,8 @@ import org.slf4j.LoggerFactory; */ public class JoinProcessor implements SqlTokenTypes { - private static final Logger log = LoggerFactory.getLogger( JoinProcessor.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JoinProcessor.class.getPackage().getName()); private final HqlSqlWalker walker; private final SyntheticAndFactory syntheticAndFactory; @@ -137,7 +137,7 @@ public class JoinProcessor implements SqlTokenTypes { 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 + "]" ); + LOG.forcingInclusionOfExtraJoins(alias, containsTableAlias); return true; } boolean shallowQuery = walker.isShallowQuery(); @@ -175,9 +175,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(); - if ( log.isDebugEnabled() ) { - log.debug( "Using FROM fragment [" + fromFragment + "]" ); - } + LOG.usingFromFragment(fromFragment); processDynamicFilterParameters( fromFragment, fromElement, @@ -185,7 +183,7 @@ public class JoinProcessor implements SqlTokenTypes { ); } - syntheticAndFactory.addWhereFragment( + syntheticAndFactory.addWhereFragment( joinFragment, whereFrag, query, @@ -255,4 +253,19 @@ public class JoinProcessor implements SqlTokenTypes { 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 2faddf0058..2b8fa4835e 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,9 +24,15 @@ */ 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.MappingException; import org.hibernate.QueryException; -import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; import org.hibernate.hql.QueryTranslator; import org.hibernate.hql.antlr.HqlSqlTokenTypes; @@ -40,19 +46,14 @@ import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.InFragment; import org.hibernate.type.LiteralType; import org.hibernate.type.Type; -import org.hibernate.type.TypeFactory; 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.text.DecimalFormat; - /** * A delegate that handles literals and constants for HqlSqlWalker, performing the token replacement functions and * classifying literals. @@ -77,7 +78,8 @@ public class LiteralProcessor implements HqlSqlTokenTypes { */ public static int DECIMAL_LITERAL_FORMAT = EXACT; - private static final Logger log = LoggerFactory.getLogger( LiteralProcessor.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + LiteralProcessor.class.getPackage().getName()); private HqlSqlWalker walker; @@ -123,28 +125,20 @@ public class LiteralProcessor implements HqlSqlTokenTypes { // the name of an entity class final String discrim = persister.getDiscriminatorSQLValue(); node.setDataType( persister.getDiscriminatorType() ); - if ( InFragment.NULL.equals(discrim) || InFragment.NOT_NULL.equals(discrim) ) { - throw new InvalidPathException( "subclass test not allowed for null or not null discriminator: '" + text + "'" ); - } - else { - setSQLValue( node, text, discrim ); //the class discriminator value - } + if (InFragment.NULL.equals(discrim) || InFragment.NOT_NULL.equals(discrim)) throw new InvalidPathException( + "subclass test not allowed for null or not null discriminator: '" + + text + "'"); + setSQLValue(node, text, discrim); // the class discriminator value } else { Object value = ReflectHelper.getConstantValue( text ); - if ( value == null ) { - throw new InvalidPathException( "Invalid path: '" + text + "'" ); - } - else { - setConstantValue( node, text, value ); - } + if (value == null) throw new InvalidPathException("Invalid path: '" + text + "'"); + setConstantValue(node, text, value); } } private void setSQLValue(DotNode node, String text, String value) { - if ( log.isDebugEnabled() ) { - log.debug( "setSQLValue() " + text + " -> " + value ); - } + LOG.setSqlValue(text, value); node.setFirstChild( null ); // Chop off the rest of the tree. node.setType( SqlTokenTypes.SQL_TOKEN ); node.setText(value); @@ -152,9 +146,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { } private void setConstantValue(DotNode node, String text, Object value) { - if ( log.isDebugEnabled() ) { - log.debug( "setConstantValue() " + text + " -> " + value + " " + value.getClass().getName() ); - } + LOG.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 ); @@ -222,9 +214,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { private void processLiteral(AST constant) { String replacement = ( String ) walker.getTokenReplacements().get( constant.getText() ); if ( replacement != null ) { - if ( log.isDebugEnabled() ) { - log.debug( "processConstant() : Replacing '" + constant.getText() + "' with '" + replacement + "'" ); - } + LOG.processConstant(constant.getText(), replacement); constant.setText( replacement ); } } @@ -234,15 +224,11 @@ public class LiteralProcessor implements HqlSqlTokenTypes { || literal.getType() == NUM_LONG || literal.getType() == NUM_BIG_INTEGER ) { literal.setText( determineIntegerRepresentation( literal.getText(), literal.getType() ) ); - } - else if ( literal.getType() == NUM_FLOAT + } else if (literal.getType() == NUM_FLOAT || literal.getType() == NUM_DOUBLE || literal.getType() == NUM_BIG_DECIMAL ) { literal.setText( determineDecimalRepresentation( literal.getText(), literal.getType() ) ); - } - else { - log.warn( "Unexpected literal token type [" + literal.getType() + "] passed for numeric processing" ); - } + } else LOG.unexpectedLiteralTokenType(literal.getType()); } private String determineIntegerRepresentation(String text, int type) { @@ -259,7 +245,7 @@ public class LiteralProcessor implements HqlSqlTokenTypes { return Integer.valueOf( text ).toString(); } catch( NumberFormatException e ) { - log.trace( "could not format incoming text [" + text + "] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG" ); + LOG.unableToFormatIncomingText(text); } } String literalValue = text; @@ -335,4 +321,35 @@ 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 989dcfd562..7afb7d5f24 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,15 +24,16 @@ */ package org.hibernate.hql.ast.util; +import static org.jboss.logging.Logger.Level.DEBUG; 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Provides utility methods for paths. * @@ -40,7 +41,8 @@ import org.slf4j.LoggerFactory; */ public final class PathHelper { - private static final Logger log = LoggerFactory.getLogger( PathHelper.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PathHelper.class.getPackage().getName()); private PathHelper() { } @@ -65,13 +67,23 @@ public final class PathHelper { lhs = ASTUtil.createBinarySubtree( factory, HqlSqlTokenTypes.DOT, ".", lhs, child ); } } - if ( log.isDebugEnabled() ) { - log.debug( "parsePath() : " + path + " -> " + ASTUtil.getDebugString( lhs ) ); - } + if (LOG.isDebugEnabled()) LOG.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 855739944d..1298d949ad 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,35 +24,35 @@ */ package org.hibernate.hql.ast.util; +import static org.jboss.logging.Logger.Level.DEBUG; import java.util.Map; - import org.hibernate.hql.antlr.HqlSqlTokenTypes; +import org.hibernate.hql.ast.HqlSqlWalker; import org.hibernate.hql.ast.tree.FromElement; +import org.hibernate.hql.ast.tree.Node; import org.hibernate.hql.ast.tree.QueryNode; import org.hibernate.hql.ast.tree.RestrictableStatement; import org.hibernate.hql.ast.tree.SqlFragment; -import org.hibernate.hql.ast.tree.Node; -import org.hibernate.hql.ast.HqlSqlWalker; +import org.hibernate.param.CollectionFilterKeyParameterSpecification; import org.hibernate.persister.entity.Queryable; import org.hibernate.sql.JoinFragment; -import org.hibernate.util.StringHelper; -import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.type.Type; -import org.hibernate.param.CollectionFilterKeyParameterSpecification; - -import antlr.ASTFactory; +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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Creates synthetic and nodes based on the where fragment part of a JoinSequence. * * @author josh */ public class SyntheticAndFactory implements HqlSqlTokenTypes { - private static final Logger log = LoggerFactory.getLogger( SyntheticAndFactory.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SyntheticAndFactory.class.getPackage().getName()); private HqlSqlWalker hqlSqlWalker; private AST thetaJoins; @@ -91,7 +91,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { whereFragment = whereFragment.substring( 4 ); } - log.debug( "Using unprocessed WHERE-fragment [{}]", whereFragment ); + LOG.usingUnprocessedWhereFragment(whereFragment); SqlFragment fragment = ( SqlFragment ) create( SQL_TOKEN, whereFragment ); fragment.setJoinFragment( joinFragment ); @@ -122,7 +122,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { hqlSqlWalker ); - log.debug( "Using processed WHERE-fragment [{}]", fragment.getText() ); + LOG.usingProcessedWhereFragment(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, @@ -136,7 +136,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { // Put the FILTERS node before the HQL condition and theta joins ASTUtil.insertChild( where, filters ); } - + // add the current fragment to the FILTERS node filters.addChild( fragment ); } @@ -154,7 +154,7 @@ public class SyntheticAndFactory implements HqlSqlTokenTypes { ASTUtil.insertSibling( thetaJoins, filters ); } } - + // add the current fragment to the THETA_JOINS node thetaJoins.addChild(fragment); } @@ -204,4 +204,19 @@ 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 b7672348f8..e5c4db2fa4 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,6 +24,7 @@ */ 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; @@ -38,23 +39,18 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.LockOptions; import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.ScrollableResults; -import org.hibernate.LockOptions; import org.hibernate.dialect.Dialect; import org.hibernate.engine.JoinSequence; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.event.EventSource; -import org.hibernate.exception.JDBCExceptionHelper; import org.hibernate.hql.FilterTranslator; import org.hibernate.hql.HolderInstantiator; import org.hibernate.hql.NameGenerator; @@ -75,6 +71,10 @@ 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 @@ -82,6 +82,9 @@ import org.hibernate.util.StringHelper; */ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator { + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + QueryTranslatorImpl.class.getPackage().getName()); + private static final String[] NO_RETURN_ALIASES = new String[] {}; private final String queryIdentifier; @@ -140,8 +143,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator private Map enabledFilters; - private static final Logger log = LoggerFactory.getLogger( QueryTranslatorImpl.class ); - /** * Construct a query translator * @@ -235,7 +236,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator */ private void compile() throws QueryException, MappingException { - log.trace( "compiling query" ); + LOG.compilingQuery(); try { ParserHelper.parse( new PreprocessingParser( tokenReplacements ), queryString, @@ -251,7 +252,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator throw me; } catch ( Exception e ) { - log.debug( "unexpected query compilation problem", e ); + LOG.debug(LOG.unexpectedQueryCompilationProblem(), e); e.printStackTrace(); QueryException qe = new QueryException( "Incorrect query syntax", e ); qe.setQueryString( queryString ); @@ -264,7 +265,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } - public String getSQLString() { + @Override + public String getSQLString() { return sqlString; } @@ -281,7 +283,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator * * @return an array of EntityPersisters. */ - protected Loadable[] getEntityPersisters() { + @Override + protected Loadable[] getEntityPersisters() { return persisters; } @@ -293,7 +296,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator public Type[] getReturnTypes() { return actualReturnTypes; } - + public String[] getReturnAliases() { // return aliases not supported in classic translator! return NO_RETURN_ALIASES; @@ -304,9 +307,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } private static void logQuery(String hql, String sql) { - if ( log.isDebugEnabled() ) { - log.debug( "HQL: " + hql ); - log.debug( "SQL: " + sql ); + if (LOG.isDebugEnabled()) { + LOG.debug("HQL: " + hql); + LOG.debug("SQL: " + sql); } } @@ -545,7 +548,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } } - public int[] getNamedParameterLocs(String name) throws QueryException { + @Override + public int[] getNamedParameterLocs(String name) throws QueryException { Object o = namedParameters.get( name ); if ( o == null ) { QueryException qe = new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name ); @@ -722,7 +726,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator for ( int k = 0; k < size; k++ ) { scalarTypes.add( - getFactory().getTypeResolver().getTypeFactory().manyToOne( persisters[k].getEntityName(), shallowQuery ) + getFactory().getTypeResolver().getTypeFactory().manyToOne( persisters[k].getEntityName(), shallowQuery ) ); String[] idColumnNames = persisters[k].getIdentifierColumnNames(); @@ -855,11 +859,13 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator /** * Overrides method from Loader */ - public CollectionPersister[] getCollectionPersisters() { + @Override + public CollectionPersister[] getCollectionPersisters() { return collectionPersister == null ? null : new CollectionPersister[] { collectionPersister }; } - protected String[] getCollectionSuffixes() { + @Override + protected String[] getCollectionSuffixes() { return collectionPersister == null ? null : new String[] { "__" }; } @@ -873,11 +879,13 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } } - protected String[] getSuffixes() { + @Override + protected String[] getSuffixes() { return suffixes; } - protected String[] getAliases() { + @Override + protected String[] getAliases() { return names; } @@ -972,7 +980,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator throw getFactory().getSQLExceptionHelper().convert( sqle, "could not execute query using iterate", - getSQLString() + getSQLString() ); } @@ -982,7 +990,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator throw new UnsupportedOperationException( "Not supported! Use the AST translator..."); } - protected boolean[] includeInResultRow() { + @Override + protected boolean[] includeInResultRow() { boolean[] isResultReturned = includeInSelect; if ( hasScalars ) { isResultReturned = new boolean[ returnedTypes.size() ]; @@ -992,14 +1001,16 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } - protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) { + @Override + protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) { return HolderInstantiator.resolveClassicResultTransformer( holderConstructor, resultTransformer ); } - protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) + @Override + protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { Object[] resultRow = getResultRow( row, rs, session ); return ( holderClass == null && resultRow.length == 1 ? @@ -1008,7 +1019,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator ); } - protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session) + @Override + protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { Object[] resultRow; if ( hasScalars ) { @@ -1025,7 +1037,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator return resultRow; } - protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException { + @Override + protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException { if ( holderClass != null ) { for ( int i = 0; i < results.size(); i++ ) { Object[] row = ( Object[] ) results.get( i ); @@ -1058,7 +1071,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator holderClass = clazz; } - protected LockMode[] getLockModes(LockOptions lockOptions) { + @Override + protected LockMode[] getLockModes(LockOptions lockOptions) { // unfortunately this stuff can't be cached because // it is per-invocation, not constant for the @@ -1086,7 +1100,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator return lockModesArray; } - protected String applyLocks(String sql, LockOptions lockOptions, Dialect dialect) throws QueryException { + @Override + protected String applyLocks(String sql, LockOptions lockOptions, Dialect dialect) throws QueryException { // can't cache this stuff either (per-invocation) final String result; if ( lockOptions == null || @@ -1116,11 +1131,13 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator return result; } - protected boolean upgradeLocks() { + @Override + protected boolean upgradeLocks() { return true; } - protected int[] getCollectionOwners() { + @Override + protected int[] getCollectionOwners() { return new int[] { collectionOwnerColumn }; } @@ -1128,15 +1145,18 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator return compiled; } - public String toString() { + @Override + public String toString() { return queryString; } - protected int[] getOwners() { + @Override + protected int[] getOwners() { return owners; } - protected EntityType[] getOwnerAssociationTypes() { + @Override + protected EntityType[] getOwnerAssociationTypes() { return ownerAssociationTypes; } @@ -1155,11 +1175,13 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator return scroll( queryParameters, returnTypes, hi, session ); } - public String getQueryIdentifier() { + @Override + public String getQueryIdentifier() { return queryIdentifier; } - protected boolean isSubselectLoadingEnabled() { + @Override + protected boolean isSubselectLoadingEnabled() { return hasSubselectLoadableCollections(); } @@ -1213,4 +1235,18 @@ 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 d183b1a592..ee00b81610 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/GUIDGenerator.java @@ -23,15 +23,17 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; 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. @@ -39,23 +41,21 @@ import org.hibernate.engine.SessionImplementor; * @author Joseph Fifield */ public class GUIDGenerator implements IdentifierGenerator { - private static final Logger log = LoggerFactory.getLogger(GUIDGenerator.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + GUIDGenerator.class.getPackage().getName()); private static boolean warned = false; public GUIDGenerator() { if ( ! warned ) { warned = true; - log.warn( - "DEPRECATED : use {} instead with custom {} implementation", - UUIDGenerator.class.getName(), - UUIDGenerationStrategy.class.getName() - ); + LOG.deprecatedUuidGenerator(UUIDGenerator.class.getName(), UUIDGenerationStrategy.class.getName()); } } public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { - + final String sql = session.getFactory().getDialect().getSelectGUIDString(); try { PreparedStatement st = session.getJDBCContext().getConnectionManager().prepareSelectStatement(sql); @@ -69,7 +69,7 @@ public class GUIDGenerator implements IdentifierGenerator { finally { rs.close(); } - log.debug("GUID identifier generated: " + result); + LOG.guidGenerated(result); return result; } finally { @@ -85,4 +85,19 @@ 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 5dce34f303..8bac64c0e7 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java @@ -24,19 +24,20 @@ */ package org.hibernate.id; +import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; -import org.hibernate.type.Type; 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. @@ -45,7 +46,9 @@ import org.hibernate.type.CustomType; * @author Steve Ebersole */ public final class IdentifierGeneratorHelper { - private static final Logger log = LoggerFactory.getLogger( IdentifierGeneratorHelper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + IdentifierGeneratorHelper.class.getPackage().getName()); /** * Marker object returned from {@link IdentifierGenerator#generate} to indicate that we should short-circuit any @@ -54,7 +57,8 @@ public final class IdentifierGeneratorHelper { * entity's id value. */ public static final Serializable SHORT_CIRCUIT_INDICATOR = new Serializable() { - public String toString() { + @Override + public String toString() { return "SHORT_CIRCUIT_INDICATOR"; } }; @@ -64,7 +68,8 @@ public final class IdentifierGeneratorHelper { * be generated as part of the datbase insertion. */ public static final Serializable POST_INSERT_INDICATOR = new Serializable() { - public String toString() { + @Override + public String toString() { return "POST_INSERT_INDICATOR"; } }; @@ -84,7 +89,7 @@ public final class IdentifierGeneratorHelper { throw new HibernateException( "The database returned no natively generated identity value" ); } final Serializable id = IdentifierGeneratorHelper.get( rs, type ); - log.debug( "Natively generated identity: " + id ); + LOG.nativelyGeneratedIdentity(id); return id; } @@ -147,7 +152,8 @@ public final class IdentifierGeneratorHelper { * * @deprecated Use the {@link #getIntegralDataTypeHolder holders} instead. */ - public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException { + @Deprecated + public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException { if ( clazz == Long.class ) { return new Long( value ); } @@ -363,11 +369,13 @@ public final class IdentifierGeneratorHelper { return result; } - public String toString() { + @Override + public String toString() { return "BasicHolder[" + exactType.getName() + "[" + value + "]]"; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -380,7 +388,8 @@ public final class IdentifierGeneratorHelper { return value == that.value; } - public int hashCode() { + @Override + public int hashCode() { return (int) ( value ^ ( value >>> 32 ) ); } } @@ -501,11 +510,13 @@ public final class IdentifierGeneratorHelper { return result; } - public String toString() { + @Override + public String toString() { return "BigIntegerHolder[" + value + "]"; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -520,7 +531,8 @@ public final class IdentifierGeneratorHelper { : value.equals( that.value ); } - public int hashCode() { + @Override + public int hashCode() { return value != null ? value.hashCode() : 0; } } @@ -641,11 +653,13 @@ public final class IdentifierGeneratorHelper { return result; } - public String toString() { + @Override + public String toString() { return "BigDecimalHolder[" + value + "]"; } - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if ( this == o ) { return true; } @@ -660,7 +674,8 @@ public final class IdentifierGeneratorHelper { : this.value.equals( that.value ); } - public int hashCode() { + @Override + public int hashCode() { return value != null ? value.hashCode() : 0; } } @@ -671,4 +686,14 @@ 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 7cdd9bf16e..ac0a4e4530 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java @@ -23,14 +23,12 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.cfg.ObjectNameNormalizer; @@ -39,6 +37,10 @@ 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
    @@ -54,7 +56,9 @@ import org.hibernate.util.StringHelper; * @author Steve Ebersole */ public class IncrementGenerator implements IdentifierGenerator, Configurable { - private static final Logger log = LoggerFactory.getLogger(IncrementGenerator.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + IncrementGenerator.class.getPackage().getName()); private Class returnClass; private String sql; @@ -112,27 +116,23 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable { buf.insert( 0, "( " ).append( " ) ids_" ); column = "ids_." + column; } - + sql = "select max(" + column + ") from " + buf.toString(); } private void initializePreviousValueHolder(SessionImplementor session) { previousValueHolder = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass ); - log.debug( "fetching initial value: " + sql ); + LOG.fetchingInitialValue(sql); try { PreparedStatement st = session.getJDBCContext().getConnectionManager().prepareSelectStatement( sql ); try { ResultSet rs = st.executeQuery(); try { - if ( rs.next() ) { - previousValueHolder.initialize( rs, 0L ).increment(); - } - else { - previousValueHolder.initialize( 1L ); - } + if (rs.next()) previousValueHolder.initialize(rs, 0L).increment(); + else previousValueHolder.initialize(1L); sql = null; - log.debug( "first free id: " + previousValueHolder.makeValue() ); + LOG.firstFreeId(previousValueHolder.makeValue()); } finally { rs.close(); @@ -151,4 +151,18 @@ 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 bad7b90643..8557aa1b30 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java @@ -30,22 +30,22 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.MappingException; import org.hibernate.cfg.ObjectNameNormalizer; +import org.hibernate.dialect.Dialect; +import org.hibernate.engine.SessionImplementor; +import org.hibernate.engine.TransactionHelper; import org.hibernate.id.enhanced.AccessCallback; import org.hibernate.id.enhanced.OptimizerFactory; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.jdbc.util.FormatStyle; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.SessionImplementor; -import org.hibernate.engine.TransactionHelper; 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; /** * @@ -64,7 +64,7 @@ import org.hibernate.type.Type; *

    *

    This implementation is not compliant with a user connection

    *

    - * + * *

    Allowed parameters (all of them are optional):

    *
      *
    • table: table name (default hibernate_sequences)
    • @@ -78,12 +78,13 @@ import org.hibernate.type.Type; * @author Emmanuel Bernard * @author Klaus Richarz. */ -public class MultipleHiLoPerTableGenerator +public class MultipleHiLoPerTableGenerator extends TransactionHelper implements PersistentIdentifierGenerator, Configurable { - - private static final Logger log = LoggerFactory.getLogger(MultipleHiLoPerTableGenerator.class); - + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + MultipleHiLoPerTableGenerator.class.getPackage().getName()); + public static final String ID_TABLE = "table"; public static final String PK_COLUMN_NAME = "primary_key_column"; public static final String PK_VALUE_NAME = "primary_key_value"; @@ -94,7 +95,7 @@ public class MultipleHiLoPerTableGenerator public static final String DEFAULT_TABLE = "hibernate_sequences"; private static final String DEFAULT_PK_COLUMN = "sequence_name"; private static final String DEFAULT_VALUE_COLUMN = "sequence_next_hi_value"; - + private String tableName; private String pkColumnName; private String valueColumnName; @@ -146,7 +147,8 @@ public class MultipleHiLoPerTableGenerator return tableName; } - public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { + @Override + public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass ); int rows; do { @@ -169,7 +171,7 @@ public class MultipleHiLoPerTableGenerator rs.close(); } catch (SQLException sqle) { - log.error("could not read or init a hi value", sqle); + LOG.error(LOG.unableToReadOrInitHiValue(), sqle); throw sqle; } finally { @@ -187,7 +189,7 @@ public class MultipleHiLoPerTableGenerator rows = ups.executeUpdate(); } catch (SQLException sqle) { - log.error("could not update hi value in: " + tableName, sqle); + LOG.error(LOG.unableToUpdateHiValue(tableName), sqle); throw sqle; } finally { @@ -266,10 +268,10 @@ public class MultipleHiLoPerTableGenerator valueColumnName + " = ? and " + pkColumnName + - " = '" + - keyValue + " = '" + + keyValue + "'"; - + insert = "insert into " + tableName + "(" + pkColumnName + ", " + valueColumnName + ") " + "values('"+ keyValue +"', ?)"; @@ -283,4 +285,17 @@ 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 87f37e08a7..82a77da913 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/SequenceGenerator.java @@ -23,22 +23,25 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; 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.hibernate.internal.util.config.ConfigurationHelper; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * sequence
      @@ -53,7 +56,9 @@ import org.hibernate.internal.util.config.ConfigurationHelper; * @author Gavin King */ public class SequenceGenerator implements PersistentIdentifierGenerator, Configurable { - private static final Logger log = LoggerFactory.getLogger(SequenceGenerator.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SequenceGenerator.class.getPackage().getName()); /** * The sequence parameter @@ -113,9 +118,7 @@ public class SequenceGenerator implements PersistentIdentifierGenerator, Configu rs.next(); IntegralDataTypeHolder result = buildHolder(); result.initialize( rs, 1 ); - if ( log.isDebugEnabled() ) { - log.debug("Sequence identifier generated: " + result); - } + LOG.sequenceIdentifierGenerated(result); return result; } finally { @@ -160,4 +163,14 @@ public class SequenceGenerator implements PersistentIdentifierGenerator, Configu 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 5382fbeda2..ec3597172a 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/SequenceIdentityGenerator.java @@ -24,22 +24,24 @@ */ package org.hibernate.id; -import org.hibernate.id.insert.InsertGeneratedIdentifierDelegate; -import org.hibernate.id.insert.AbstractReturningDelegate; -import org.hibernate.id.insert.IdentifierGeneratingInsert; -import org.hibernate.dialect.Dialect; -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.sql.Insert; -import org.hibernate.type.Type; -import org.hibernate.engine.SessionImplementor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +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.MappingException; +import org.hibernate.dialect.Dialect; +import org.hibernate.engine.SessionImplementor; +import org.hibernate.id.insert.AbstractReturningDelegate; +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 @@ -57,9 +59,11 @@ import java.util.Properties; public class SequenceIdentityGenerator extends SequenceGenerator implements PostInsertIdentifierGenerator { - private static final Logger log = LoggerFactory.getLogger( SequenceIdentityGenerator.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SequenceIdentityGenerator.class.getPackage().getName()); - public Serializable generate(SessionImplementor s, Object obj) { + @Override + public Serializable generate(SessionImplementor s, Object obj) { return IdentifierGeneratorHelper.POST_INSERT_INDICATOR; } @@ -70,7 +74,8 @@ public class SequenceIdentityGenerator extends SequenceGenerator return new Delegate( persister, dialect, getSequenceName() ); } - public void configure(Type type, Properties params, Dialect dialect) throws MappingException { + @Override + public void configure(Type type, Properties params, Dialect dialect) throws MappingException { super.configure( type, params, dialect ); } @@ -95,11 +100,13 @@ public class SequenceIdentityGenerator extends SequenceGenerator return insert; } - protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException { + @Override + protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException { return session.getJDBCContext().getConnectionManager().prepareStatement( insertSQL, keyColumns ); } - protected Serializable executeAndExtract(PreparedStatement insert) throws SQLException { + @Override + protected Serializable executeAndExtract(PreparedStatement insert) throws SQLException { insert.executeUpdate(); return IdentifierGeneratorHelper.getGeneratedIdentity( insert.getGeneratedKeys(), @@ -113,11 +120,23 @@ public class SequenceIdentityGenerator extends SequenceGenerator super( dialect ); } - public Insert setComment(String comment) { + @Override + public Insert setComment(String comment) { // don't allow comments on these insert statements as comments totally // blow up the Oracle getGeneratedKeys "support" :( - log.info( "disallowing insert statement comment for select-identity due to Oracle driver bug" ); + LOG.disallowingInsertStatementComment(); 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 8cff01a2a3..7ca826fb78 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/TableGenerator.java @@ -31,19 +31,19 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.cfg.ObjectNameNormalizer; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.jdbc.util.FormatStyle; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.TransactionHelper; +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 @@ -75,17 +75,18 @@ public class TableGenerator extends TransactionHelper /* COLUMN and TABLE should be renamed but it would break the public API */ /** The column parameter */ public static final String COLUMN = "column"; - + /** Default column name */ public static final String DEFAULT_COLUMN_NAME = "next_hi"; - + /** The table parameter */ public static final String TABLE = "table"; - - /** Default table name */ + + /** Default table name */ public static final String DEFAULT_TABLE_NAME = "hibernate_unique_key"; - private static final Logger log = LoggerFactory.getLogger(TableGenerator.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TableGenerator.class.getPackage().getName()); private Type identifierType; private String tableName; @@ -119,18 +120,18 @@ public class TableGenerator extends TransactionHelper ) ); - query = "select " + - columnName + - " from " + + query = "select " + + columnName + + " from " + dialect.appendLockHint(LockMode.PESSIMISTIC_WRITE, tableName) + dialect.getForUpdateString(); - update = "update " + - tableName + - " set " + - columnName + - " = ? where " + - columnName + + update = "update " + + tableName + + " set " + + columnName + + " = ? where " + + columnName + " = ?"; } @@ -176,7 +177,8 @@ public class TableGenerator extends TransactionHelper * * @throws SQLException */ - public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { + @Override + public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { IntegralDataTypeHolder value = buildHolder(); int rows; do { @@ -190,15 +192,15 @@ public class TableGenerator extends TransactionHelper try { ResultSet rs = qps.executeQuery(); if ( !rs.next() ) { - String err = "could not read a hi value - you need to populate the table: " + tableName; - log.error(err); + String err = LOG.unableToReadHiValue(tableName); + LOG.error(err); throw new IdentifierGenerationException(err); } value.initialize( rs, 1 ); rs.close(); } catch (SQLException sqle) { - log.error("could not read a hi value", sqle); + LOG.error(LOG.unableToReadHiValue(), sqle); throw sqle; } finally { @@ -214,7 +216,7 @@ public class TableGenerator extends TransactionHelper rows = ups.executeUpdate(); } catch (SQLException sqle) { - log.error("could not update hi value in: " + tableName, sqle); + LOG.error(LOG.unableToUpdateHiValue(tableName), sqle); throw sqle; } finally { @@ -228,4 +230,20 @@ 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 50d33dea70..f29afa6ebd 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/UUIDGenerator.java @@ -23,13 +23,10 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; @@ -38,6 +35,10 @@ 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 @@ -60,7 +61,8 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable { public static final String UUID_GEN_STRATEGY = "uuid_gen_strategy"; public static final String UUID_GEN_STRATEGY_CLASS = "uuid_gen_strategy_class"; - private static final Logger log = LoggerFactory.getLogger( UUIDGenerator.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + UUIDGenerator.class.getPackage().getName()); private UUIDGenerationStrategy strategy; private UUIDTypeDescriptor.ValueTransformer valueTransformer; @@ -85,11 +87,11 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable { strategy = (UUIDGenerationStrategy) strategyClass.newInstance(); } catch ( Exception ignore ) { - log.warn( "Unable to instantiate UUID generation strategy class : {}", ignore ); + LOG.unableToInstantiateUuidGenerationStrategy(ignore); } } catch ( ClassNotFoundException ignore ) { - log.warn( "Unable to locate requested UUID generation strategy class : {}", strategyClassName ); + LOG.unableToLocateUuidGenerationStrategy(strategyClassName); } } } @@ -116,4 +118,18 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable { 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 ea5e2cd0bf..0cd1059e47 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/UUIDHexGenerator.java @@ -23,16 +23,17 @@ */ package org.hibernate.id; +import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; -import org.hibernate.type.Type; 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
      @@ -47,7 +48,10 @@ import org.hibernate.internal.util.config.ConfigurationHelper; * @author Gavin King */ public class UUIDHexGenerator extends AbstractUUIDGenerator implements Configurable { - private static final Logger log = LoggerFactory.getLogger( UUIDHexGenerator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + UUIDHexGenerator.class.getPackage().getName()); + private static boolean warned = false; private String sep = ""; @@ -55,11 +59,7 @@ public class UUIDHexGenerator extends AbstractUUIDGenerator implements Configura public UUIDHexGenerator() { if ( ! warned ) { warned = true; - log.warn( - "Using {} which does not generate IETF RFC 4122 compliant UUID values; consider using {} instead", - this.getClass().getName(), - UUIDGenerator.class.getName() - ); + LOG.usingUuidHexGenerator(this.getClass().getName(), UUIDGenerator.class.getName()); } } @@ -96,4 +96,16 @@ 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 13b83039bd..189662ecd6 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,15 +23,18 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; 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. @@ -39,7 +42,9 @@ import org.hibernate.util.ReflectHelper; * @author Steve Ebersole */ public class OptimizerFactory { - private static final Logger log = LoggerFactory.getLogger( OptimizerFactory.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OptimizerFactory.class.getPackage().getName()); public static final String NONE = "none"; public static final String HILO = "hilo"; @@ -78,7 +83,8 @@ public class OptimizerFactory { * * @deprecated Use {@link #buildOptimizer(String, Class, int, long)} instead */ - @SuppressWarnings({ "UnnecessaryBoxing" }) + @Deprecated + @SuppressWarnings({ "UnnecessaryBoxing" }) public static Optimizer buildOptimizer(String type, Class returnClass, int incrementSize) { String optimizerClassName; if ( NONE.equals( type ) ) { @@ -106,7 +112,7 @@ public class OptimizerFactory { return ( Optimizer ) ctor.newInstance( returnClass, Integer.valueOf( incrementSize ) ); } catch( Throwable ignore ) { - log.warn( "Unable to instantiate specified optimizer [{}], falling back to noop", type ); + LOG.unableToInstantiateOptimizer(type); } // the default... @@ -252,12 +258,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" ); - } - if ( log.isTraceEnabled() ) { - log.trace( "creating hilo optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + "]" ); - } + if (incrementSize < 1) throw new HibernateException("increment size cannot be less than 1"); + LOG.creatingHiloOptimizer(incrementSize, returnClass.getName()); } /** @@ -332,13 +334,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" ); - } - if ( log.isTraceEnabled() ) { - log.trace( "creating hilo optimizer (legacy) with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + "]" ); - } - + if (incrementSize < 1) throw new HibernateException("increment size cannot be less than 1"); + LOG.creatingLegacyHiloOptimizer(incrementSize, returnClass.getName()); maxLo = incrementSize; lo = maxLo+1; } @@ -403,9 +400,7 @@ public class OptimizerFactory { if ( incrementSize < 1 ) { throw new HibernateException( "increment size cannot be less than 1" ); } - if ( log.isTraceEnabled() ) { - log.trace( "creating pooled optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + "]" ); - } + LOG.creatingPooledOptimizer(incrementSize, returnClass.getName()); } /** @@ -414,17 +409,13 @@ public class OptimizerFactory { public synchronized Serializable generate(AccessCallback callback) { if ( hiValue == null ) { value = callback.getNextValue(); - if ( value.lt( 1 ) ) { - // unfortunately not really safe to normalize this - // to 1 as an initial value like we do the others - // because we would not be able to control this if - // we are using a sequence... - log.info( "pooled optimizer source reported [" + value + "] as the initial value; use of 1 or greater highly recommended" ); - } - if ( ( initialValue == -1 && value.lt( incrementSize ) ) || value.eq( initialValue ) ) { - // the call to obtain next-value just gave us the initialValue - hiValue = callback.getNextValue(); - } + // unfortunately not really safe to normalize this + // to 1 as an initial value like we do the others + // because we would not be able to control this if + // we are using a sequence... + if (value.lt(1)) LOG.pooledOptimizerReportedInitialValue(value); + // the call to obtain next-value just gave us the initialValue + if ((initialValue == -1 && value.lt(incrementSize)) || value.eq(initialValue)) hiValue = callback.getNextValue(); else { hiValue = value; value = hiValue.copy().subtract( incrementSize ); @@ -479,9 +470,7 @@ public class OptimizerFactory { if ( incrementSize < 1 ) { throw new HibernateException( "increment size cannot be less than 1" ); } - if ( log.isTraceEnabled() ) { - log.trace( "creating pooled optimizer (lo) with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.getName() + "]" ); - } + LOG.creatingPooledLoOptimizer(incrementSize, returnClass.getName()); } public Serializable generate(AccessCallback callback) { @@ -504,4 +493,39 @@ 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 d946d2cf1e..4b43474d68 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,18 +24,19 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; -import org.hibernate.HibernateException; 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. @@ -43,7 +44,9 @@ import org.hibernate.id.IntegralDataTypeHolder; * @author Steve Ebersole */ public class SequenceStructure implements DatabaseStructure { - private static final Logger log = LoggerFactory.getLogger( SequenceStructure.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SequenceStructure.class.getPackage().getName()); private final String sequenceName; private final int initialValue; @@ -109,9 +112,7 @@ public class SequenceStructure implements DatabaseStructure { rs.next(); IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( numberType ); value.initialize( rs, 1 ); - if ( log.isDebugEnabled() ) { - log.debug( "Sequence value obtained: " + value.makeValue() ); - } + LOG.sequenceValueObtained(value.makeValue()); return value; } finally { @@ -160,4 +161,15 @@ 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 6faac74b8e..7b7c8049fc 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,23 +23,25 @@ */ package org.hibernate.id.enhanced; -import java.util.Properties; +import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.WARN; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.cfg.Environment; -import org.hibernate.id.PersistentIdentifierGenerator; -import org.hibernate.id.Configurable; +import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.MappingException; +import org.hibernate.cfg.Environment; import org.hibernate.cfg.ObjectNameNormalizer; +import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.mapping.Table; import org.hibernate.type.Type; -import org.hibernate.dialect.Dialect; +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. @@ -97,7 +99,9 @@ import org.hibernate.dialect.Dialect; * @author Steve Ebersole */ public class SequenceStyleGenerator implements PersistentIdentifierGenerator, Configurable { - private static final Logger log = LoggerFactory.getLogger( SequenceStyleGenerator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SequenceStyleGenerator.class.getPackage().getName()); // general purpose parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public static final String SEQUENCE_PARAM = "sequence_name"; @@ -172,9 +176,7 @@ public class SequenceStyleGenerator implements PersistentIdentifierGenerator, Co if ( dialect.supportsSequences() && !forceTableUse ) { if ( OptimizerFactory.POOL.equals( optimizationStrategy ) && !dialect.supportsPooledSequences() ) { forceTableUse = true; - log.info( - "Forcing table use for sequence-style generator due to pooled optimizer selection where db does not support pooled sequences" - ); + LOG.forcingTableUse(); } } @@ -299,7 +301,7 @@ public class SequenceStyleGenerator implements PersistentIdentifierGenerator, Co */ protected int determineAdjustedIncrementSize(String optimizationStrategy, int incrementSize) { if ( OptimizerFactory.NONE.equals( optimizationStrategy ) && incrementSize > 1 ) { - log.warn( "config specified explicit optimizer of [" + OptimizerFactory.NONE + "], but [" + INCREMENT_PARAM + "=" + incrementSize + "; honoring optimizer setting" ); + LOG.honoringOptimizerSetting(OptimizerFactory.NONE, INCREMENT_PARAM, incrementSize); incrementSize = 1; } return incrementSize; @@ -369,4 +371,21 @@ 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 a1d4db56b4..7014b891e0 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,37 +23,38 @@ */ package org.hibernate.id.enhanced; -import java.sql.Types; +import static org.jboss.logging.Logger.Level.INFO; +import java.io.Serializable; import java.sql.Connection; -import java.sql.SQLException; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.util.Properties; +import java.sql.SQLException; +import java.sql.Types; import java.util.Collections; import java.util.Map; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.util.Properties; +import org.hibernate.HibernateException; +import org.hibernate.LockMode; +import org.hibernate.LockOptions; +import org.hibernate.MappingException; import org.hibernate.cfg.Environment; -import org.hibernate.engine.TransactionHelper; +import org.hibernate.cfg.ObjectNameNormalizer; +import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionImplementor; +import org.hibernate.engine.TransactionHelper; +import org.hibernate.id.Configurable; import org.hibernate.id.IdentifierGeneratorHelper; import org.hibernate.id.IntegralDataTypeHolder; import org.hibernate.id.PersistentIdentifierGenerator; -import org.hibernate.id.Configurable; import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.type.Type; -import org.hibernate.dialect.Dialect; -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.LockOptions; -import org.hibernate.LockMode; -import org.hibernate.cfg.ObjectNameNormalizer; 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. @@ -129,7 +130,9 @@ import org.hibernate.util.StringHelper; * @author Steve Ebersole */ public class TableGenerator extends TransactionHelper implements PersistentIdentifierGenerator, Configurable { - private static final Logger log = LoggerFactory.getLogger( TableGenerator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TableGenerator.class.getPackage().getName()); public static final String CONFIG_PREFER_SEGMENT_PER_ENTITY = "prefer_entity_table_as_segment_value"; @@ -410,7 +413,7 @@ public class TableGenerator extends TransactionHelper implements PersistentIdent protected String determineDefaultSegmentValue(Properties params) { boolean preferSegmentPerEntity = ConfigurationHelper.getBoolean( CONFIG_PREFER_SEGMENT_PER_ENTITY, params, false ); String defaultToUse = preferSegmentPerEntity ? params.getProperty( TABLE ) : DEF_SEGMENT_VALUE; - log.info( "explicit segment value for id generator [" + tableName + '.' + segmentColumnName + "] suggested; using default [" + defaultToUse + "]" ); + LOG.usingDefaultIdGeneratorSegmentValue(tableName, segmentColumnName, defaultToUse); return defaultToUse; } @@ -472,7 +475,8 @@ public class TableGenerator extends TransactionHelper implements PersistentIdent /** * {@inheritDoc} */ - public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { + @Override + public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( identifierType.getReturnedClass() ); int rows; do { @@ -503,7 +507,7 @@ public class TableGenerator extends TransactionHelper implements PersistentIdent selectRS.close(); } catch ( SQLException sqle ) { - log.error( "could not read or init a hi value", sqle ); + LOG.error(LOG.unableToReadOrInitHiValue(), sqle); throw sqle; } finally { @@ -526,7 +530,7 @@ public class TableGenerator extends TransactionHelper implements PersistentIdent rows = updatePS.executeUpdate(); } catch ( SQLException sqle ) { - log.error( "could not updateQuery hi value in: " + tableName, sqle ); + LOG.error(LOG.unableToUpdateQueryHiValue(tableName), sqle); throw sqle; } finally { @@ -579,4 +583,23 @@ 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 931128d136..351e4d58ca 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 @@ -30,10 +30,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.dialect.Dialect; @@ -44,6 +40,9 @@ 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 @@ -51,8 +50,10 @@ import org.hibernate.jdbc.util.SQLStatementLogger; * @author Steve Ebersole */ public class TableStructure extends TransactionHelper implements DatabaseStructure { - private static final Logger log = LoggerFactory.getLogger( TableStructure.class ); - private static final SQLStatementLogger SQL_STATEMENT_LOGGER = new SQLStatementLogger( false, false ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TableStructure.class.getPackage().getName()); + private static final SQLStatementLogger SQL_STATEMENT_LOGGER = new SQLStatementLogger(false, false); private final String tableName; private final String valueColumnName; @@ -161,7 +162,8 @@ public class TableStructure extends TransactionHelper implements DatabaseStructu /** * {@inheritDoc} */ - protected Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { + @Override + protected Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException { IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( numberType ); int rows; do { @@ -170,15 +172,15 @@ public class TableStructure extends TransactionHelper implements DatabaseStructu try { ResultSet selectRS = selectPS.executeQuery(); if ( !selectRS.next() ) { - String err = "could not read a hi value - you need to populate the table: " + tableName; - log.error( err ); + String err = LOG.unableToReadHiValue(tableName); + LOG.error(err); throw new IdentifierGenerationException( err ); } value.initialize( selectRS, 1 ); selectRS.close(); } catch ( SQLException sqle ) { - log.error( "could not read a hi value", sqle ); + LOG.error(LOG.unableToReadHiValue(), sqle); throw sqle; } finally { @@ -195,7 +197,7 @@ public class TableStructure extends TransactionHelper implements DatabaseStructu rows = updatePS.executeUpdate(); } catch ( SQLException sqle ) { - log.error( "could not updateQuery hi value in: " + tableName, sqle ); + LOG.error(LOG.unableToUpdateQueryHiValue(tableName), sqle); throw sqle; } finally { @@ -208,4 +210,19 @@ 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 abf3043e8b..916d216231 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,33 +23,34 @@ */ package org.hibernate.id.factory; -import java.util.Properties; +import static org.jboss.logging.Logger.Level.DEBUG; import java.io.Serializable; +import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.hibernate.id.IdentifierGenerator; -import org.hibernate.id.UUIDGenerator; -import org.hibernate.id.UUIDHexGenerator; -import org.hibernate.id.TableHiLoGenerator; +import org.hibernate.MappingException; +import org.hibernate.dialect.Dialect; import org.hibernate.id.Assigned; +import org.hibernate.id.Configurable; +import org.hibernate.id.ForeignGenerator; +import org.hibernate.id.GUIDGenerator; +import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.IdentityGenerator; +import org.hibernate.id.IncrementGenerator; import org.hibernate.id.SelectGenerator; import org.hibernate.id.SequenceGenerator; import org.hibernate.id.SequenceHiLoGenerator; -import org.hibernate.id.IncrementGenerator; -import org.hibernate.id.ForeignGenerator; -import org.hibernate.id.GUIDGenerator; import org.hibernate.id.SequenceIdentityGenerator; -import org.hibernate.id.Configurable; +import org.hibernate.id.TableHiLoGenerator; +import org.hibernate.id.UUIDGenerator; +import org.hibernate.id.UUIDHexGenerator; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableGenerator; import org.hibernate.type.Type; import org.hibernate.util.ReflectHelper; -import org.hibernate.dialect.Dialect; -import org.hibernate.MappingException; +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. @@ -57,7 +58,9 @@ import org.hibernate.MappingException; * @author Steve Ebersole */ public class DefaultIdentifierGeneratorFactory implements IdentifierGeneratorFactory, Serializable { - private static final Logger log = LoggerFactory.getLogger( DefaultIdentifierGeneratorFactory.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DefaultIdentifierGeneratorFactory.class.getPackage().getName()); private transient Dialect dialect; private ConcurrentHashMap generatorStrategyToClassNameMap = new ConcurrentHashMap(); @@ -87,17 +90,15 @@ public class DefaultIdentifierGeneratorFactory implements IdentifierGeneratorFac * {@inheritDoc} */ public void setDialect(Dialect dialect) { - log.debug( "Setting dialect [" + dialect + "]" ); + LOG.settingDialect(dialect); this.dialect = dialect; } public void register(String strategy, Class generatorClass) { - String msg = "Registering IdentifierGenerator strategy [" + strategy + "] -> [" + generatorClass + "]"; Object old = generatorStrategyToClassNameMap.put( strategy, generatorClass ); - if ( old != null ) { - msg += ", overriding [" + old + "]"; - } - log.debug( msg ); + String msg = LOG.registeringIdentifierGeneratorStrategy(strategy, generatorClass); + if (old != null) msg += LOG.overriding(old); + LOG.debug(msg); } /** @@ -138,4 +139,22 @@ 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 824e18c41b..878560c060 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/AbstractScrollableResults.java @@ -24,6 +24,7 @@ */ package org.hibernate.impl; +import static org.jboss.logging.Logger.Level.TRACE; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; @@ -35,10 +36,6 @@ import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.MappingException; @@ -48,6 +45,10 @@ 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 @@ -56,7 +57,8 @@ import org.hibernate.type.Type; */ public abstract class AbstractScrollableResults implements ScrollableResults { - private static final Logger log = LoggerFactory.getLogger( AbstractScrollableResults.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractScrollableResults.class.getPackage().getName()); private final ResultSet resultSet; private final PreparedStatement ps; @@ -81,7 +83,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults { this.queryParameters = queryParameters; this.types = types; this.holderInstantiator = holderInstantiator!=null && holderInstantiator.isRequired() - ? holderInstantiator + ? holderInstantiator : null; } @@ -133,7 +135,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults { } catch( Throwable ignore ) { // ignore this error for now - log.trace( "exception trying to cleanup load context : " + ignore.getMessage() ); + LOG.unableToCleanupLoadContext(ignore.getMessage()); } } } @@ -158,7 +160,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults { if ( holderInstantiator!=null ) { throw new HibernateException("query specifies a holder class"); } - + if ( returnType.getReturnedClass()==types[col].getReturnedClass() ) { return get(col); } @@ -179,7 +181,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults { if ( holderInstantiator!=null ) { throw new HibernateException("query specifies a holder class"); } - + if ( returnType.getReturnedClass().isAssignableFrom( types[col].getReturnedClass() ) ) { return get(col); } @@ -276,15 +278,26 @@ public abstract class AbstractScrollableResults implements ScrollableResults { int i, Type type, Type returnType) throws HibernateException { - throw new HibernateException( - "incompatible column types: " + - type.getName() + - ", " + - returnType.getName() + throw new HibernateException( + "incompatible column types: " + + type.getName() + + ", " + + returnType.getName() ); } 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 b3f718077d..d5df0a6fbc 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/IteratorImpl.java @@ -24,13 +24,11 @@ */ package org.hibernate.impl; +import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.NoSuchElementException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.engine.HibernateIterator; @@ -38,6 +36,10 @@ 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 @@ -46,7 +48,8 @@ import org.hibernate.type.Type; */ public final class IteratorImpl implements HibernateIterator { - private static final Logger log = LoggerFactory.getLogger(IteratorImpl.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + IteratorImpl.class.getPackage().getName()); private ResultSet rs; private final EventSource session; @@ -104,22 +107,20 @@ public final class IteratorImpl implements HibernateIterator { } catch( Throwable ignore ) { // ignore this error for now - log.trace( "exception trying to cleanup load context : " + ignore.getMessage() ); + LOG.unableToCleanupLoadContext(ignore.getMessage()); } } } } private void postNext() throws SQLException { - log.debug("attempting to retrieve next results"); + LOG.retrievingNextResults(); this.hasNext = rs.next(); if (!hasNext) { - log.debug("exhausted results"); + LOG.exhaustedResults(); close(); } - else { - log.debug("retrieved next results"); - } + else LOG.retrievedNextResults(); } public boolean hasNext() { @@ -133,7 +134,7 @@ public final class IteratorImpl implements HibernateIterator { try { boolean isHolder = holderInstantiator.isRequired(); - log.debug("assembling results"); + LOG.assemblingResults(); if ( single && !isHolder ) { currentResult = types[0].nullSafeGet( rs, names[0], session, null ); } @@ -152,7 +153,7 @@ public final class IteratorImpl implements HibernateIterator { } postNext(); - log.debug("returning current results"); + LOG.returningCurrentResults(); return currentResult; } catch (SQLException sqle) { @@ -176,13 +177,50 @@ public final class IteratorImpl implements HibernateIterator { if ( !( types[0] instanceof EntityType ) ) { throw new UnsupportedOperationException("Not an entity"); } - - session.delete( - ( (EntityType) types[0] ).getAssociatedEntityName(), + + session.delete( + ( (EntityType) types[0] ).getAssociatedEntityName(), currentResult, false, 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 f1968aeb9d..ba6437be55 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/NonFlushedChangesImpl.java @@ -29,26 +29,28 @@ package org.hibernate.impl; * @author Gail Badner */ -import org.hibernate.engine.NonFlushedChanges; -import org.hibernate.engine.ActionQueue; -import org.hibernate.engine.StatefulPersistenceContext; -import org.hibernate.event.EventSource; +import static org.jboss.logging.Logger.Level.TRACE; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; - -import java.util.Map; -import java.util.HashMap; -import java.io.Serializable; -import java.io.ObjectInputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 { - private static final Logger log = LoggerFactory.getLogger(NonFlushedChangesImpl.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NonFlushedChangesImpl.class.getPackage().getName()); private static class SessionNonFlushedChanges implements Serializable { private transient EntityMode entityMode; @@ -69,7 +71,7 @@ public final class NonFlushedChangesImpl implements NonFlushedChanges { } private void writeObject(ObjectOutputStream oos) throws IOException { - log.trace( "serializing SessionNonFlushedChanges" ); + LOG.serializingSessionNonFlushedChanges(); oos.defaultWriteObject(); oos.writeObject( entityMode.toString() ); persistenceContext.serialize( oos ); @@ -96,7 +98,7 @@ public final class NonFlushedChangesImpl implements NonFlushedChanges { /* package-protected */ ActionQueue getActionQueue(EntityMode entityMode) { return getSessionNonFlushedChanges( entityMode ).actionQueue; - } + } /* package-protected */ StatefulPersistenceContext getPersistenceContext(EntityMode entityMode) { @@ -106,4 +108,15 @@ 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 ec43d984ef..6e0cc6490a 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryImpl.java @@ -23,6 +23,10 @@ */ 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; @@ -43,10 +47,6 @@ import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.transaction.TransactionManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.Cache; import org.hibernate.ConnectionReleaseMode; @@ -126,6 +126,10 @@ 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; /** @@ -153,7 +157,8 @@ import org.hibernate.util.ReflectHelper; */ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryImplementor { - private static final Logger log = LoggerFactory.getLogger(SessionFactoryImpl.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SessionFactoryImpl.class.getPackage().getName()); private static final IdentifierGenerator UUID_GENERATOR = UUIDGenerator.buildSessionFactoryUniqueIdentifierGenerator(); private final String name; @@ -201,11 +206,11 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI Settings settings, EventListeners listeners, SessionFactoryObserver observer) throws HibernateException { - log.info("building session factory"); + LOG.buildingSessionFactory(); this.statistics = new ConcurrentStatisticsImpl( this ); getStatistics().setStatisticsEnabled( settings.isStatisticsEnabled() ); - log.debug( "Statistics initialized [enabled={}]}", settings.isStatisticsEnabled() ); + LOG.statisticsInitialized(settings.isStatisticsEnabled()); this.properties = new Properties(); this.properties.putAll( cfg.getProperties() ); @@ -227,15 +232,8 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI this.filters = new HashMap(); this.filters.putAll( cfg.getFilterDefinitions() ); - if ( log.isDebugEnabled() ) { - log.debug("Session factory constructed with filter configurations : " + filters); - } - - if ( log.isDebugEnabled() ) { - log.debug( - "instantiating session factory with properties: " + properties - ); - } + LOG.sessionFactoryConstructedWithFilterConfigurations(filters); + LOG.instantiatingSessionFactory(properties); // Caches settings.getRegionFactory().start( settings, properties ); @@ -279,7 +277,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI if ( accessStrategy == null && settings.isSecondLevelCacheEnabled() ) { final AccessType accessType = AccessType.parse( model.getCacheConcurrencyStrategy() ); if ( accessType != null ) { - log.trace( "Building cache for entity data [" + model.getEntityName() + "]" ); + LOG.buildingCacheForEntityData(model.getEntityName()); EntityRegion entityRegion = settings.getRegionFactory().buildEntityRegion( cacheRegionName, properties, CacheDataDescriptionImpl.decode( model ) ); accessStrategy = entityRegion.buildAccessStrategy( accessType ); entityAccessStrategies.put( cacheRegionName, accessStrategy ); @@ -301,7 +299,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI final AccessType accessType = AccessType.parse( model.getCacheConcurrencyStrategy() ); CollectionRegionAccessStrategy accessStrategy = null; if ( accessType != null && settings.isSecondLevelCacheEnabled() ) { - log.trace( "Building cache for collection data [" + model.getRole() + "]" ); + LOG.buildingCacheForCollectionData(model.getRole()); CollectionRegion collectionRegion = settings.getRegionFactory().buildCollectionRegion( cacheRegionName, properties, CacheDataDescriptionImpl.decode( model ) ); accessStrategy = collectionRegion.buildAccessStrategy( accessType ); entityAccessStrategies.put( cacheRegionName, accessStrategy ); @@ -312,7 +310,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI Type indexType = persister.getIndexType(); if ( indexType != null && indexType.isAssociationType() && !indexType.isAnyType() ) { String entityName = ( ( AssociationType ) indexType ).getAssociatedEntityName( this ); - Set roles = ( Set ) tmpEntityToCollectionRoleMap.get( entityName ); + Set roles = tmpEntityToCollectionRoleMap.get( entityName ); if ( roles == null ) { roles = new HashSet(); tmpEntityToCollectionRoleMap.put( entityName, roles ); @@ -322,7 +320,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI Type elementType = persister.getElementType(); if ( elementType.isAssociationType() && !elementType.isAnyType() ) { String entityName = ( ( AssociationType ) elementType ).getAssociatedEntityName( this ); - Set roles = ( Set ) tmpEntityToCollectionRoleMap.get( entityName ); + Set roles = tmpEntityToCollectionRoleMap.get( entityName ); if ( roles == null ) { roles = new HashSet(); tmpEntityToCollectionRoleMap.put( entityName, roles ); @@ -369,7 +367,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } SessionFactoryObjectFactory.addInstance(uuid, name, this, properties); - log.debug("instantiated session factory"); + LOG.instantiatedSessionFactory(); if ( settings.isAutoCreateSchema() ) { new SchemaExport( getJdbcServices(), cfg ).create( false, true ); @@ -385,7 +383,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } if ( settings.getTransactionManagerLookup()!=null ) { - log.debug("obtaining JTA TransactionManager"); + LOG.obtainingJtaTransactionManager(); transactionManager = settings.getTransactionManagerLookup().getTransactionManager(properties); } else { @@ -421,10 +419,8 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI String queryName = ( String ) iterator.next(); HibernateException e = ( HibernateException ) errors.get( queryName ); failingQueries.append( queryName ); - if ( iterator.hasNext() ) { - failingQueries.append( ", " ); - } - log.error( "Error in named query: " + queryName, e ); + if (iterator.hasNext()) failingQueries.append(", "); + LOG.error(LOG.namedQueryError(queryName), e); } throw new HibernateException( failingQueries.toString() ); } @@ -539,7 +535,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI Map errors = new HashMap(); // Check named HQL queries - log.debug("Checking " + namedQueries.size() + " named HQL queries"); + LOG.checkingNamedHqlQueries(namedQueries.size()); Iterator itr = namedQueries.entrySet().iterator(); while ( itr.hasNext() ) { final Map.Entry entry = ( Map.Entry ) itr.next(); @@ -547,7 +543,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.debug("Checking named query: " + queryName); + LOG.checkingNamedQuery(queryName); //TODO: BUG! this currently fails for named queries for non-POJO entities queryPlanCache.getHQLQueryPlan( qd.getQueryString(), false, CollectionHelper.EMPTY_MAP ); } @@ -559,7 +555,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } } - log.debug("Checking " + namedSqlQueries.size() + " named SQL queries"); + LOG.checkingNamedSqlQueries(namedSqlQueries.size()); itr = namedSqlQueries.entrySet().iterator(); while ( itr.hasNext() ) { final Map.Entry entry = ( Map.Entry ) itr.next(); @@ -567,7 +563,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.debug("Checking named SQL query: " + queryName); + LOG.checkingNamedSqlQuery(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; @@ -748,7 +744,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI // from javax.naming.Referenceable public Reference getReference() throws NamingException { - log.debug("Returning a Reference to the SessionFactory"); + LOG.returningReferenceToSessionFactory(); return new Reference( SessionFactoryImpl.class.getName(), new StringRefAddr("uuid", uuid), @@ -758,23 +754,16 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } private Object readResolve() throws ObjectStreamException { - log.trace("Resolving serialized SessionFactory"); + LOG.resolvingSerializedSessionFactory(); // look for the instance by uuid Object result = SessionFactoryObjectFactory.getInstance(uuid); if (result==null) { // in case we were deserialized in a different JVM, look for an instance with the same name // (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); - } - else { - log.debug("resolved SessionFactory by name"); - } - } - else { - log.debug("resolved SessionFactory by uid"); - } + if (result == null) throw new InvalidObjectException("Could not find a SessionFactory named: " + name); + LOG.resolvedSessionFactoryByName(); + } else LOG.resolvedSessionFactoryByUid(); return result; } @@ -798,15 +787,15 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - log.trace("deserializing"); + LOG.deserializing(); in.defaultReadObject(); - log.debug("deserialized: " + uuid); + LOG.deserialized(uuid); } private void writeObject(ObjectOutputStream out) throws IOException { - log.debug("serializing: " + uuid); + LOG.serializing(uuid); out.defaultWriteObject(); - log.trace("serialized"); + LOG.serialized(); } public Type[] getReturnTypes(String queryString) throws HibernateException { @@ -826,7 +815,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } public ClassMetadata getClassMetadata(String entityName) throws HibernateException { - return (ClassMetadata) classMetadata.get(entityName); + return classMetadata.get(entityName); } /** @@ -934,11 +923,11 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void close() throws HibernateException { if ( isClosed ) { - log.trace( "already closed" ); + LOG.alreadyClosed(); return; } - log.info("closing"); + LOG.closing(); isClosed = true; @@ -999,12 +988,9 @@ 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.debug( - "evicting second-level cache: " + - MessageHelper.infoString( p, identifier, SessionFactoryImpl.this ) - ); - } + if (LOG.isDebugEnabled()) LOG.evictingSecondLevelCache(MessageHelper.infoString(p, + identifier, + SessionFactoryImpl.this)); p.getCacheAccessStrategy().evict( buildCacheKey( identifier, p ) ); } } @@ -1026,9 +1012,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictEntityRegion(String entityName) { EntityPersister p = getEntityPersister( entityName ); if ( p.hasCache() ) { - if ( log.isDebugEnabled() ) { - log.debug( "evicting second-level cache: " + p.getEntityName() ); - } + LOG.evictingSecondLevelCache(p.getEntityName()); p.getCacheAccessStrategy().evictAll(); } } @@ -1049,12 +1033,9 @@ 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.debug( - "evicting second-level cache: " + - MessageHelper.collectionInfoString(p, ownerIdentifier, SessionFactoryImpl.this) - ); - } + if (LOG.isDebugEnabled()) LOG.evictingSecondLevelCache(MessageHelper.collectionInfoString(p, + ownerIdentifier, + SessionFactoryImpl.this)); CacheKey cacheKey = buildCacheKey( ownerIdentifier, p ); p.getCacheAccessStrategy().evict( cacheKey ); } @@ -1073,9 +1054,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI public void evictCollectionRegion(String role) { CollectionPersister p = getCollectionPersister( role ); if ( p.hasCache() ) { - if ( log.isDebugEnabled() ) { - log.debug( "evicting second-level cache: " + p.getRole() ); - } + LOG.evictingSecondLevelCache(p.getRole()); p.getCacheAccessStrategy().evictAll(); } } @@ -1098,20 +1077,13 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } public void evictQueryRegion(String regionName) { - if ( regionName == null ) { - throw new NullPointerException( - "Region-name cannot be null (use Cache#evictDefaultQueryRegion to evict the default query cache)" - ); - } - else { - synchronized ( allCacheRegions ) { - if ( settings.isQueryCacheEnabled() ) { - QueryCache namedQueryCache = ( QueryCache ) queryCaches.get( regionName ); - if ( namedQueryCache != null ) { - namedQueryCache.clear(); - // TODO : cleanup entries in queryCaches + allCacheRegions ? - } - } + if (regionName == null) throw new NullPointerException( + "Region-name cannot be null (use Cache#evictDefaultQueryRegion to evict the default query cache)"); + synchronized (allCacheRegions) { + if (settings.isQueryCacheEnabled()) { + QueryCache namedQueryCache = (QueryCache)queryCaches.get(regionName); + // TODO : cleanup entries in queryCaches + allCacheRegions ? + if (namedQueryCache != null) namedQueryCache.clear(); } } } @@ -1249,9 +1221,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI return null; } else if ( "jta".equals( impl ) ) { - if ( settings.getTransactionFactory().areCallbacksLocalToHibernateTransactions() ) { - log.warn( "JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()" ); - } + if (settings.getTransactionFactory().areCallbacksLocalToHibernateTransactions()) LOG.autoFlushWillNotWork(); return new JTASessionContext( this ); } else if ( "thread".equals( impl ) ) { @@ -1268,7 +1238,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI .newInstance( new Object[] { this } ); } catch( Throwable t ) { - log.error( "Unable to construct current session context [" + impl + "]", t ); + LOG.error(LOG.unableToConstructCurrentSessionContext(impl), t); return null; } } @@ -1326,7 +1296,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI } Object result = SessionFactoryObjectFactory.getInstance( uuid ); if ( result == null ) { - log.trace( "could not locate session factory by uuid [" + uuid + "] during session deserialization; trying name" ); + LOG.unableToLocateSessionFactoryByUuid(uuid); if ( isNamed ) { result = SessionFactoryObjectFactory.getNamedInstance( name ); } @@ -1336,4 +1306,117 @@ 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 4623b35c66..9f86c17539 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionFactoryObjectFactory.java @@ -23,6 +23,9 @@ */ 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; @@ -38,12 +41,12 @@ import javax.naming.event.NamingEvent; import javax.naming.event.NamingExceptionEvent; import javax.naming.event.NamingListener; import javax.naming.spi.ObjectFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 @@ -53,12 +56,12 @@ public class SessionFactoryObjectFactory implements ObjectFactory { @SuppressWarnings({ "UnusedDeclaration" }) private static final SessionFactoryObjectFactory INSTANCE; //to stop the class from being unloaded - private static final Logger log; + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SessionFactoryObjectFactory.class.getPackage().getName()); static { - log = LoggerFactory.getLogger( SessionFactoryObjectFactory.class ); INSTANCE = new SessionFactoryObjectFactory(); - log.debug("initializing class SessionFactoryObjectFactory"); + LOG.initializingSessionFactoryObjectFactory(); } private static final ConcurrentHashMap INSTANCES = new ConcurrentHashMap(); @@ -66,11 +69,11 @@ public class SessionFactoryObjectFactory implements ObjectFactory { private static final NamingListener LISTENER = new NamespaceChangeListener() { public void objectAdded(NamingEvent evt) { - log.debug( "A factory was successfully bound to name: " + evt.getNewBinding().getName() ); + LOG.factoryBoundToName(evt.getNewBinding().getName()); } public void objectRemoved(NamingEvent evt) { String name = evt.getOldBinding().getName(); - log.info("A factory was unbound from name: " + name); + LOG.factoryUnboundFromName(name); Object instance = NAMED_INSTANCES.remove(name); Iterator iter = INSTANCES.values().iterator(); while ( iter.hasNext() ) { @@ -79,49 +82,47 @@ public class SessionFactoryObjectFactory implements ObjectFactory { } public void objectRenamed(NamingEvent evt) { String name = evt.getOldBinding().getName(); - log.info("A factory was renamed from name: " + name); + LOG.factoryRenamedFromName(name); NAMED_INSTANCES.put( evt.getNewBinding().getName(), NAMED_INSTANCES.remove(name) ); } public void namingExceptionThrown(NamingExceptionEvent evt) { //noinspection ThrowableResultOfMethodCallIgnored - log.warn( "Naming exception occurred accessing factory: " + evt.getException() ); + LOG.namingExceptionAccessingFactory(evt.getException()); } }; public Object getObjectInstance(Object reference, Name name, Context ctx, Hashtable env) throws Exception { - log.debug("JNDI lookup: " + name); + LOG.jndiLookup(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.debug("registered: " + uid + " (" + ( (name==null) ? "unnamed" : name ) + ')'); + LOG.registered(uid, name == null ? LOG.unnamed() : 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.info("Not binding factory to JNDI, no JNDI name configured"); - } + if (name == null) LOG.notBindingFactoryToJndi(); else { - log.info("Factory name: " + name); + LOG.factoryName(name); try { Context ctx = JndiHelper.getInitialContext(properties); JndiHelper.bind(ctx, name, instance); - log.info("Bound factory to JNDI name: " + name); + LOG.factoryBoundToJndiName(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 factory to JNDI", ne); + LOG.warn(LOG.unableToBindFactoryToJndi(), ne); } catch(ClassCastException cce) { - log.warn("InitialContext did not implement EventContext"); + LOG.initialContextDidNotImplementEventContext(); } } @@ -132,18 +133,18 @@ public class SessionFactoryObjectFactory implements ObjectFactory { //TODO: theoretically non-threadsafe... if (name!=null) { - log.info("Unbinding factory from JNDI name: " + name); + LOG.unbindingFactoryFromJndiName(name); try { Context ctx = JndiHelper.getInitialContext(properties); ctx.unbind(name); - log.info("Unbound factory from JNDI name: " + name); + LOG.factoryUnboundFromJndiName(name); } catch (InvalidNameException ine) { - log.error("Invalid JNDI name: " + name, ine); + LOG.error(LOG.invalidJndiName(name), ine); } catch (NamingException ne) { - log.warn("Could not unbind factory from JNDI", ne); + LOG.warn(LOG.unableToUnbindFactoryFromJndi(), ne); } NAMED_INSTANCES.remove(name); @@ -155,25 +156,108 @@ public class SessionFactoryObjectFactory implements ObjectFactory { } public static Object getNamedInstance(String name) { - log.debug("lookup: name=" + name); + LOG.lookupName(name); Object result = NAMED_INSTANCES.get(name); if (result==null) { - log.debug("Not found: " + name); - log.debug( NAMED_INSTANCES.toString() ); + LOG.notFound(name); + LOG.debug(NAMED_INSTANCES.toString()); } return result; } public static Object getInstance(String uid) { - log.debug("lookup: uid=" + uid); + LOG.lookupUid(uid); Object result = INSTANCES.get(uid); if (result==null) { - log.debug("Not found: " + uid); - log.debug( INSTANCES.toString() ); + LOG.notFound(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(); + } } 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 25b99c52b2..ec41fb2db7 100644 --- a/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/SessionImpl.java @@ -24,14 +24,17 @@ */ 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; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.Serializable; -import java.io.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; @@ -44,20 +47,18 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.CacheMode; import org.hibernate.ConnectionReleaseMode; import org.hibernate.Criteria; import org.hibernate.EntityMode; +import org.hibernate.EntityNameResolver; import org.hibernate.Filter; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.LobHelper; import org.hibernate.LockMode; +import org.hibernate.LockOptions; import org.hibernate.MappingException; import org.hibernate.ObjectDeletedException; import org.hibernate.Query; @@ -72,21 +73,19 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.TransientObjectException; import org.hibernate.TypeHelper; -import org.hibernate.UnresolvableObjectException; import org.hibernate.UnknownProfileException; -import org.hibernate.EntityNameResolver; -import org.hibernate.LockOptions; +import org.hibernate.UnresolvableObjectException; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.ActionQueue; import org.hibernate.engine.CollectionEntry; import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityKey; +import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.NonFlushedChanges; import org.hibernate.engine.PersistenceContext; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.StatefulPersistenceContext; import org.hibernate.engine.Status; -import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.jdbc.LobCreationContext; import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.internal.JDBCContextImpl; @@ -136,11 +135,15 @@ import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import org.hibernate.stat.SessionStatistics; import org.hibernate.stat.SessionStatisticsImpl; -import org.hibernate.type.Type; import org.hibernate.type.SerializationException; +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; /** @@ -151,18 +154,19 @@ import org.hibernate.util.StringHelper; * * @author Gavin King */ -public final class SessionImpl extends AbstractSessionImpl +public final class SessionImpl extends AbstractSessionImpl implements EventSource, org.hibernate.classic.Session, JDBCContext.Context, LobCreationContext { // todo : need to find a clean way to handle the "event source" role // a seperate classs responsible for generating/dispatching events just duplicates most of the Session methods... // passing around seperate reto interceptor, factory, actionQueue, and persistentContext is not manageable... - private static final Logger log = LoggerFactory.getLogger(SessionImpl.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SessionImpl.class.getPackage().getName()); private transient EntityMode entityMode = EntityMode.POJO; private transient boolean autoClear; //for EJB3 - + private transient long timestamp; private transient FlushMode flushMode = FlushMode.AUTO; private transient CacheMode cacheMode = CacheMode.NORMAL; @@ -209,11 +213,9 @@ public final class SessionImpl extends AbstractSessionImpl loadQueryInfluencers = new LoadQueryInfluencers( factory ); - if ( factory.getStatistics().isStatisticsEnabled() ) { - factory.getStatisticsImplementor().openSession(); - } + if (factory.getStatistics().isStatisticsEnabled()) factory.getStatisticsImplementor().openSession(); - log.debug( "opened session [" + entityMode + "]" ); + LOG.openedSession(entityMode); } /** @@ -255,13 +257,9 @@ public final class SessionImpl extends AbstractSessionImpl loadQueryInfluencers = new LoadQueryInfluencers( factory ); - if ( factory.getStatistics().isStatisticsEnabled() ) { - factory.getStatisticsImplementor().openSession(); - } + if (factory.getStatistics().isStatisticsEnabled()) factory.getStatisticsImplementor().openSession(); - if ( log.isDebugEnabled() ) { - log.debug( "opened session at timestamp: " + timestamp ); - } + LOG.openedSessionAt(timestamp); } public Session getSession(EntityMode entityMode) { @@ -305,11 +303,11 @@ public final class SessionImpl extends AbstractSessionImpl } public Connection close() throws HibernateException { - log.trace( "closing session" ); + LOG.closingSession(); if ( isClosed() ) { throw new SessionException( "Session was already closed" ); } - + if ( factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor().closeSession(); @@ -366,12 +364,12 @@ public final class SessionImpl extends AbstractSessionImpl public void managedFlush() { if ( isClosed() ) { - log.trace( "skipping auto-flush due to session closed" ); + LOG.skippingAutoFlush(); return; } - log.trace("automatically flushing session"); + LOG.automaticallyFlushingSession(); flush(); - + if ( childSessionsByEntityMode != null ) { Iterator iter = childSessionsByEntityMode.values().iterator(); while ( iter.hasNext() ) { @@ -447,7 +445,7 @@ public final class SessionImpl extends AbstractSessionImpl ObjectOutputStream oos = null; try { oos = new ObjectOutputStream( baos ); - ( ( StatefulPersistenceContext ) pc ).serialize( oos ); + ( pc ).serialize( oos ); } catch (IOException ex) { throw new SerializationException( "could not serialize persistence context", ex ); @@ -517,7 +515,7 @@ public final class SessionImpl extends AbstractSessionImpl } public void managedClose() { - log.trace( "automatically closing session" ); + LOG.automaticallyClosingSession(); close(); } @@ -530,7 +528,7 @@ public final class SessionImpl extends AbstractSessionImpl checkTransactionSynchStatus(); return !isClosed() && jdbcContext.getConnectionManager().isCurrentlyConnected(); } - + public boolean isTransactionInProgress() { checkTransactionSynchStatus(); return !isClosed() && jdbcContext.isTransactionInProgress(); @@ -538,46 +536,46 @@ public final class SessionImpl extends AbstractSessionImpl public Connection disconnect() throws HibernateException { errorIfClosed(); - log.debug( "disconnecting session" ); + LOG.disconnectingSession(); return jdbcContext.getConnectionManager().manualDisconnect(); } public void reconnect() throws HibernateException { errorIfClosed(); - log.debug( "reconnecting session" ); + LOG.reconnectingSession(); checkTransactionSynchStatus(); jdbcContext.getConnectionManager().manualReconnect(); } public void reconnect(Connection conn) throws HibernateException { errorIfClosed(); - log.debug( "reconnecting session" ); + LOG.reconnectingSession(); checkTransactionSynchStatus(); jdbcContext.getConnectionManager().manualReconnect( conn ); } public void beforeTransactionCompletion(Transaction tx) { - log.trace( "before transaction completion" ); + LOG.beforeTransactionCompletion(); actionQueue.beforeTransactionCompletion(); if ( rootSession == null ) { try { interceptor.beforeTransactionCompletion(tx); } catch (Throwable t) { - log.error("exception in interceptor beforeTransactionCompletion()", t); + LOG.error(LOG.exceptionInBeforeTransactionCompletionInterceptor(), t); } } } - + public void setAutoClear(boolean enabled) { errorIfClosed(); autoClear = enabled; } - + /** - * Check if there is a Hibernate or JTA transaction in progress and, - * if there is not, flush if necessary, make sure the connection has - * been committed (if it is not in autocommit mode) and run the after + * Check if there is a Hibernate or JTA transaction in progress and, + * if there is not, flush if necessary, make sure the connection has + * been committed (if it is not in autocommit mode) and run the after * completion processing */ public void afterOperation(boolean success) { @@ -587,7 +585,7 @@ public final class SessionImpl extends AbstractSessionImpl } public void afterTransactionCompletion(boolean success, Transaction tx) { - log.trace( "after transaction completion" ); + LOG.afterTransactionCompletion(); persistenceContext.afterTransactionCompletion(); actionQueue.afterTransactionCompletion(success); if ( rootSession == null && tx != null ) { @@ -595,7 +593,7 @@ public final class SessionImpl extends AbstractSessionImpl interceptor.afterTransactionCompletion(tx); } catch (Throwable t) { - log.error("exception in interceptor afterTransactionCompletion()", t); + LOG.error(LOG.exceptionInAfterTransactionCompletionInterceptor(), t); } } if ( autoClear ) { @@ -604,7 +602,7 @@ public final class SessionImpl extends AbstractSessionImpl } /** - * clear all the internal collections, just + * clear all the internal collections, just * to help the garbage collector, does not * clear anything that is needed during the * afterTransactionCompletion() phase @@ -630,10 +628,10 @@ public final class SessionImpl extends AbstractSessionImpl throw new TransientObjectException( "Given object not associated with the session" ); } if ( e.getStatus() != Status.MANAGED ) { - throw new ObjectDeletedException( - "The given object was deleted", - e.getId(), - e.getPersister().getEntityName() + throw new ObjectDeletedException( + "The given object was deleted", + e.getId(), + e.getPersister().getEntityName() ); } return e.getLockMode(); @@ -1007,11 +1005,11 @@ public final class SessionImpl extends AbstractSessionImpl * Do NOT return a proxy. */ public Object immediateLoad(String entityName, Serializable id) throws HibernateException { - if ( log.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { EntityPersister persister = getFactory().getEntityPersister(entityName); - log.debug( "initializing proxy: " + MessageHelper.infoString( persister, id, getFactory() ) ); + LOG.initializingProxy(MessageHelper.infoString(persister, id, getFactory())); } - + LoadEvent event = new LoadEvent(id, entityName, true, this); fireLoad(event, LoadEventListener.IMMEDIATE_LOAD); return event.getResult(); @@ -1071,7 +1069,7 @@ public final class SessionImpl extends AbstractSessionImpl fireLoad(event, LoadEventListener.GET); return event.getResult(); } - + private void fireLoad(LoadEvent event, LoadType loadType) { errorIfClosed(); checkTransactionSynchStatus(); @@ -1180,9 +1178,9 @@ public final class SessionImpl extends AbstractSessionImpl public boolean isDirty() throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); - log.debug("checking session dirtiness"); + LOG.checkingSessionDirtiness(); if ( actionQueue.areInsertionsOrDeletionsQueued() ) { - log.debug("session dirty (scheduled updates and insertions)"); + LOG.sessionDirty(); return true; } else { @@ -1209,12 +1207,9 @@ public final class SessionImpl extends AbstractSessionImpl public void forceFlush(EntityEntry entityEntry) throws HibernateException { errorIfClosed(); - if ( log.isDebugEnabled() ) { - log.debug( - "flushing to force deletion of re-saved object: " + - MessageHelper.infoString( entityEntry.getPersister(), entityEntry.getId(), getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.flushingToForceDeletion(MessageHelper.infoString(entityEntry.getPersister(), + entityEntry.getId(), + getFactory())); if ( persistenceContext.getCascadeLevel() > 0 ) { throw new ObjectDeletedException( @@ -1291,9 +1286,9 @@ public final class SessionImpl extends AbstractSessionImpl queryParameters.validateParameters(); NativeSQLQueryPlan plan = getNativeSQLQueryPlan(nativeQuerySpecification); - + autoFlushIfRequired( plan.getCustomQuery().getQuerySpaces() ); - + boolean success = false; int result = 0; try { @@ -1362,11 +1357,9 @@ public final class SessionImpl extends AbstractSessionImpl throw new IllegalArgumentException("attempt to doAfterTransactionCompletion delete-by-query with null query"); } - if ( log.isTraceEnabled() ) { - log.trace( "delete: " + query ); - if ( values.length != 0 ) { - log.trace( "parameters: " + StringHelper.toString( values ) ); - } + if (LOG.isTraceEnabled()) { + LOG.delete(query); + if (values.length != 0) LOG.parameters(StringHelper.toString(values)); } List list = find( query, values, types ); @@ -1390,7 +1383,7 @@ public final class SessionImpl extends AbstractSessionImpl filter.setComment( queryString ); return filter; } - + public Query getNamedQuery(String queryName) throws MappingException { errorIfClosed(); checkTransactionSynchStatus(); @@ -1422,12 +1415,10 @@ public final class SessionImpl extends AbstractSessionImpl public void setFlushMode(FlushMode flushMode) { errorIfClosed(); checkTransactionSynchStatus(); - if ( log.isTraceEnabled() ) { - log.trace("setting flush mode to: " + flushMode); - } + LOG.settingFlushMode(flushMode); this.flushMode = flushMode; } - + public FlushMode getFlushMode() { checkTransactionSynchStatus(); return flushMode; @@ -1437,33 +1428,30 @@ public final class SessionImpl extends AbstractSessionImpl checkTransactionSynchStatus(); return cacheMode; } - + public void setCacheMode(CacheMode cacheMode) { errorIfClosed(); checkTransactionSynchStatus(); - if ( log.isTraceEnabled() ) { - log.trace("setting cache mode to: " + cacheMode); - } - this.cacheMode= cacheMode; + LOG.settingCacheMode(cacheMode); + this.cacheMode= cacheMode; } public Transaction getTransaction() throws HibernateException { errorIfClosed(); return jdbcContext.getTransaction(); } - + public Transaction beginTransaction() throws HibernateException { errorIfClosed(); - if ( rootSession != null ) { - // todo : should seriously consider not allowing a txn to begin from a child session - // can always route the request to the root session... - log.warn( "Transaction started on non-root session" ); - } + // todo : should seriously consider not allowing a txn to begin from a child session + // can always route the request to the root session... + if (rootSession != null) LOG.transactionStartedOnNonRootSession(); + Transaction result = getTransaction(); result.begin(); return result; } - + public void afterTransactionBegin(Transaction tx) { errorIfClosed(); interceptor.afterTransactionBegin(tx); @@ -1529,7 +1517,7 @@ public final class SessionImpl extends AbstractSessionImpl return entry != null ? entry.getId() : null; } } - + private Serializable getProxyIdentifier(Object proxy) { return ( (HibernateProxy) proxy ).getHibernateLazyInitializer().getIdentifier(); } @@ -1741,7 +1729,7 @@ public final class SessionImpl extends AbstractSessionImpl } else { //if it is initialized, see if the underlying - //instance is contained, since we need to + //instance is contained, since we need to //account for the fact that it might have been //evicted object = li.getImplementation(); @@ -1753,13 +1741,13 @@ public final class SessionImpl extends AbstractSessionImpl EntityEntry entry = persistenceContext.getEntry( object ); return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE; } - + public Query createQuery(String queryString) { errorIfClosed(); checkTransactionSynchStatus(); return super.createQuery(queryString); } - + public SQLQuery createSQLQuery(String sql) { errorIfClosed(); checkTransactionSynchStatus(); @@ -1795,9 +1783,7 @@ public final class SessionImpl extends AbstractSessionImpl errorIfClosed(); checkTransactionSynchStatus(); - if ( log.isTraceEnabled() ) { - log.trace( "scroll SQL query: " + customQuery.getSQL() ); - } + LOG.scrollSqlQuery(customQuery.getSQL()); CustomLoader loader = new CustomLoader( customQuery, getFactory() ); @@ -1813,15 +1799,13 @@ public final class SessionImpl extends AbstractSessionImpl } // basically just an adapted copy of find(CriteriaImpl) - public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) + public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); - if ( log.isTraceEnabled() ) { - log.trace( "SQL query: " + customQuery.getSQL() ); - } - + LOG.sqlQuery(customQuery.getSQL()); + CustomLoader loader = new CustomLoader( customQuery, getFactory() ); autoFlushIfRequired( loader.getQuerySpaces() ); @@ -1843,7 +1827,7 @@ public final class SessionImpl extends AbstractSessionImpl checkTransactionSynchStatus(); return factory; } - + public void initializeCollection(PersistentCollection collection, boolean writing) throws HibernateException { errorIfClosed(); @@ -1872,7 +1856,7 @@ public final class SessionImpl extends AbstractSessionImpl return entry.getPersister().getEntityName(); } } - + public String getEntityName(Object object) { errorIfClosed(); checkTransactionSynchStatus(); @@ -1939,13 +1923,13 @@ public final class SessionImpl extends AbstractSessionImpl checkTransactionSynchStatus(); return actionQueue; } - + public PersistenceContext getPersistenceContext() { errorIfClosed(); checkTransactionSynchStatus(); return persistenceContext; } - + public SessionStatistics getStatistics() { checkTransactionSynchStatus(); return new SessionStatisticsImpl(this); @@ -1973,7 +1957,7 @@ public final class SessionImpl extends AbstractSessionImpl public boolean isReadOnly(Object entityOrProxy) { errorIfClosed(); checkTransactionSynchStatus(); - return persistenceContext.isReadOnly( entityOrProxy ); + return persistenceContext.isReadOnly( entityOrProxy ); } public void setReadOnly(Object entity, boolean readOnly) { @@ -2111,7 +2095,7 @@ public final class SessionImpl extends AbstractSessionImpl * @throws ClassNotFoundException Indicates a class resolution issue */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { - log.trace( "deserializing session" ); + LOG.deserializingSession(); ois.defaultReadObject(); @@ -2172,7 +2156,7 @@ public final class SessionImpl extends AbstractSessionImpl throw new IllegalStateException( "Cannot serialize a session while connected" ); } - log.trace( "serializing session" ); + LOG.serializingSession(); oos.defaultWriteObject(); @@ -2358,4 +2342,109 @@ 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 c18b38f2fd..cb70a1c202 100755 --- a/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java @@ -21,6 +21,7 @@ */ package org.hibernate.impl; +import static org.jboss.logging.Logger.Level.TRACE; import java.io.Serializable; import java.sql.Connection; import java.util.Collections; @@ -28,9 +29,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.CacheMode; import org.hibernate.ConnectionReleaseMode; import org.hibernate.Criteria; @@ -50,12 +48,12 @@ import org.hibernate.UnresolvableObjectException; import org.hibernate.cache.CacheKey; import org.hibernate.collection.PersistentCollection; import org.hibernate.engine.EntityKey; +import org.hibernate.engine.LoadQueryInfluencers; +import org.hibernate.engine.NonFlushedChanges; import org.hibernate.engine.PersistenceContext; import org.hibernate.engine.QueryParameters; import org.hibernate.engine.StatefulPersistenceContext; import org.hibernate.engine.Versioning; -import org.hibernate.engine.LoadQueryInfluencers; -import org.hibernate.engine.NonFlushedChanges; import org.hibernate.engine.jdbc.internal.JDBCContextImpl; import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.engine.query.HQLQueryPlan; @@ -72,6 +70,10 @@ 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 @@ -79,7 +81,8 @@ import org.hibernate.util.CollectionHelper; public class StatelessSessionImpl extends AbstractSessionImpl implements JDBCContext.Context, StatelessSession { - private static final Logger log = LoggerFactory.getLogger( StatelessSessionImpl.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StatelessSessionImpl.class.getPackage().getName()); private JDBCContextImpl jdbcContext; private PersistenceContext temporaryPersistenceContext = new StatefulPersistenceContext( this ); @@ -200,12 +203,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.trace( - "refreshing transient " + - MessageHelper.infoString( persister, id, this.getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.refreshingTransient(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 ) { @@ -673,7 +671,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl // no auto-flushing to support in stateless session return false; } - + public int executeNativeUpdate(NativeSQLQuerySpecification nativeSQLQuerySpecification, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); @@ -692,4 +690,14 @@ public class StatelessSessionImpl extends AbstractSessionImpl 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 e39cd086eb..87b906e618 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,15 +23,16 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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} @@ -39,7 +40,9 @@ import org.hibernate.util.ArrayHelper; * @author Steve Ebersole */ public class TypeInfoExtracter { - private static final Logger log = LoggerFactory.getLogger( TypeInfoExtracter.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TypeInfoExtracter.class.getPackage().getName()); private TypeInfoExtracter() { } @@ -77,19 +80,19 @@ public class TypeInfoExtracter { } } catch ( SQLException e ) { - log.warn( "Error accessing type info result set : " + e.toString() ); + LOG.unableToAccessTypeInfoResultSet(e.toString()); } finally { try { resultSet.close(); } catch ( SQLException e ) { - log.warn( "Unable to release type info result set" ); + LOG.unableToReleaseTypeInfoResultSet(); } } } catch ( SQLException e ) { - log.warn( "Unable to retrieve type info result set : " + e.toString() ); + LOG.unableToRetrieveTypeInfoResultSet(e.toString()); } return typeInfoSet; @@ -101,4 +104,23 @@ 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 e6ccd512f8..6e53655400 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,6 +23,9 @@ */ 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; @@ -32,14 +35,16 @@ import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NamingException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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 { - private static final Logger log = LoggerFactory.getLogger( JndiHelper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JndiHelper.class.getPackage().getName()); private JndiHelper() { } @@ -113,7 +118,7 @@ public final class JndiHelper { */ public static void bind(String jndiName, Object value, Context context) { try { - log.trace( "binding : " + jndiName ); + LOG.binding(jndiName); context.rebind( jndiName, value ); } catch ( Exception initialException ) { @@ -126,7 +131,7 @@ public final class JndiHelper { Context intermediateContext = null; try { - log.trace( "intermediate lookup: " + intermediateContextName ); + LOG.intermediateLookup(intermediateContextName); intermediateContext = (Context) intermediateContextBase.lookup( intermediateContextName ); } catch ( NameNotFoundException handledBelow ) { @@ -136,11 +141,9 @@ public final class JndiHelper { throw new JndiException( "Unaniticipated error doing intermediate lookup", e ); } - if ( intermediateContext != null ) { - log.trace( "Found interediate context: " + intermediateContextName ); - } + if (intermediateContext != null) LOG.foundIntermediateContext(intermediateContextName); else { - log.trace( "Creating subcontext: " + intermediateContextName ); + LOG.creatingSubcontextTrace(intermediateContextName); try { intermediateContext = intermediateContextBase.createSubcontext( intermediateContextName ); } @@ -151,7 +154,7 @@ public final class JndiHelper { intermediateContextBase = intermediateContext; n = n.getSuffix( 1 ); } - log.trace( "binding: " + n ); + LOG.binding(n); try { intermediateContextBase.rebind( n, value ); } @@ -159,7 +162,7 @@ public final class JndiHelper { throw new JndiException( "Error performing intermediate bind [" + n + "]", e ); } } - log.debug( "Bound name: " + jndiName ); + LOG.boundName(jndiName); } private static Name tokenizeName(String jndiName, Context context) { @@ -185,14 +188,14 @@ public final class JndiHelper { public static InitialContext getInitialContext(Properties props) throws NamingException { Hashtable hash = extractJndiProperties(props); - log.info("JNDI InitialContext properties:" + hash); + LOG.jndiInitialContextProperties(hash); try { return hash.size()==0 ? new InitialContext() : new InitialContext(hash); } catch (NamingException e) { - log.error("Could not obtain initial context", e); + LOG.error(LOG.unableToObtainInitialContext(), e); throw e; } } @@ -207,7 +210,7 @@ public final class JndiHelper { */ public static void bind(Context ctx, String name, Object val) throws NamingException { try { - log.trace("binding: " + name); + LOG.binding(name); ctx.rebind(name, val); } catch (Exception e) { @@ -217,26 +220,71 @@ public final class JndiHelper { Context subctx=null; try { - log.trace("lookup: " + ctxName); + LOG.lookup(ctxName); subctx = (Context) ctx.lookup(ctxName); } catch (NameNotFoundException nfe) {} if (subctx!=null) { - log.debug("Found subcontext: " + ctxName); + LOG.foundSubcontext(ctxName); ctx = subctx; } else { - log.info("Creating subcontext: " + ctxName); + LOG.creatingSubcontextInfo(ctxName); ctx = ctx.createSubcontext(ctxName); } n = n.getSuffix(1); } - log.trace("binding: " + n); + LOG.binding(n); ctx.rebind(n, val); } - log.debug("Bound name: " + name); + LOG.boundName(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 new file mode 100644 index 0000000000..e3c2d3808a --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/AbstractBatcher.java @@ -0,0 +1,714 @@ +/* + * 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 new file mode 100644 index 0000000000..91edc08952 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/BatchingBatcher.java @@ -0,0 +1,87 @@ +/* + * 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/ConnectionManager.java b/hibernate-core/src/main/java/org/hibernate/jdbc/ConnectionManager.java new file mode 100644 index 0000000000..d38c3bc730 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/ConnectionManager.java @@ -0,0 +1,598 @@ +/* + * 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 java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.sql.Connection; +import java.sql.SQLException; +import org.hibernate.ConnectionReleaseMode; +import org.hibernate.HibernateException; +import org.hibernate.Interceptor; +import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.exception.JDBCExceptionHelper; +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; + +/** + * Encapsulates JDBC Connection management logic needed by Hibernate. + *

      + * The lifecycle is intended to span a logical series of interactions with the + * database. Internally, this means the the lifecycle of the Session. + * + * @author Steve Ebersole + */ +public class ConnectionManager implements Serializable { + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ConnectionManager.class.getPackage().getName()); + + public static interface Callback { + public void connectionOpened(); + public void connectionCleanedUp(); + public boolean isTransactionInProgress(); + } + + private transient SessionFactoryImplementor factory; + private final Callback callback; + + private final ConnectionReleaseMode releaseMode; + private transient Connection connection; + private transient Connection borrowedConnection; + + private final boolean wasConnectionSupplied; + private transient Batcher batcher; + private transient Interceptor interceptor; + private boolean isClosed; + private transient boolean isFlushing; + + /** + * Constructs a ConnectionManager. + *

      + * This is the form used internally. + * + * @param factory The SessionFactory. + * @param callback An observer for internal state change. + * @param releaseMode The mode by which to release JDBC connections. + * @param connection An externally supplied connection. + */ + public ConnectionManager( + SessionFactoryImplementor factory, + Callback callback, + ConnectionReleaseMode releaseMode, + Connection connection, + Interceptor interceptor) { + this.factory = factory; + this.callback = callback; + + this.interceptor = interceptor; + this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); + + this.connection = connection; + wasConnectionSupplied = ( connection != null ); + + this.releaseMode = wasConnectionSupplied ? ConnectionReleaseMode.ON_CLOSE : releaseMode; + } + + /** + * Private constructor used exclusively from custom serialization + */ + private ConnectionManager( + SessionFactoryImplementor factory, + Callback callback, + ConnectionReleaseMode releaseMode, + Interceptor interceptor, + boolean wasConnectionSupplied, + boolean isClosed) { + this.factory = factory; + this.callback = callback; + + this.interceptor = interceptor; + this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); + + this.wasConnectionSupplied = wasConnectionSupplied; + this.isClosed = isClosed; + this.releaseMode = wasConnectionSupplied ? ConnectionReleaseMode.ON_CLOSE : releaseMode; + } + + /** + * The session factory. + * + * @return the session factory. + */ + public SessionFactoryImplementor getFactory() { + return factory; + } + + /** + * The batcher managed by this ConnectionManager. + * + * @return The batcher. + */ + public Batcher getBatcher() { + return batcher; + } + + /** + * Was the connection being used here supplied by the user? + * + * @return True if the user supplied the JDBC connection; false otherwise + */ + public boolean isSuppliedConnection() { + return wasConnectionSupplied; + } + + /** + * Retrieves the connection currently managed by this ConnectionManager. + *

      + * Note, that we may need to obtain a connection to return here if a + * connection has either not yet been obtained (non-UserSuppliedConnectionProvider) + * or has previously been aggressively released (if supported in this environment). + * + * @return The current Connection. + * + * @throws HibernateException Indicates a connection is currently not + * available (we are currently manually disconnected). + */ + public Connection getConnection() throws HibernateException { + if ( isClosed ) { + throw new HibernateException( "connection manager has been closed" ); + } + if ( connection == null ) { + openConnection(); + } + return connection; + } + + public boolean hasBorrowedConnection() { + // used from testsuite + return borrowedConnection != null; + } + + public Connection borrowConnection() { + if ( isClosed ) { + throw new HibernateException( "connection manager has been closed" ); + } + if ( isSuppliedConnection() ) { + return connection; + } + else { + if ( borrowedConnection == null ) { + borrowedConnection = BorrowedConnectionProxy.generateProxy( this ); + } + return borrowedConnection; + } + } + + public void releaseBorrowedConnection() { + if ( borrowedConnection != null ) { + try { + BorrowedConnectionProxy.renderUnuseable( borrowedConnection ); + } + finally { + borrowedConnection = null; + } + } + } + + /** + * Is the connection considered "auto-commit"? + * + * @return True if we either do not have a connection, or the connection + * really is in auto-commit mode. + * + * @throws SQLException Can be thrown by the Connection.isAutoCommit() check. + */ + public boolean isAutoCommit() throws SQLException { + return connection == null + || connection.isClosed() + || connection.getAutoCommit(); + } + + /** + * Will connections be released after each statement execution? + *

      + * Connections will be released after each statement if either:

        + *
      • the defined release-mode is {@link ConnectionReleaseMode#AFTER_STATEMENT}; or + *
      • the defined release-mode is {@link ConnectionReleaseMode#AFTER_TRANSACTION} but + * we are in auto-commit mode. + *

        + * release-mode = {@link ConnectionReleaseMode#ON_CLOSE} should [b]never[/b] release + * a connection. + * + * @return True if the connections will be released after each statement; false otherwise. + */ + public boolean isAggressiveRelease() { + if ( releaseMode == ConnectionReleaseMode.AFTER_STATEMENT ) { + return true; + } + else if ( releaseMode == ConnectionReleaseMode.AFTER_TRANSACTION ) { + boolean inAutoCommitState; + try { + inAutoCommitState = isAutoCommit()&& !callback.isTransactionInProgress(); + } + catch( SQLException e ) { + // assume we are in an auto-commit state + inAutoCommitState = true; + } + return inAutoCommitState; + } + return false; + } + + /** + * Modified version of {@link #isAggressiveRelease} which does not force a + * transaction check. This is solely used from our {@link #afterTransaction} + * callback, so no need to do the check; plus it seems to cause problems on + * websphere (god i love websphere ;) + *

        + * It uses this information to decide if an aggressive release was skipped + * do to open resources, and if so forces a release. + * + * @return True if the connections will be released after each statement; false otherwise. + */ + private boolean isAggressiveReleaseNoTransactionCheck() { + if ( releaseMode == ConnectionReleaseMode.AFTER_STATEMENT ) { + return true; + } + else { + boolean inAutoCommitState; + try { + inAutoCommitState = isAutoCommit(); + } + catch( SQLException e ) { + // assume we are in an auto-commit state + inAutoCommitState = true; + } + return releaseMode == ConnectionReleaseMode.AFTER_TRANSACTION && inAutoCommitState; + } + } + + /** + * Is this ConnectionManager instance "logically" connected. Meaning + * do we either have a cached connection available or do we have the + * ability to obtain a connection on demand. + * + * @return True if logically connected; false otherwise. + */ + public boolean isCurrentlyConnected() { + return wasConnectionSupplied ? connection != null : !isClosed; + } + + /** + * To be called after execution of each JDBC statement. Used to + * conditionally release the JDBC connection aggressively if + * the configured release mode indicates. + */ + public void afterStatement() { + if ( isAggressiveRelease() ) { + if (isFlushing) LOG.skippingAggressiveReleaseDueToFlushCycle(); + else if (batcher.hasOpenResources()) LOG.skippingAggressiveReleaseDueToOpenResources(); + else if (borrowedConnection != null) LOG.skippingAggressiveReleaseDueToBorrowedConnection(); + else aggressiveRelease(); + } + } + + /** + * To be called after local transaction completion. Used to conditionally + * release the JDBC connection aggressively if the configured release mode + * indicates. + */ + public void afterTransaction() { + if (isAfterTransactionRelease()) aggressiveRelease(); + else if ( isAggressiveReleaseNoTransactionCheck() && batcher.hasOpenResources() ) { + LOG.forcingBatcherResourceCleanup(); + batcher.closeStatements(); + aggressiveRelease(); + } else if (isOnCloseRelease()) LOG.transactionCompletedWithOnCloseConnectionReleaseMode(); + batcher.unsetTransactionTimeout(); + } + + private boolean isAfterTransactionRelease() { + return releaseMode == ConnectionReleaseMode.AFTER_TRANSACTION; + } + + private boolean isOnCloseRelease() { + return releaseMode == ConnectionReleaseMode.ON_CLOSE; + } + + /** + * To be called after Session completion. Used to release the JDBC + * connection. + * + * @return The connection mantained here at time of close. Null if + * there was no connection cached internally. + */ + public Connection close() { + try { + return cleanup(); + } + finally { + isClosed = true; + } + } + + /** + * Manually disconnect the underlying JDBC Connection. The assumption here + * is that the manager will be reconnected at a later point in time. + * + * @return The connection mantained here at time of disconnect. Null if + * there was no connection cached internally. + */ + public Connection manualDisconnect() { + return cleanup(); + } + + /** + * Manually reconnect the underlying JDBC Connection. Should be called at + * some point after manualDisconnect(). + *

        + * This form is used for ConnectionProvider-supplied connections. + */ + public void manualReconnect() { + } + + /** + * Manually reconnect the underlying JDBC Connection. Should be called at + * some point after manualDisconnect(). + *

        + * This form is used for user-supplied connections. + */ + public void manualReconnect(Connection suppliedConnection) { + this.connection = suppliedConnection; + } + + /** + * Releases the Connection and cleans up any resources associated with + * that Connection. This is intended for use: + * 1) at the end of the session + * 2) on a manual disconnect of the session + * 3) from afterTransaction(), in the case of skipped aggressive releasing + * + * @return The released connection. + * @throws HibernateException + */ + private Connection cleanup() throws HibernateException { + releaseBorrowedConnection(); + + if ( connection == null ) { + LOG.connectionAlreadyNullInCleanup(); + return null; + } + + try { + LOG.performingCleanup(); + + batcher.closeStatements(); + Connection c = null; + if ( !wasConnectionSupplied ) { + closeConnection(); + } + else { + c = connection; + } + connection = null; + return c; + } + finally { + callback.connectionCleanedUp(); + } + } + + /** + * Performs actions required to perform an aggressive release of the + * JDBC Connection. + */ + private void aggressiveRelease() { + if ( !wasConnectionSupplied ) { + LOG.aggressivelyReleasingJdbcConnection(); + if (connection != null) closeConnection(); + } + } + + /** + * Pysically opens a JDBC Connection. + * + * @throws HibernateException + */ + private void openConnection() throws HibernateException { + if (connection != null) return; + + LOG.openingJdbcConnection(); + try { + connection = factory.getConnectionProvider().getConnection(); + } + catch (SQLException sqle) { + throw JDBCExceptionHelper.convert( + factory.getSQLExceptionConverter(), + sqle, + "Cannot open connection" + ); + } + + callback.connectionOpened(); // register synch; stats.connect() + } + + /** + * Physically closes the JDBC Connection. + */ + private void closeConnection() { + if (LOG.isDebugEnabled()) LOG.releasingJdbcConnection(batcher.openResourceStatsAsString()); + + try { + if ( !connection.isClosed() ) { + JDBCExceptionReporter.logAndClearWarnings( connection ); + } + factory.getConnectionProvider().closeConnection( connection ); + connection = null; + } + catch (SQLException sqle) { + throw JDBCExceptionHelper.convert( + factory.getSQLExceptionConverter(), + sqle, + "Cannot release connection" + ); + } + } + + /** + * Callback to let us know that a flush is beginning. We use this fact + * to temporarily circumvent aggressive connection releasing until after + * the flush cycle is complete {@link #flushEnding()} + */ + public void flushBeginning() { + LOG.registeringFlushBegin(); + isFlushing = true; + } + + /** + * Callback to let us know that a flush is ending. We use this fact to + * stop circumventing aggressive releasing connections. + */ + public void flushEnding() { + LOG.registeringFlushEnd(); + isFlushing = false; + afterStatement(); + } + + public boolean isReadyForSerialization() { + return wasConnectionSupplied ? connection == null : !batcher.hasOpenResources(); + } + + /** + * Used during serialization. + * + * @param oos The stream to which we are being written. + * @throws IOException Indicates an I/O error writing to the stream + */ + private void writeObject(ObjectOutputStream oos) throws IOException { + if ( !isReadyForSerialization() ) { + throw new IllegalStateException( "Cannot serialize a ConnectionManager while connected" ); + } + + oos.writeObject( factory ); + oos.writeObject( interceptor ); + oos.defaultWriteObject(); + } + + /** + * Used during deserialization. + * + * @param ois The stream from which we are being read. + * @throws IOException Indicates an I/O error reading the stream + * @throws ClassNotFoundException Indicates resource class resolution. + */ + private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { + factory = (SessionFactoryImplementor) ois.readObject(); + interceptor = (Interceptor) ois.readObject(); + ois.defaultReadObject(); + + this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); + } + + public void serialize(ObjectOutputStream oos) throws IOException { + oos.writeBoolean( wasConnectionSupplied ); + oos.writeBoolean( isClosed ); + } + + public static ConnectionManager deserialize( + ObjectInputStream ois, + SessionFactoryImplementor factory, + Interceptor interceptor, + ConnectionReleaseMode connectionReleaseMode, + JDBCContext jdbcContext) throws IOException { + return new ConnectionManager( + factory, + jdbcContext, + connectionReleaseMode, + interceptor, + ois.readBoolean(), + 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 = "Connection already null in cleanup : no action" ) + void connectionAlreadyNullInCleanup(); + + @LogMessage( level = INFO ) + @Message( value = "Forcing batcher resource cleanup on transaction completion; forgot to close ScrollableResults/Iterator?" ) + void forcingBatcherResourceCleanup(); + + @LogMessage( level = DEBUG ) + @Message( value = "Opening JDBC connection" ) + void openingJdbcConnection(); + + @LogMessage( level = TRACE ) + @Message( value = "Performing cleanup" ) + void performingCleanup(); + + @LogMessage( level = TRACE ) + @Message( value = "Registering flush begin" ) + void registeringFlushBegin(); + + @LogMessage( level = TRACE ) + @Message( value = "Registering flush end" ) + void registeringFlushEnd(); + + @LogMessage( level = DEBUG ) + @Message( value = "Releasing JDBC connection [%s]" ) + void releasingJdbcConnection( String openResourceStatsAsString ); + + @LogMessage( level = DEBUG ) + @Message( value = "Skipping aggresive-release due to borrowed connection" ) + void skippingAggressiveReleaseDueToBorrowedConnection(); + + @LogMessage( level = DEBUG ) + @Message( value = "Skipping aggressive-release due to flush cycle" ) + void skippingAggressiveReleaseDueToFlushCycle(); + + @LogMessage( level = DEBUG ) + @Message( value = "Skipping aggresive-release due to open resources on batcher" ) + void skippingAggressiveReleaseDueToOpenResources(); + + @LogMessage( level = DEBUG ) + @Message( value = "Transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!" ) + void transactionCompletedWithOnCloseConnectionReleaseMode(); + } +} 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 45d093dd7e..7029285cbe 100644 --- a/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java +++ b/hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java @@ -24,18 +24,20 @@ */ package org.hibernate.jdbc; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.StaleStateException; -import org.hibernate.HibernateException; -import org.hibernate.engine.ExecuteUpdateResultCheckStyle; -import org.hibernate.util.JDBCExceptionReporter; -import org.hibernate.exception.GenericJDBCException; - +import static org.jboss.logging.Logger.Level.DEBUG; import java.sql.CallableStatement; -import java.sql.SQLException; import java.sql.PreparedStatement; +import java.sql.SQLException; import java.sql.Types; +import org.hibernate.HibernateException; +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. @@ -43,7 +45,9 @@ import java.sql.Types; * @author Steve Ebersole */ public class Expectations { - private static final Logger log = LoggerFactory.getLogger( Expectations.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Expectations.class.getPackage().getName()); public static final int USUAL_EXPECTED_COUNT = 1; public static final int USUAL_PARAM_POSITION = 1; @@ -72,22 +76,13 @@ public class Expectations { } private void checkBatched(int rowCount, int batchPosition) { - if ( rowCount == -2 ) { - if ( log.isDebugEnabled() ) { - log.debug( "success of batch update unknown: " + batchPosition ); - } - } - else if ( rowCount == -3 ) { - throw new BatchFailedException( "Batch update failed: " + batchPosition ); - } + if (rowCount == -2) LOG.successOfBatchUpdateUnknown(batchPosition); + else if (rowCount == -3) throw new BatchFailedException("Batch update failed: " + batchPosition); else { - if ( expectedRowCount > rowCount ) { - throw new StaleStateException( - "Batch update returned unexpected row count from update [" + batchPosition + - "]; actual row count: " + rowCount + - "; expected: " + expectedRowCount - ); - } + if (expectedRowCount > rowCount) throw new StaleStateException( + "Batch update returned unexpected row count from update [" + + batchPosition + "]; actual row count: " + rowCount + + "; expected: " + expectedRowCount); if ( expectedRowCount < rowCount ) { String msg = "Batch update returned unexpected row count from update [" + batchPosition + "]; actual row count: " + rowCount + @@ -129,16 +124,19 @@ public class Expectations { this.parameterPosition = parameterPosition; } - public int prepare(PreparedStatement statement) throws SQLException, HibernateException { + @Override + public int prepare(PreparedStatement statement) throws SQLException, HibernateException { toCallableStatement( statement ).registerOutParameter( parameterPosition, Types.NUMERIC ); return 1; } - public boolean canBeBatched() { + @Override + public boolean canBeBatched() { return false; } - protected int determineRowCount(int reportedRowCount, PreparedStatement statement) { + @Override + protected int determineRowCount(int reportedRowCount, PreparedStatement statement) { try { return toCallableStatement( statement ).getInt( parameterPosition ); } @@ -195,4 +193,15 @@ 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 5fea4adab6..506abc33a7 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,8 @@ */ package org.hibernate.jdbc.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.MessageLogger; /** * Centralize logging handling for SQL statements. @@ -36,7 +36,9 @@ public class SQLStatementLogger { // todo : for 4.0 // private static final Logger log = LoggerFactory.getLogger( SQLStatementLogger.class ); // this is the legacy logging 'category'... - private static final Logger log = LoggerFactory.getLogger( "org.hibernate.SQL" ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLStatementLogger.class.getPackage().getName()); private boolean logToStdout; private boolean formatSql; @@ -104,17 +106,22 @@ public class SQLStatementLogger { * @param style The requested formatting style. */ public void logStatement(String statement, FormatStyle style) { - if ( log.isDebugEnabled() || logToStdout ) { + if (LOG.isDebugEnabled() || logToStdout) { style = determineActualStyle( style ); statement = style.getFormatter().format( statement ); - } - log.debug( statement ); - if ( logToStdout ) { - System.out.println( "Hibernate: " + statement ); + LOG.debug(statement); + if (logToStdout) System.out.println("Hibernate: " + statement); } } 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 a4946c1398..5026fbfc3c 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/HibernateService.java @@ -1,22 +1,21 @@ //$Id: HibernateService.java 6100 2005-03-17 10:48:03Z turin42 $ package org.hibernate.jmx; -import java.util.Properties; +import static org.jboss.logging.Logger.Level.INFO; import java.util.Map; - +import java.util.Properties; import javax.naming.InitialContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Environment; import org.hibernate.cfg.internal.ServicesRegistryBootstrap; -import org.hibernate.service.spi.ServicesRegistry; -import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.internal.util.jndi.JndiHelper; +import org.hibernate.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; /** @@ -30,7 +29,8 @@ import org.hibernate.util.ExternalSessionFactoryConfig; */ public class HibernateService extends ExternalSessionFactoryConfig implements HibernateServiceMBean { - private static final Logger log = LoggerFactory.getLogger(HibernateServiceMBean.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HibernateService.class.getPackage().getName()); private String boundName; private Properties properties = new Properties(); @@ -41,33 +41,34 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi buildSessionFactory(); } catch (HibernateException he) { - log.info( "Could not build SessionFactory using the MBean classpath - will try again using client classpath: " + he.getMessage() ); - log.debug("Error was", he); + LOG.unableToBuildSessionFactoryUsingMBeanClasspath(he.getMessage()); + LOG.debug(LOG.errorWas(), he); new SessionFactoryStub(this); } } public void stop() { - log.info("stopping service"); + LOG.stoppingService(); try { InitialContext context = JndiHelper.getInitialContext( buildProperties() ); ( (SessionFactory) context.lookup(boundName) ).close(); //context.unbind(boundName); } catch (Exception e) { - log.warn("exception while stopping service", e); + LOG.warn(LOG.unableToStopService(), e); } } - + SessionFactory buildSessionFactory() throws HibernateException { - log.info( "starting service at JNDI name: " + boundName ); - log.info( "service properties: " + properties ); + LOG.startingServiceAtJndiName(boundName); + LOG.serviceProperties(properties); return buildConfiguration().buildSessionFactory( new ServicesRegistryBootstrap().initiateServicesRegistry( properties ) ); } - protected Map getExtraProperties() { + @Override + protected Map getExtraProperties() { return properties; } @@ -168,4 +169,33 @@ 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 f1d39a5ca6..b1c6c1b85c 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/SessionFactoryStub.java @@ -23,25 +23,22 @@ */ package org.hibernate.jmx; +import static org.jboss.logging.Logger.Level.DEBUG; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.sql.Connection; import java.util.Map; import java.util.Set; - import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.StringRefAddr; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; +import org.hibernate.Cache; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; -import org.hibernate.Cache; import org.hibernate.TypeHelper; import org.hibernate.engine.FilterDefinition; import org.hibernate.id.IdentifierGenerator; @@ -50,6 +47,10 @@ 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 @@ -60,7 +61,9 @@ import org.hibernate.stat.Statistics; */ public class SessionFactoryStub implements SessionFactory { private static final IdentifierGenerator UUID_GENERATOR = UUIDGenerator.buildSessionFactoryUniqueIdentifierGenerator(); - private static final Logger log = LoggerFactory.getLogger( SessionFactoryStub.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SessionFactoryStub.class.getPackage().getName()); private transient SessionFactory impl; private transient HibernateService service; @@ -91,7 +94,7 @@ public class SessionFactoryStub implements SessionFactory { public org.hibernate.classic.Session openSession() throws HibernateException { return getImpl().openSession(); } - + public org.hibernate.classic.Session openSession(Connection conn) { return getImpl().openSession(conn); } @@ -99,7 +102,7 @@ public class SessionFactoryStub implements SessionFactory { public org.hibernate.classic.Session getCurrentSession() { return getImpl().getCurrentSession(); } - + private synchronized SessionFactory getImpl() { if (impl==null) impl = service.buildSessionFactory(); return impl; @@ -110,19 +113,12 @@ public class SessionFactoryStub implements SessionFactory { // look for the instance by uuid Object result = SessionFactoryObjectFactory.getInstance(uuid); if (result==null) { - // in case we were deserialized in a different JVM, look for an instance with the same name + // in case we were deserialized in a different JVM, look for an instance with the same name // (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); - } - else { - log.debug("resolved stub SessionFactory by name"); - } - } - else { - log.debug("resolved stub SessionFactory by uid"); - } + if (result == null) throw new InvalidObjectException("Could not find a stub SessionFactory named: " + name); + LOG.resolvedStubSessionFactoryByName(); + } else LOG.resolvedStubSessionFactoryByUid(); return result; } @@ -161,7 +157,7 @@ public class SessionFactoryStub implements SessionFactory { public void close() throws HibernateException { } - + public boolean isClosed() { return false; } @@ -183,7 +179,7 @@ public class SessionFactoryStub implements SessionFactory { throws HibernateException { getImpl().evictEntity(entityName, id); } - + public void evictEntity(String entityName) throws HibernateException { getImpl().evictEntity(entityName); } @@ -232,4 +228,19 @@ 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 e262c6208f..f100273916 100644 --- a/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java +++ b/hibernate-core/src/main/java/org/hibernate/jmx/StatisticsService.java @@ -5,9 +5,6 @@ import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.naming.Reference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.SessionFactory; import org.hibernate.impl.SessionFactoryObjectFactory; import org.hibernate.stat.CollectionStatistics; @@ -16,6 +13,9 @@ 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
        @@ -46,16 +46,17 @@ import org.hibernate.stat.StatisticsImpl; * And call the MBean by providing the SessionFactoryJNDIName first. * Then the session factory will be retrieved from JNDI and the statistics * loaded. - * + * * @author Emmanuel Bernard */ public class StatisticsService implements StatisticsServiceMBean { - + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StatisticsService.class.getPackage().getName()); //TODO: We probably should have a StatisticsNotPublishedException, to make it clean - + SessionFactory sf; String sfJNDIName; - Logger log = LoggerFactory.getLogger(StatisticsService.class); Statistics stats = new StatisticsImpl(); /** @@ -71,25 +72,25 @@ public class StatisticsService implements StatisticsServiceMBean { } else { setSessionFactory( (SessionFactory) obj ); - } - } + } + } catch (NameNotFoundException e) { - log.error("No session factory with JNDI name " + sfJNDIName, e); + LOG.error(LOG.noSessionFactoryWithJndiName(sfJNDIName), e); setSessionFactory(null); - } + } catch (NamingException e) { - log.error("Error while accessing session factory with JNDI name " + sfJNDIName, e); + LOG.error(LOG.unableToAccessSessionFactory(sfJNDIName), e); setSessionFactory(null); - } + } catch (ClassCastException e) { - log.error("JNDI name " + sfJNDIName + " does not handle a session factory reference", e); + LOG.error(LOG.jndiNameDoesNotHandleSessionFactoryReference(sfJNDIName), e); setSessionFactory(null); } } - + /** * Useful to init this MBean wo a JNDI session factory name - * + * * @param sf session factory to register */ public void setSessionFactory(SessionFactory sf) { @@ -98,9 +99,9 @@ public class StatisticsService implements StatisticsServiceMBean { stats = new StatisticsImpl(); } else { - stats = sf.getStatistics(); + stats = sf.getStatistics(); } - + } /** * @see StatisticsServiceMBean#clear() @@ -272,7 +273,7 @@ public class StatisticsService implements StatisticsServiceMBean { public void setStatisticsEnabled(boolean enable) { stats.setStatisticsEnabled(enable); } - + public void logSummary() { stats.logSummary(); } @@ -292,7 +293,7 @@ public class StatisticsService implements StatisticsServiceMBean { public String[] getSecondLevelCacheRegionNames() { return stats.getSecondLevelCacheRegionNames(); } - + public long getSuccessfulTransactionCount() { return stats.getSuccessfulTransactionCount(); } @@ -314,4 +315,20 @@ 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 b0e8d6ca91..32c504eee1 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java @@ -23,6 +23,8 @@ */ 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; @@ -36,23 +38,21 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.LockMode; +import org.hibernate.LockOptions; import org.hibernate.QueryException; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.StaleObjectStateException; import org.hibernate.WrongClassException; -import org.hibernate.LockOptions; import org.hibernate.cache.FilterKey; 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,6 +83,10 @@ 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 @@ -100,7 +104,7 @@ import org.hibernate.util.StringHelper; */ public abstract class Loader { - private static final Logger log = LoggerFactory.getLogger( Loader.class ); + protected static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Loader.class.getPackage().getName()); private final SessionFactoryImplementor factory; private ColumnNameCache columnNameCache; @@ -123,7 +127,7 @@ public abstract class Loader { * @return The entity persisters. */ protected abstract Loadable[] getEntityPersisters(); - + /** * An array indicating whether the entities have eager property fetching * enabled. @@ -157,7 +161,7 @@ public abstract class Loader { } /** - * An (optional) persister for a collection to be initialized; only + * An (optional) persister for a collection to be initialized; only * collection loaders return a non-null value */ protected CollectionPersister[] getCollectionPersisters() { @@ -226,7 +230,7 @@ public abstract class Loader { throws HibernateException { sql = applyLocks( sql, parameters.getLockOptions(), dialect ); - + return getFactory().getSettings().isCommentsEnabled() ? prependComment( sql, parameters ) : sql; } @@ -317,7 +321,7 @@ public abstract class Loader { final boolean returnProxies) throws HibernateException { final int entitySpan = getEntityPersisters().length; - final List hydratedObjects = entitySpan == 0 ? + final List hydratedObjects = entitySpan == 0 ? null : new ArrayList( entitySpan ); final Object result; @@ -341,10 +345,10 @@ public abstract class Loader { ); } - initializeEntitiesAndCollections( - hydratedObjects, - resultSet, - session, + initializeEntitiesAndCollections( + hydratedObjects, + resultSet, + session, queryParameters.isReadOnly( session ) ); session.getPersistenceContext().initializeNonLazyCollections(); @@ -359,7 +363,7 @@ public abstract class Loader { final EntityKey keyToRead) throws HibernateException { final int entitySpan = getEntityPersisters().length; - final List hydratedObjects = entitySpan == 0 ? + final List hydratedObjects = entitySpan == 0 ? null : new ArrayList( entitySpan ); Object result = null; @@ -380,7 +384,7 @@ public abstract class Loader { if ( result == null ) { result = loaded; } - } + } while ( keyToRead.equals( loadedKeys[0] ) && resultSet.next() ); } catch ( SQLException sqle ) { @@ -391,10 +395,10 @@ public abstract class Loader { ); } - initializeEntitiesAndCollections( - hydratedObjects, - resultSet, - session, + initializeEntitiesAndCollections( + hydratedObjects, + resultSet, + session, queryParameters.isReadOnly( session ) ); session.getPersistenceContext().initializeNonLazyCollections(); @@ -589,9 +593,9 @@ public abstract class Loader { final String optionalEntityName = queryParameters.getOptionalEntityName(); if ( optionalObject != null && optionalEntityName != null ) { - return new EntityKey( + return new EntityKey( optionalId, - session.getEntityPersister( optionalEntityName, optionalObject ), + session.getEntityPersister( optionalEntityName, optionalObject ), session.getEntityMode() ); } @@ -788,11 +792,11 @@ public abstract class Loader { for ( int i=0; i -1; //true if this is a query and we are loading multiple instances of the same collection role //otherwise this is a CollectionInitializer and we are loading up a single collection or batch - + final Object owner = hasCollectionOwners ? row[ collectionOwners[i] ] : null; //if null, owner will be retrieved from session @@ -807,16 +811,16 @@ public abstract class Loader { //TODO: old version did not require hashmap lookup: //keys[collectionOwner].getIdentifier() } - - readCollectionElement( - owner, - key, - collectionPersister, - descriptors[i], - resultSet, - session + + readCollectionElement( + owner, + key, + collectionPersister, + descriptors[i], + resultSet, + session ); - + } } @@ -857,14 +861,14 @@ public abstract class Loader { EntityKey[] keys = new EntityKey[entitySpan]; //we can reuse it for each row - if ( log.isTraceEnabled() ) log.trace( "processing result set" ); + LOG.processingResultSet(); int count; for ( count = 0; count < maxRows && rs.next(); count++ ) { - - if ( log.isTraceEnabled() ) log.debug("result set row: " + count); - Object result = getRowFromResultSet( + LOG.resultSetRow(count); + + Object result = getRowFromResultSet( rs, session, queryParameters, @@ -881,12 +885,10 @@ public abstract class Loader { subselectResultKeys.add(keys); keys = new EntityKey[entitySpan]; //can't reuse in this case } - + } - if ( log.isTraceEnabled() ) { - log.trace( "done processing result set (" + count + " rows)" ); - } + LOG.processingResultSetDone(count); } finally { @@ -904,7 +906,7 @@ public abstract class Loader { protected boolean isSubselectLoadingEnabled() { return false; } - + protected boolean hasSubselectLoadableCollections() { final Loadable[] loadables = getEntityPersisters(); for (int i=0; i 1 ) { //if we only returned one entity, query by key is more efficient - + Set[] keySets = transpose(keys); - + Map namedParameterLocMap = buildNamedParameterLocMap( queryParameters ); - + final Loadable[] loadables = getEntityPersisters(); final String[] aliases = getAliases(); final Iterator iter = keys.iterator(); while ( iter.hasNext() ) { - + final EntityKey[] rowKeys = (EntityKey[]) iter.next(); for ( int i=0; i -1 ) { EntityKey ownerKey = keys[owner]; if ( keys[i] == null && ownerKey != null ) { - + final PersistenceContext persistenceContext = session.getPersistenceContext(); - + /*final boolean isPrimaryKey; final boolean isSpecialOneToOne; if ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) { @@ -1132,24 +1132,24 @@ public abstract class Loader { isPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null; isSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null; }*/ - + //TODO: can we *always* use the "null property" approach for everything? /*if ( isPrimaryKey && !isSpecialOneToOne ) { - persistenceContext.addNonExistantEntityKey( - new EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() ) + persistenceContext.addNonExistantEntityKey( + new EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() ) ); } else if ( isSpecialOneToOne ) {*/ - boolean isOneToOneAssociation = ownerAssociationTypes!=null && - ownerAssociationTypes[i]!=null && + boolean isOneToOneAssociation = ownerAssociationTypes!=null && + ownerAssociationTypes[i]!=null && ownerAssociationTypes[i].isOneToOne(); if ( isOneToOneAssociation ) { - persistenceContext.addNullProperty( ownerKey, + persistenceContext.addNullProperty( ownerKey, ownerAssociationTypes[i].getPropertyName() ); } /*} else { - persistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey( + persistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey( persisters[i].getEntityName(), ownerAssociationTypes[i].getRHSUniqueKeyPropertyName(), ownerKey.getIdentifier(), @@ -1172,26 +1172,23 @@ public abstract class Loader { final CollectionPersister persister, final CollectionAliases descriptor, final ResultSet rs, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { final PersistenceContext persistenceContext = session.getPersistenceContext(); - final Serializable collectionRowKey = (Serializable) persister.readKey( - rs, - descriptor.getSuffixedKeyAliases(), - session + final Serializable collectionRowKey = (Serializable) persister.readKey( + rs, + descriptor.getSuffixedKeyAliases(), + session ); - + if ( collectionRowKey != null ) { // we found a collection element in the result set - if ( log.isDebugEnabled() ) { - log.debug( - "found row of collection: " + - MessageHelper.collectionInfoString( persister, collectionRowKey, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.foundCollectionRow(MessageHelper.collectionInfoString(persister, + collectionRowKey, + getFactory())); Object owner = optionalOwner; if ( owner == null ) { @@ -1219,12 +1216,9 @@ 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.debug( - "result set contains (possibly empty) collection: " + - MessageHelper.collectionInfoString( persister, optionalKey, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.resultSetContainsCollection(MessageHelper.collectionInfoString(persister, + optionalKey, + getFactory())); persistenceContext.getLoadContexts() .getCollectionLoadContext( rs ) @@ -1255,13 +1249,10 @@ public abstract class Loader { for ( int j=0; j! ); - - final boolean idIsResultId = id != null && - resultId != null && + + final boolean idIsResultId = id != null && + resultId != null && idType.isEqual( id, resultId, session.getEntityMode(), factory ); - + if ( idIsResultId ) resultId = id; //use the id passed in } @@ -1330,7 +1321,7 @@ public abstract class Loader { final Serializable id, final Object entity, final ResultSet rs, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { Object version = session.getPersistenceContext().getEntry( entity ).getVersion(); @@ -1369,18 +1360,13 @@ public abstract class Loader { final EntityKey optionalObjectKey, final LockMode[] lockModes, final List hydratedObjects, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { final int cols = persisters.length; final EntityAliases[] descriptors = getEntityAliases(); - if ( log.isDebugEnabled() ) { - log.debug( - "result row: " + - StringHelper.toString( keys ) - ); - } + if (LOG.isDebugEnabled()) LOG.resultRow(StringHelper.toString(keys)); final Object[] rowResults = new Object[cols]; @@ -1398,18 +1384,18 @@ public abstract class Loader { object = session.getEntityUsingInterceptor( key ); if ( object != null ) { //its already loaded so don't need to hydrate it - instanceAlreadyLoaded( + instanceAlreadyLoaded( rs, i, persisters[i], key, object, lockModes[i], - session + session ); } else { - object = instanceNotYetLoaded( + object = instanceNotYetLoaded( rs, i, persisters[i], @@ -1419,7 +1405,7 @@ public abstract class Loader { optionalObjectKey, optionalObject, hydratedObjects, - session + session ); } @@ -1442,13 +1428,13 @@ public abstract class Loader { final EntityKey key, final Object object, final LockMode lockMode, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { if ( !persister.isInstance( object, session.getEntityMode() ) ) { - throw new WrongClassException( - "loaded object was of wrong class " + object.getClass(), - key.getIdentifier(), - persister.getEntityName() + throw new WrongClassException( + "loaded object was of wrong class " + object.getClass(), + key.getIdentifier(), + persister.getEntityName() ); } @@ -1483,14 +1469,14 @@ public abstract class Loader { final EntityKey optionalObjectKey, final Object optionalObject, final List hydratedObjects, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { final String instanceClass = getInstanceClass( - rs, - i, - persister, - key.getIdentifier(), - session + rs, + i, + persister, + key.getIdentifier(), + session ); final Object object; @@ -1509,16 +1495,16 @@ public abstract class Loader { // (but don't yet initialize the object itself) // note that we acquire LockMode.READ even if it was not requested LockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode; - loadFromResultSet( - rs, - i, - object, - instanceClass, - key, - rowIdAlias, - acquiredLockMode, - persister, - session + loadFromResultSet( + rs, + i, + object, + instanceClass, + key, + rowIdAlias, + acquiredLockMode, + persister, + session ); //materialize associations (and initialize the object) later @@ -1526,7 +1512,7 @@ public abstract class Loader { return object; } - + private boolean isEagerPropertyFetchEnabled(int i) { boolean[] array = getEntityEagerPropertyFetches(); return array!=null && array[i]; @@ -1547,7 +1533,7 @@ public abstract class Loader { final String rowIdAlias, final LockMode lockMode, final Loadable rootPersister, - final SessionImplementor session) + final SessionImplementor session) throws SQLException, HibernateException { final Serializable id = key.getIdentifier(); @@ -1555,25 +1541,20 @@ public abstract class Loader { // Get the persister for the _subclass_ final Loadable persister = (Loadable) getFactory().getEntityPersister( instanceEntityName ); - if ( log.isTraceEnabled() ) { - log.trace( - "Initializing object from ResultSet: " + - MessageHelper.infoString( persister, id, getFactory() ) - ); - } - + if (LOG.isTraceEnabled()) LOG.initializingObjectFromResultSet(MessageHelper.infoString(persister, id, getFactory())); + boolean eagerPropertyFetch = isEagerPropertyFetchEnabled(i); // add temp entry so that the next step is circular-reference // safe - only needed because some types don't take proper // advantage of two-phase-load (esp. components) - TwoPhaseLoad.addUninitializedEntity( - key, - object, - persister, - lockMode, - !eagerPropertyFetch, - session + TwoPhaseLoad.addUninitializedEntity( + key, + object, + persister, + lockMode, + !eagerPropertyFetch, + session ); //This is not very nice (and quite slow): @@ -1581,14 +1562,14 @@ public abstract class Loader { getEntityAliases()[i].getSuffixedPropertyAliases() : getEntityAliases()[i].getSuffixedPropertyAliases(persister); - final Object[] values = persister.hydrate( - rs, - id, - object, - rootPersister, - cols, - eagerPropertyFetch, - session + final Object[] values = persister.hydrate( + rs, + id, + object, + rootPersister, + cols, + eagerPropertyFetch, + session ); final Object rowId = persister.hasRowId() ? rs.getObject(rowIdAlias) : null; @@ -1599,13 +1580,13 @@ public abstract class Loader { if (ukName!=null) { final int index = ( (UniqueKeyLoadable) persister ).getPropertyIndex(ukName); final Type type = persister.getPropertyTypes()[index]; - + // polymorphism not really handled completely correctly, // perhaps...well, actually its ok, assuming that the // entity name used in the lookup is the same as the // the one used here, which it will be - - EntityUniqueKey euk = new EntityUniqueKey( + + EntityUniqueKey euk = new EntityUniqueKey( rootPersister.getEntityName(), //polymorphism comment above ukName, type.semiResolve( values[index], session, object ), @@ -1616,15 +1597,15 @@ public abstract class Loader { } } - TwoPhaseLoad.postHydrate( - persister, - id, - values, - rowId, - object, - lockMode, - !eagerPropertyFetch, - session + TwoPhaseLoad.postHydrate( + persister, + id, + values, + rowId, + object, + lockMode, + !eagerPropertyFetch, + session ); } @@ -1637,7 +1618,7 @@ public abstract class Loader { final int i, final Loadable persister, final Serializable id, - final SessionImplementor session) + final SessionImplementor session) throws HibernateException, SQLException { if ( persister.hasSubclasses() ) { @@ -1654,10 +1635,10 @@ public abstract class Loader { if ( result == null ) { //woops we got an instance of another class hierarchy branch - throw new WrongClassException( + throw new WrongClassException( "Discriminator: " + discriminatorValue, id, - persister.getEntityName() + persister.getEntityName() ); } @@ -1731,22 +1712,22 @@ public abstract class Loader { boolean hasFirstRow = getFirstRow( selection ) > 0; boolean useOffset = hasFirstRow && useLimit && dialect.supportsLimitOffset(); boolean callable = queryParameters.isCallable(); - + boolean useScrollableResultSetToSkip = hasFirstRow && !useOffset && getFactory().getSettings().isScrollableResultSetsEnabled(); ScrollMode scrollMode = scroll ? queryParameters.getScrollMode() : ScrollMode.SCROLL_INSENSITIVE; if ( useLimit ) { - sql = dialect.getLimitString( + sql = dialect.getLimitString( sql.trim(), //use of trim() here is ugly? - useOffset ? getFirstRow(selection) : 0, - getMaxOrLimit(selection, dialect) + useOffset ? getFirstRow(selection) : 0, + getMaxOrLimit(selection, dialect) ); } sql = preprocessSQL( sql, queryParameters, dialect ); - + PreparedStatement st = null; st = session.getJDBCContext().getConnectionManager().prepareQueryStatement( @@ -1790,19 +1771,12 @@ public abstract class Loader { LockOptions lockOptions = queryParameters.getLockOptions(); if ( lockOptions != null ) { if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) { - 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() ); - } + if (!dialect.supportsLockTimeouts()) LOG.unsupportedLockTimeoutRequested(lockOptions.getTimeOut()); + else if (dialect.isLockTimeoutParameterized()) st.setInt(col++, lockOptions.getTimeOut()); } } - log.trace( "Bound [" + col + "] parameters total" ); + LOG.boundParametersTotal(col); } catch ( SQLException sqle ) { st.close(); @@ -1963,13 +1937,7 @@ public abstract class Loader { TypedValue typedval = ( TypedValue ) e.getValue(); int[] locs = getNamedParameterLocs( name ); for ( int i = 0; i < locs.length; i++ ) { - if ( log.isDebugEnabled() ) { - log.debug( - "bindNamedParameters() " + - typedval.getValue() + " -> " + name + - " [" + ( locs[i] + startIndex ) + "]" - ); - } + LOG.bindNamedParameters(typedval.getValue(), name, locs[i] + startIndex); typedval.getType().nullSafeSet( statement, typedval.getValue(), locs[i] + startIndex, session ); } result += locs.length; @@ -1994,19 +1962,19 @@ public abstract class Loader { final boolean autodiscovertypes, final boolean callable, final RowSelection selection, - final SessionImplementor session) + final SessionImplementor session) throws SQLException, HibernateException { - + ResultSet rs = null; try { Dialect dialect = getFactory().getDialect(); rs = st.executeQuery(); rs = wrapResultSetIfEnabled( rs , session ); - + if ( !dialect.supportsLimitOffset() || !useLimit( selection, dialect ) ) { advance( rs, selection ); } - + if ( autodiscovertypes ) { autoDiscoverTypes( rs ); } @@ -2020,7 +1988,7 @@ public abstract class Loader { protected void autoDiscoverTypes(ResultSet rs) { throw new AssertionFailure("Auto discover types not supported in this loader"); - + } private synchronized ResultSet wrapResultSetIfEnabled(final ResultSet rs, final SessionImplementor session) { @@ -2028,13 +1996,13 @@ public abstract class Loader { // potential deadlock issues due to nature of code. if ( session.getFactory().getSettings().isWrapResultSetsEnabled() ) { try { - log.debug("Wrapping result set [" + rs + "]"); + LOG.wrappingResultSet(rs); return session.getFactory() .getSettings() .getJdbcSupport().wrap( rs, retreiveColumnNameToIndexCache( rs ) ); } catch(SQLException e) { - log.info("Error wrapping result set", e); + LOG.info(LOG.unableToWrapResultSet(), e); return rs; } } @@ -2045,7 +2013,7 @@ public abstract class Loader { private ColumnNameCache retreiveColumnNameToIndexCache(ResultSet rs) throws SQLException { if ( columnNameCache == null ) { - log.trace("Building columnName->columnIndex cache"); + LOG.buildingColumnIndexByNameCache(); columnNameCache = new ColumnNameCache( rs.getMetaData().getColumnCount() ); } @@ -2066,13 +2034,8 @@ public abstract class Loader { final Serializable optionalIdentifier, final EntityPersister persister, LockOptions lockOptions) throws HibernateException { - - if ( log.isDebugEnabled() ) { - log.debug( - "loading entity: " + - MessageHelper.infoString( persister, id, identifierType, getFactory() ) - ); - } + + if (LOG.isDebugEnabled()) LOG.loadingEntity(MessageHelper.infoString(persister, id, identifierType, getFactory())); List result; try { @@ -2089,16 +2052,16 @@ public abstract class Loader { final Loadable[] persisters = getEntityPersisters(); throw factory.getSQLExceptionHelper().convert( sqle, - "could not load an entity: " + + "could not load an entity: " + MessageHelper.infoString( persisters[persisters.length-1], id, identifierType, getFactory() ), getSQLString() ); } - log.debug("done entity load"); - + LOG.loadingEntityDone(); + return result; - + } /** @@ -2112,10 +2075,8 @@ public abstract class Loader { final Type keyType, final Type indexType, final EntityPersister persister) throws HibernateException { - - if ( log.isDebugEnabled() ) { - log.debug( "loading collection element by index" ); - } + + LOG.loadingCollectionElementByIndex(); List result; try { @@ -2136,10 +2097,10 @@ public abstract class Loader { ); } - log.debug("done entity load"); - + LOG.loadingEntityDone(); + return result; - + } /** @@ -2157,12 +2118,7 @@ public abstract class Loader { final EntityPersister persister, LockOptions lockOptions) throws HibernateException { - if ( log.isDebugEnabled() ) { - log.debug( - "batch loading entity: " + - MessageHelper.infoString(persister, ids, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.batchLoadingEntity(MessageHelper.infoString(persister, ids, getFactory())); Type[] types = new Type[ids.length]; Arrays.fill( types, idType ); @@ -2180,14 +2136,14 @@ public abstract class Loader { catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, - "could not load an entity batch: " + + "could not load an entity batch: " + MessageHelper.infoString( getEntityPersisters()[0], ids, getFactory() ), getSQLString() ); } - log.debug("done entity batch load"); - + LOG.batchLoadingEntityDone(); + return result; } @@ -2200,31 +2156,28 @@ public abstract class Loader { final Serializable id, final Type type) throws HibernateException { - if ( log.isDebugEnabled() ) { - log.debug( - "loading collection: "+ - MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.loadingCollection(MessageHelper.collectionInfoString(getCollectionPersisters()[0], + id, + getFactory())); Serializable[] ids = new Serializable[]{id}; try { - doQueryAndInitializeNonLazyCollections( + doQueryAndInitializeNonLazyCollections( session, new QueryParameters( new Type[]{type}, ids, ids ), - true + true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, - "could not initialize a collection: " + + "could not initialize a collection: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ), getSQLString() ); } - - log.debug("done loading collection"); + + LOG.loadingCollectionDone(); } @@ -2236,32 +2189,29 @@ public abstract class Loader { final Serializable[] ids, final Type type) throws HibernateException { - if ( log.isDebugEnabled() ) { - log.debug( - "batch loading collection: "+ - MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.batchLoadingCollection(MessageHelper.collectionInfoString(getCollectionPersisters()[0], + ids, + getFactory())); Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); try { - doQueryAndInitializeNonLazyCollections( + doQueryAndInitializeNonLazyCollections( session, new QueryParameters( idTypes, ids, ids ), - true + true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, - "could not initialize a collection batch: " + + "could not initialize a collection batch: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); } - - log.debug("done batch load"); + + LOG.batchLoadingCollectionDone(); } @@ -2281,13 +2231,13 @@ public abstract class Loader { try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ), - true + true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, - "could not load collection by subselect: " + + "could not load collection by subselect: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); @@ -2304,7 +2254,7 @@ public abstract class Loader { final Set querySpaces, final Type[] resultTypes) throws HibernateException { - final boolean cacheable = factory.getSettings().isQueryCacheEnabled() && + final boolean cacheable = factory.getSettings().isQueryCacheEnabled() && queryParameters.isCacheable(); if ( cacheable ) { @@ -2320,41 +2270,37 @@ public abstract class Loader { } private List listUsingQueryCache( - final SessionImplementor session, - final QueryParameters queryParameters, - final Set querySpaces, + final SessionImplementor session, + final QueryParameters queryParameters, + final Set querySpaces, final Type[] resultTypes) { - + QueryCache queryCache = factory.getQueryCache( queryParameters.getCacheRegion() ); - + QueryKey key = generateQueryKey( session, queryParameters ); - if ( querySpaces == null || querySpaces.size() == 0 ) { - log.trace( "unexpected querySpaces is "+( querySpaces == null ? "null" : "empty" ) ); - } - else { - log.trace( "querySpaces is "+querySpaces.toString() ); - } + if (querySpaces == null || querySpaces.size() == 0) LOG.unexpectedQuerySpaces(querySpaces == null ? querySpaces : LOG.empty()); + else LOG.querySpaces(querySpaces.toString()); List result = getResultFromQueryCache( - session, - queryParameters, + session, + queryParameters, querySpaces, - resultTypes, - queryCache, - key + resultTypes, + queryCache, + key ); if ( result == null ) { result = doList( session, queryParameters, key.getResultTransformer() ); putResultInQueryCache( - session, - queryParameters, + session, + queryParameters, resultTypes, - queryCache, - key, - result + queryCache, + key, + result ); } @@ -2464,7 +2410,7 @@ public abstract class Loader { boolean put = queryCache.put( key, key.getResultTransformer().getCachedResultTypes( resultTypes ), - result, + result, queryParameters.isNaturalKeyLookup(), session ); @@ -2636,8 +2582,138 @@ public abstract class Loader { return factory; } - public String toString() { + @Override + 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 d3d49b5485..d65744a7d4 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,13 +24,16 @@ */ package org.hibernate.loader.collection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.MappingException; -import org.hibernate.engine.SessionFactoryImplementor; 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. @@ -43,43 +46,55 @@ import org.hibernate.persister.collection.QueryableCollection; */ public class BasicCollectionLoader extends CollectionLoader { - private static final Logger log = LoggerFactory.getLogger(BasicCollectionLoader.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicCollectionLoader.class.getPackage().getName()); public BasicCollectionLoader( - QueryableCollection collectionPersister, - SessionFactoryImplementor session, + QueryableCollection collectionPersister, + SessionFactoryImplementor session, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( collectionPersister, 1, session, loadQueryInfluencers ); } public BasicCollectionLoader( - QueryableCollection collectionPersister, - int batchSize, - SessionFactoryImplementor factory, + QueryableCollection collectionPersister, + int batchSize, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( collectionPersister, batchSize, null, factory, loadQueryInfluencers ); } - + protected BasicCollectionLoader( - QueryableCollection collectionPersister, - int batchSize, - String subquery, - SessionFactoryImplementor factory, + QueryableCollection collectionPersister, + int batchSize, + String subquery, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { super( collectionPersister, factory, loadQueryInfluencers ); - + JoinWalker walker = new BasicCollectionJoinWalker( - collectionPersister, - batchSize, - subquery, - factory, + collectionPersister, + batchSize, + subquery, + factory, loadQueryInfluencers ); initFromWalker( walker ); postInstantiate(); - log.debug( "Static select for collection " + collectionPersister.getRole() + ": " + getSQLString() ); + LOG.staticSelectForCollection(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 20fe495e71..6640d94859 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,13 +24,16 @@ */ package org.hibernate.loader.collection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.jboss.logging.Logger.Level.DEBUG; import org.hibernate.MappingException; -import org.hibernate.engine.SessionFactoryImplementor; 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
        @@ -43,42 +46,54 @@ import org.hibernate.persister.collection.QueryableCollection; */ public class OneToManyLoader extends CollectionLoader { - private static final Logger log = LoggerFactory.getLogger(OneToManyLoader.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OneToManyLoader.class.getPackage().getName()); public OneToManyLoader( - QueryableCollection oneToManyPersister, - SessionFactoryImplementor session, + QueryableCollection oneToManyPersister, + SessionFactoryImplementor session, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( oneToManyPersister, 1, session, loadQueryInfluencers ); } public OneToManyLoader( - QueryableCollection oneToManyPersister, - int batchSize, - SessionFactoryImplementor factory, + QueryableCollection oneToManyPersister, + int batchSize, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( oneToManyPersister, batchSize, null, factory, loadQueryInfluencers ); } public OneToManyLoader( - QueryableCollection oneToManyPersister, - int batchSize, - String subquery, - SessionFactoryImplementor factory, + QueryableCollection oneToManyPersister, + int batchSize, + String subquery, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { super( oneToManyPersister, factory, loadQueryInfluencers ); - + JoinWalker walker = new OneToManyJoinWalker( - oneToManyPersister, - batchSize, - subquery, - factory, + oneToManyPersister, + batchSize, + subquery, + factory, loadQueryInfluencers ); initFromWalker( walker ); postInstantiate(); - log.debug( "Static select for one-to-many " + oneToManyPersister.getRole() + ": " + getSQLString() ); + LOG.staticSelectForOneToMany(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 4ab4d8830c..0ca4ce2440 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,35 +24,38 @@ */ 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; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.HashMap; - import org.hibernate.HibernateException; -import org.hibernate.engine.query.sql.NativeSQLQueryReturn; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +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. *

        * This support is built on top of the notion of "custom queries"... - * + * * @author Gavin King * @author Max Andersen * @author Steve Ebersole */ public class SQLCustomQuery implements CustomQuery { - public static final Logger log = LoggerFactory.getLogger( SQLCustomQuery.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLCustomQuery.class.getPackage().getName()); private final String sql; private final Set querySpaces = new HashSet(); @@ -82,7 +85,7 @@ public class SQLCustomQuery implements CustomQuery { final Collection additionalQuerySpaces, final SessionFactoryImplementor factory) throws HibernateException { - log.trace( "starting processing of sql query [" + sqlQuery + "]" ); + LOG.processingSqlQery(sqlQuery); SQLQueryReturnProcessor processor = new SQLQueryReturnProcessor(queryReturns, factory); SQLQueryReturnProcessor.ResultAliasContext aliasContext = processor.process(); @@ -252,4 +255,15 @@ 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 007d463429..fe0bc3dfd9 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,43 +24,45 @@ */ 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.MappingException; -import org.hibernate.loader.custom.Return; -import org.hibernate.loader.custom.ScalarReturn; -import org.hibernate.loader.custom.RootReturn; +import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.engine.query.sql.NativeSQLQueryCollectionReturn; +import org.hibernate.engine.query.sql.NativeSQLQueryJoinReturn; +import org.hibernate.engine.query.sql.NativeSQLQueryNonScalarReturn; +import org.hibernate.engine.query.sql.NativeSQLQueryReturn; +import org.hibernate.engine.query.sql.NativeSQLQueryRootReturn; +import org.hibernate.engine.query.sql.NativeSQLQueryScalarReturn; +import org.hibernate.loader.BasicLoader; +import org.hibernate.loader.CollectionAliases; +import org.hibernate.loader.ColumnEntityAliases; +import org.hibernate.loader.DefaultEntityAliases; +import org.hibernate.loader.EntityAliases; +import org.hibernate.loader.GeneratedCollectionAliases; +import org.hibernate.loader.custom.CollectionFetchReturn; import org.hibernate.loader.custom.CollectionReturn; import org.hibernate.loader.custom.ColumnCollectionAliases; -import org.hibernate.loader.custom.FetchReturn; -import org.hibernate.loader.custom.CollectionFetchReturn; -import org.hibernate.loader.custom.NonScalarReturn; import org.hibernate.loader.custom.EntityFetchReturn; -import org.hibernate.loader.BasicLoader; -import org.hibernate.loader.EntityAliases; -import org.hibernate.loader.DefaultEntityAliases; -import org.hibernate.loader.ColumnEntityAliases; -import org.hibernate.loader.CollectionAliases; -import org.hibernate.loader.GeneratedCollectionAliases; -import org.hibernate.engine.query.sql.NativeSQLQueryReturn; -import org.hibernate.engine.query.sql.NativeSQLQueryCollectionReturn; -import org.hibernate.engine.query.sql.NativeSQLQueryScalarReturn; -import org.hibernate.engine.query.sql.NativeSQLQueryNonScalarReturn; -import org.hibernate.engine.query.sql.NativeSQLQueryJoinReturn; -import org.hibernate.engine.query.sql.NativeSQLQueryRootReturn; -import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.loader.custom.FetchReturn; +import org.hibernate.loader.custom.NonScalarReturn; +import org.hibernate.loader.custom.Return; +import org.hibernate.loader.custom.RootReturn; +import org.hibernate.loader.custom.ScalarReturn; import org.hibernate.persister.collection.SQLLoadableCollection; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.SQLLoadable; import org.hibernate.type.EntityType; import org.hibernate.type.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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} @@ -74,7 +76,8 @@ import org.slf4j.LoggerFactory; */ public class SQLQueryReturnProcessor { - public static final Logger log = LoggerFactory.getLogger( SQLQueryReturnProcessor.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SQLQueryReturnProcessor.class.getPackage().getName()); private NativeSQLQueryReturn[] queryReturns; @@ -384,7 +387,7 @@ public class SQLQueryReturnProcessor { private void addPersister(String alias, Map propertyResult, SQLLoadable persister) { alias2Persister.put( alias, persister ); String suffix = generateEntitySuffix(); - log.trace( "mapping alias [" + alias + "] to entity-suffix [" + suffix + "]" ); + LOG.mappingAliasToEntitySuffix(alias, suffix); alias2Suffix.put( alias, suffix ); entityPropertyResultMaps.put( alias, propertyResult ); } @@ -393,7 +396,7 @@ public class SQLQueryReturnProcessor { SQLLoadableCollection collectionPersister = ( SQLLoadableCollection ) factory.getCollectionPersister( role ); alias2CollectionPersister.put( alias, collectionPersister ); String suffix = generateCollectionSuffix(); - log.trace( "mapping alias [" + alias + "] to collection-suffix [" + suffix + "]" ); + LOG.mappingAliasToCollectionSuffix(alias, suffix); alias2CollectionSuffix.put( alias, suffix ); collectionPropertyResultMaps.put( alias, propertyResults ); @@ -522,4 +525,20 @@ public class SQLQueryReturnProcessor { // 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/AbstractEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/entity/AbstractEntityLoader.java index d279720990..20294cb84c 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/entity/AbstractEntityLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/entity/AbstractEntityLoader.java @@ -28,37 +28,33 @@ import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.LockOptions; +import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; -import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.loader.OuterJoinLoader; import org.hibernate.persister.entity.OuterJoinLoadable; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.Type; -public abstract class AbstractEntityLoader extends OuterJoinLoader +public abstract class AbstractEntityLoader extends OuterJoinLoader implements UniqueEntityLoader { - protected static final Logger log = LoggerFactory.getLogger(EntityLoader.class); protected final OuterJoinLoadable persister; protected final Type uniqueKeyType; protected final String entityName; public AbstractEntityLoader( - OuterJoinLoadable persister, - Type uniqueKeyType, - SessionFactoryImplementor factory, + OuterJoinLoadable persister, + Type uniqueKeyType, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) { super( factory, loadQueryInfluencers ); this.uniqueKeyType = uniqueKeyType; this.entityName = persister.getEntityName(); this.persister = persister; - + } /** @@ -82,18 +78,18 @@ public abstract class AbstractEntityLoader extends OuterJoinLoader Object optionalObject, Serializable optionalId, LockOptions lockOptions) { - + List list = loadEntity( - session, - id, - uniqueKeyType, - optionalObject, - entityName, - optionalId, + session, + id, + uniqueKeyType, + optionalObject, + entityName, + optionalId, persister, lockOptions ); - + if ( list.size()==1 ) { return list.get(0); } @@ -113,15 +109,17 @@ public abstract class AbstractEntityLoader extends OuterJoinLoader ); } } - + } - protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) + @Override + protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { return row[row.length-1]; } - protected boolean isSingleRowLoader() { + @Override + protected boolean isSingleRowLoader() { return true; } 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 38ae052239..9f4d54e526 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 @@ -26,35 +26,34 @@ package org.hibernate.loader.entity; import org.hibernate.MappingException; import org.hibernate.engine.CascadingAction; -import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.LoadQueryInfluencers; +import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.loader.JoinWalker; import org.hibernate.persister.entity.OuterJoinLoadable; public class CascadeEntityLoader extends AbstractEntityLoader { - + public CascadeEntityLoader( OuterJoinLoadable persister, CascadingAction action, SessionFactoryImplementor factory) throws MappingException { super( - persister, - persister.getIdentifierType(), + persister, + persister.getIdentifierType(), factory, LoadQueryInfluencers.NONE ); JoinWalker walker = new CascadeEntityJoinWalker( - persister, + persister, action, factory ); initFromWalker( walker ); postInstantiate(); - - log.debug( "Static select for action " + action + " on entity " + entityName + ": " + getSQLString() ); + LOG.staticSelectForAction(action, 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 015a67de31..991c33d93e 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,18 +24,16 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.MappingException; +import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; -import org.hibernate.engine.LoadQueryInfluencers; import org.hibernate.loader.JoinWalker; import org.hibernate.loader.OuterJoinLoader; import org.hibernate.persister.collection.QueryableCollection; @@ -43,15 +41,20 @@ 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; /** - * + * * * @author Gavin King */ public class CollectionElementLoader extends OuterJoinLoader { - - private static final Logger log = LoggerFactory.getLogger(CollectionElementLoader.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CollectionElementLoader.class.getPackage().getName()); private final OuterJoinLoadable persister; private final Type keyType; @@ -60,7 +63,7 @@ public class CollectionElementLoader extends OuterJoinLoader { public CollectionElementLoader( QueryableCollection collectionPersister, - SessionFactoryImplementor factory, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { super( factory, loadQueryInfluencers ); @@ -68,38 +71,38 @@ public class CollectionElementLoader extends OuterJoinLoader { this.indexType = collectionPersister.getIndexType(); this.persister = (OuterJoinLoadable) collectionPersister.getElementPersister(); this.entityName = persister.getEntityName(); - + JoinWalker walker = new EntityJoinWalker( - persister, - ArrayHelper.join( - collectionPersister.getKeyColumnNames(), + persister, + ArrayHelper.join( + collectionPersister.getKeyColumnNames(), collectionPersister.getIndexColumnNames() ), - 1, - LockMode.NONE, - factory, + 1, + LockMode.NONE, + factory, loadQueryInfluencers ); initFromWalker( walker ); postInstantiate(); - - log.debug( "Static select for entity " + entityName + ": " + getSQLString() ); + + LOG.staticSelectForEntity(entityName, getSQLString()); } - public Object loadElement(SessionImplementor session, Object key, Object index) + public Object loadElement(SessionImplementor session, Object key, Object index) throws HibernateException { - + List list = loadEntity( - session, + session, key, index, - keyType, + keyType, indexType, persister ); - + if ( list.size()==1 ) { return list.get(0); } @@ -114,10 +117,11 @@ public class CollectionElementLoader extends OuterJoinLoader { throw new HibernateException("More than one row was found"); } } - + } - protected Object getResultColumnOrRow( + @Override + protected Object getResultColumnOrRow( Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) @@ -125,8 +129,20 @@ public class CollectionElementLoader extends OuterJoinLoader { return row[row.length-1]; } - protected boolean isSingleRowLoader() { + @Override + 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 fee30dcf13..b8d7409ac5 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 @@ -42,14 +42,14 @@ import org.hibernate.type.Type; * @author Gavin King */ public class EntityLoader extends AbstractEntityLoader { - + private final boolean batchLoader; private final int[][] compositeKeyManyToOneTargetIndices; - + public EntityLoader( - OuterJoinLoadable persister, + OuterJoinLoadable persister, LockMode lockMode, - SessionFactoryImplementor factory, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( persister, 1, lockMode, factory, loadQueryInfluencers ); } @@ -63,18 +63,18 @@ public class EntityLoader extends AbstractEntityLoader { } public EntityLoader( - OuterJoinLoadable persister, - int batchSize, + OuterJoinLoadable persister, + int batchSize, LockMode lockMode, - SessionFactoryImplementor factory, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { this( persister, - persister.getIdentifierColumnNames(), - persister.getIdentifierType(), + persister.getIdentifierColumnNames(), + persister.getIdentifierType(), batchSize, lockMode, - factory, + factory, loadQueryInfluencers ); } @@ -97,21 +97,21 @@ public class EntityLoader extends AbstractEntityLoader { } public EntityLoader( - OuterJoinLoadable persister, - String[] uniqueKey, - Type uniqueKeyType, - int batchSize, + OuterJoinLoadable persister, + String[] uniqueKey, + Type uniqueKeyType, + int batchSize, LockMode lockMode, - SessionFactoryImplementor factory, + SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { super( persister, uniqueKeyType, factory, loadQueryInfluencers ); EntityJoinWalker walker = new EntityJoinWalker( - persister, - uniqueKey, - batchSize, - lockMode, - factory, + persister, + uniqueKey, + batchSize, + lockMode, + factory, loadQueryInfluencers ); initFromWalker( walker ); @@ -119,8 +119,8 @@ public class EntityLoader extends AbstractEntityLoader { postInstantiate(); batchLoader = batchSize > 1; - - log.debug( "Static select for entity " + entityName + " [" + lockMode + "]: " + getSQLString() ); + + LOG.staticSelectForEntity(entityName, lockMode, getSQLString()); } public EntityLoader( @@ -147,11 +147,7 @@ public class EntityLoader extends AbstractEntityLoader { batchLoader = batchSize > 1; - log.debug( - "Static select for entity " + entityName + - " [" + lockOptions.getLockMode() + ":" + lockOptions.getTimeOut() + "]: " - + getSQLString() - ); + LOG.staticSelectForEntity(entityName, lockOptions.getLockMode(), lockOptions.getTimeOut(), getSQLString()); } @@ -159,11 +155,13 @@ public class EntityLoader extends AbstractEntityLoader { return load( session, key, null, null, LockOptions.NONE ); } - protected boolean isSingleRowLoader() { + @Override + protected boolean isSingleRowLoader() { return !batchLoader; } - public int[][] getCompositeKeyManyToOneTargetIndices() { + @Override + public int[][] getCompositeKeyManyToOneTargetIndices() { return compositeKeyManyToOneTargetIndices; } } \ No newline at end of file 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 cabd43a6bd..5c6a0a8f0e 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,6 +23,7 @@ */ 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; @@ -31,7 +32,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import org.hibernate.AssertionFailure; import org.hibernate.FetchMode; import org.hibernate.HibernateException; @@ -70,7 +70,6 @@ import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Table; import org.hibernate.metadata.CollectionMetadata; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.persister.entity.Loadable; import org.hibernate.persister.entity.PropertyMapping; import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.Alias; @@ -85,8 +84,10 @@ import org.hibernate.type.Type; import org.hibernate.util.ArrayHelper; import org.hibernate.util.FilterHelper; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** @@ -98,7 +99,11 @@ import org.slf4j.LoggerFactory; */ public abstract class AbstractCollectionPersister implements CollectionMetadata, SQLLoadableCollection { - // TODO: encapsulate the protected instance variables! + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractCollectionPersister.class.getPackage().getName()); + + // TODO: encapsulate the protected instance variables! private final String role; @@ -118,14 +123,14 @@ public abstract class AbstractCollectionPersister private final boolean hasOrder; protected final boolean hasWhere; private final int baseIndex; - + private final String nodeName; private final String elementNodeName; private final String indexNodeName; protected final boolean indexContainsFormula; protected final boolean elementIsPureFormula; - + //types private final Type keyType; private final Type indexType; @@ -149,7 +154,7 @@ public abstract class AbstractCollectionPersister protected final String[] indexColumnAliases; protected final String[] elementColumnAliases; protected final String[] keyColumnAliases; - + protected final String identifierColumnName; private final String identifierColumnAlias; //private final String unquotedIdentifierColumnName; @@ -186,7 +191,7 @@ public abstract class AbstractCollectionPersister private final CollectionRegionAccessStrategy cacheAccessStrategy; private final CollectionType collectionType; private CollectionInitializer initializer; - + private final CacheEntryStructure cacheEntryStructure; // dynamic filters for the collection @@ -216,8 +221,6 @@ public abstract class AbstractCollectionPersister private Map collectionPropertyColumnAliases = new HashMap(); private Map collectionPropertyColumnNames = new HashMap(); - private static final Logger log = LoggerFactory.getLogger( AbstractCollectionPersister.class ); - public AbstractCollectionPersister( final Collection collection, final CollectionRegionAccessStrategy cacheAccessStrategy, @@ -234,7 +237,7 @@ public abstract class AbstractCollectionPersister else { cacheEntryStructure = new UnstructuredCacheEntry(); } - + dialect = factory.getDialect(); sqlExceptionHelper = factory.getSQLExceptionHelper(); collectionType = collection.getCollectionType(); @@ -253,11 +256,11 @@ public abstract class AbstractCollectionPersister isPrimitiveArray = collection.isPrimitiveArray(); isArray = collection.isArray(); subselectLoadable = collection.isSubselectLoadable(); - - qualifiedTableName = table.getQualifiedName( + + qualifiedTableName = table.getQualifiedName( dialect, factory.getSettings().getDefaultCatalogName(), - factory.getSettings().getDefaultSchemaName() + factory.getSettings().getDefaultSchemaName() ); int spacesSize = 1 + collection.getSynchronizedTables().size(); @@ -283,7 +286,7 @@ public abstract class AbstractCollectionPersister batchSize = batch; isVersioned = collection.isOptimisticLocked(); - + // KEY keyType = collection.getKey().getType(); @@ -299,7 +302,7 @@ public abstract class AbstractCollectionPersister keyColumnAliases[k] = col.getAlias(dialect,collection.getOwner().getRootTable()); k++; } - + //unquotedKeyColumnNames = StringHelper.unQuote(keyColumnAliases); //ELEMENT @@ -312,11 +315,11 @@ public abstract class AbstractCollectionPersister elemNode = cfg.getClassMapping(entityName).getNodeName(); } // NativeSQL: collect element column and auto-aliases - + } else { elementPersister = null; - } + } elementNodeName = elemNode; int elementSpan = collection.getElement().getColumnSpan(); @@ -357,7 +360,7 @@ public abstract class AbstractCollectionPersister j++; } elementIsPureFormula = isPureFormula; - + //workaround, for backward compatibility of sets with no //not-null columns, assume all columns are used in the //row locator SQL @@ -399,10 +402,10 @@ public abstract class AbstractCollectionPersister i++; } indexContainsFormula = hasFormula; - baseIndex = indexedCollection.isList() ? + baseIndex = indexedCollection.isList() ? ( (List) indexedCollection ).getBaseIndex() : 0; - indexNodeName = indexedCollection.getIndexNodeName(); + indexNodeName = indexedCollection.getIndexNodeName(); } else { @@ -416,7 +419,7 @@ public abstract class AbstractCollectionPersister baseIndex = 0; indexNodeName = null; } - + hasIdentifier = collection.isIdentified(); if (hasIdentifier) { if ( collection.isOneToMany() ) { @@ -444,9 +447,9 @@ public abstract class AbstractCollectionPersister //unquotedIdentifierColumnName = null; identifierGenerator = null; } - + //GENERATE THE SQL: - + //sqlSelectString = sqlSelectString(); //sqlSelectRowString = sqlSelectRowString(); @@ -502,9 +505,9 @@ public abstract class AbstractCollectionPersister sqlDetectRowByIndexString = generateDetectRowByIndexString(); sqlDetectRowByElementString = generateDetectRowByElementString(); sqlSelectRowByIndexString = generateSelectRowByIndexString(); - + logStaticSQL(); - + isLazy = collection.isLazy(); isExtraLazy = collection.isExtraLazy(); @@ -519,19 +522,19 @@ public abstract class AbstractCollectionPersister } if ( elementType.isComponentType() ) { - elementPropertyMapping = new CompositeElementPropertyMapping( + elementPropertyMapping = new CompositeElementPropertyMapping( elementColumnNames, elementColumnReaders, elementColumnReaderTemplates, elementFormulaTemplates, (CompositeType) elementType, - factory + factory ); } else if ( !elementType.isEntityType() ) { - elementPropertyMapping = new ElementPropertyMapping( + elementPropertyMapping = new ElementPropertyMapping( elementColumnNames, - elementType + elementType ); } else { @@ -539,9 +542,9 @@ public abstract class AbstractCollectionPersister elementPropertyMapping = (PropertyMapping) elementPersister; } else { - elementPropertyMapping = new ElementPropertyMapping( + elementPropertyMapping = new ElementPropertyMapping( elementColumnNames, - elementType + elementType ); } } @@ -606,20 +609,12 @@ public abstract class AbstractCollectionPersister } protected void logStaticSQL() { - if ( log.isDebugEnabled() ) { - 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() ); - } + 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()); } } @@ -650,26 +645,26 @@ public abstract class AbstractCollectionPersister if ( !isSubselectLoadable() ) { return null; } - + final PersistenceContext persistenceContext = session.getPersistenceContext(); - + SubselectFetch subselect = persistenceContext.getBatchFetchQueue() .getSubselect( new EntityKey( key, getOwnerEntityPersister(), session.getEntityMode() ) ); - + if (subselect == null) { return null; } else { - + // Take care of any entities that might have - // been evicted! + // been evicted! Iterator iter = subselect.getResult().iterator(); while ( iter.hasNext() ) { if ( !persistenceContext.containsEntity( (EntityKey) iter.next() ) ) { iter.remove(); } - } - + } + // Run a subquery loader return createSubselectInitializer( subselect, session ); } @@ -758,12 +753,12 @@ public abstract class AbstractCollectionPersister return elementClass; } - public Object readElement(ResultSet rs, Object owner, String[] aliases, SessionImplementor session) + public Object readElement(ResultSet rs, Object owner, String[] aliases, SessionImplementor session) throws HibernateException, SQLException { return getElementType().nullSafeGet( rs, aliases, session, owner ); } - public Object readIndex(ResultSet rs, String[] aliases, SessionImplementor session) + public Object readIndex(ResultSet rs, String[] aliases, SessionImplementor session) throws HibernateException, SQLException { Object index = getIndexType().nullSafeGet( rs, aliases, session, null ); if ( index == null ) { @@ -780,7 +775,7 @@ public abstract class AbstractCollectionPersister return index; } - public Object readIdentifier(ResultSet rs, String alias, SessionImplementor session) + public Object readIdentifier(ResultSet rs, String alias, SessionImplementor session) throws HibernateException, SQLException { Object id = getIdentifierType().nullSafeGet( rs, alias, session, null ); if ( id == null ) { @@ -789,7 +784,7 @@ public abstract class AbstractCollectionPersister return id; } - public Object readKey(ResultSet rs, String[] aliases, SessionImplementor session) + public Object readKey(ResultSet rs, String[] aliases, SessionImplementor session) throws HibernateException, SQLException { return getKeyType().nullSafeGet( rs, aliases, session, null ); } @@ -799,7 +794,7 @@ public abstract class AbstractCollectionPersister */ protected int writeKey(PreparedStatement st, Serializable key, int i, SessionImplementor session) throws HibernateException, SQLException { - + if ( key == null ) { throw new NullPointerException( "null key for collection: " + role ); //an assertion } @@ -863,7 +858,7 @@ public abstract class AbstractCollectionPersister */ public int writeIdentifier(PreparedStatement st, Object id, int i, SessionImplementor session) throws HibernateException, SQLException { - + getIdentifierType().nullSafeSet( st, id, i, session ); return i + 1; } @@ -901,7 +896,7 @@ public abstract class AbstractCollectionPersister return null; } } - + public String getIdentifierColumnName() { if ( hasIdentifier ) { return identifierColumnName; @@ -924,7 +919,7 @@ public abstract class AbstractCollectionPersister } protected String generateSelectSizeString(boolean isIntegerIndexed) { - String selectValue = isIntegerIndexed ? + String selectValue = isIntegerIndexed ? "max(" + getIndexColumnNames()[0] + ") + 1": //lists, arrays "count(" + getElementColumnNames()[0] + ")"; //sets, maps, bags return new SimpleSelect(dialect) @@ -1023,7 +1018,7 @@ public abstract class AbstractCollectionPersister public String[] getElementColumnNames(String alias) { return qualify(alias, elementColumnNames, elementFormulaTemplates); } - + private static String[] qualify(String alias, String[] columnNames, String[] formulaTemplates) { int span = columnNames.length; String[] result = new String[span]; @@ -1066,12 +1061,7 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowDeleteEnabled() ) { - if ( log.isDebugEnabled() ) { - log.debug( - "Deleting collection: " + - MessageHelper.collectionInfoString( this, id, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.deletingCollection(MessageHelper.collectionInfoString(this, id, getFactory())); // Remove all the old entries @@ -1113,14 +1103,12 @@ public abstract class AbstractCollectionPersister } } - if ( log.isDebugEnabled() ) { - log.debug( "done deleting collection" ); - } + LOG.deletingCollectionDone(); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( sqle, - "could not delete collection: " + + "could not delete collection: " + MessageHelper.collectionInfoString( this, id, getFactory() ), getSQLDeleteString() ); @@ -1135,12 +1123,7 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowInsertEnabled() ) { - if ( log.isDebugEnabled() ) { - log.debug( - "Inserting collection: " + - MessageHelper.collectionInfoString( this, id, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.insertingCollection(MessageHelper.collectionInfoString(this, id, getFactory())); try { //create all the new entries @@ -1209,28 +1192,21 @@ public abstract class AbstractCollectionPersister i++; } - if ( log.isDebugEnabled() ) { - log.debug( "done inserting collection: " + count + " rows inserted" ); - } + LOG.insertingCollectionDone(count); - } - else { - if ( log.isDebugEnabled() ) { - log.debug( "collection was empty" ); - } - } + } else LOG.collectionWasEmpty(); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( sqle, - "could not insert collection: " + + "could not insert collection: " + MessageHelper.collectionInfoString( this, id, getFactory() ), getSQLInsertRowString() ); } } } - + protected boolean isRowDeleteEnabled() { return true; } @@ -1240,15 +1216,10 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowDeleteEnabled() ) { - if ( log.isDebugEnabled() ) { - log.debug( - "Deleting rows of collection: " + - MessageHelper.collectionInfoString( this, id, getFactory() ) - ); - } - + if (LOG.isDebugEnabled()) LOG.deletingCollectionRows(MessageHelper.collectionInfoString(this, id, getFactory())); + boolean deleteByIndex = !isOneToMany() && hasIndex && !indexContainsFormula; - + try { //delete all the deleted entries Iterator deletes = collection.getDeletes( this, !deleteByIndex ); @@ -1309,28 +1280,21 @@ public abstract class AbstractCollectionPersister } } - if ( log.isDebugEnabled() ) { - log.debug( "done deleting collection rows: " + count + " deleted" ); - } + LOG.deletingCollectionRowsDone(count); } - } - else { - if ( log.isDebugEnabled() ) { - log.debug( "no rows to delete" ); - } - } + } else LOG.noRowsToDelete(); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( sqle, - "could not delete collection rows: " + + "could not delete collection rows: " + MessageHelper.collectionInfoString( this, id, getFactory() ), getSQLDeleteRowString() ); } } } - + protected boolean isRowInsertEnabled() { return true; } @@ -1340,12 +1304,7 @@ public abstract class AbstractCollectionPersister if ( !isInverse && isRowInsertEnabled() ) { - if ( log.isDebugEnabled() ) { - log.debug( - "Inserting rows of collection: " + - MessageHelper.collectionInfoString( this, id, getFactory() ) - ); - } + if (LOG.isDebugEnabled()) LOG.insertingCollectionRows(MessageHelper.collectionInfoString(this, id, getFactory())); try { //insert all the new entries @@ -1409,14 +1368,12 @@ public abstract class AbstractCollectionPersister } i++; } - if ( log.isDebugEnabled() ) { - log.debug( "done inserting rows: " + count + " inserted" ); - } + LOG.insertingCollectionRowsDone(count); } catch ( SQLException sqle ) { throw sqlExceptionHelper.convert( sqle, - "could not insert collection rows: " + + "could not insert collection rows: " + MessageHelper.collectionInfoString( this, id, getFactory() ), getSQLInsertRowString() ); @@ -1515,7 +1472,7 @@ public abstract class AbstractCollectionPersister if ( elementPersister == null ) { throw new AssertionFailure( "not an association" ); } - return ( Loadable ) elementPersister; + return elementPersister; } public boolean isCollection() { @@ -1534,25 +1491,21 @@ public abstract class AbstractCollectionPersister protected abstract String generateInsertRowString(); - public void updateRows(PersistentCollection collection, Serializable id, SessionImplementor session) + public void updateRows(PersistentCollection collection, Serializable id, SessionImplementor session) throws HibernateException { if ( !isInverse && collection.isRowUpdatePossible() ) { - if ( log.isDebugEnabled() ) { - log.debug( "Updating rows of collection: " + role + "#" + id ); - } + LOG.updatingCollectionRows(role, id); //update all the modified entries int count = doUpdateRows( id, collection, session ); - if ( log.isDebugEnabled() ) { - log.debug( "done updating rows: " + count + " updated" ); - } + LOG.updatingCollectionRowsDone(count); } } - protected abstract int doUpdateRows(Serializable key, PersistentCollection collection, SessionImplementor session) + protected abstract int doUpdateRows(Serializable key, PersistentCollection collection, SessionImplementor session) throws HibernateException; public CollectionMetadata getCollectionMetadata() { @@ -1618,7 +1571,7 @@ public abstract class AbstractCollectionPersister public boolean isVersioned() { return isVersioned && getOwnerEntityPersister().isVersioned(); } - + public String getNodeName() { return nodeName; } @@ -1653,7 +1606,7 @@ public abstract class AbstractCollectionPersister public boolean isSubselectLoadable() { return subselectLoadable; } - + public boolean isMutable() { return isMutable; } @@ -1664,14 +1617,14 @@ public abstract class AbstractCollectionPersister if ( rawAliases == null ) { return null; } - + String result[] = new String[rawAliases.length]; for ( int i=0; i0 ) { - query.setParameter( - query.getNamedParameters()[0], - key, - persister.getKeyType() + query.setParameter( + query.getNamedParameters()[0], + key, + persister.getKeyType() ); } else { @@ -79,4 +76,16 @@ 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 ba5e71e7bd..422e9bdb05 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,6 +23,8 @@ */ 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; @@ -35,10 +37,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; import org.hibernate.FetchMode; @@ -111,6 +109,10 @@ 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 @@ -122,7 +124,8 @@ public abstract class AbstractEntityPersister implements OuterJoinLoadable, Queryable, ClassMetadata, UniqueKeyLoadable, SQLLoadable, LazyPropertyInitializer, PostInsertIdentityPersister, Lockable { - private static final Logger log = LoggerFactory.getLogger( AbstractEntityPersister.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractEntityPersister.class.getPackage().getName()); public static final String ENTITY_CLASS = "class"; @@ -293,12 +296,12 @@ public abstract class AbstractEntityPersister public String getDiscriminatorColumnReaders() { return DISCRIMINATOR_ALIAS; - } - + } + public String getDiscriminatorColumnReaderTemplate() { return DISCRIMINATOR_ALIAS; - } - + } + protected String getDiscriminatorAlias() { return DISCRIMINATOR_ALIAS; } @@ -383,7 +386,7 @@ public abstract class AbstractEntityPersister /** * The query that inserts a row, letting the database generate an id - * + * * @return The IDENTITY-based insertion query. */ protected String getSQLIdentityInsertString() { @@ -672,7 +675,7 @@ public abstract class AbstractEntityPersister aliases.add( thing.getAlias( factory.getDialect(), prop.getValue().getTable() ) ); columnsLazy.add( lazy ); columnSelectables.add( Boolean.valueOf( prop.isSelectable() ) ); - + readers[l] = col.getReadExpr( factory.getDialect() ); String readerTemplate = col.getTemplate( factory.getDialect(), factory.getSqlFunctionRegistry() ); readerTemplates[l] = readerTemplate; @@ -793,13 +796,7 @@ public abstract class AbstractEntityPersister throw new HibernateException( "entity is not associated with the session: " + id ); } - if ( log.isTraceEnabled() ) { - log.trace( - "initializing lazy properties of: " + - MessageHelper.infoString( this, id, getFactory() ) + - ", field access: " + fieldName - ); - } + if (LOG.isTraceEnabled()) LOG.initializingLazyProperties(MessageHelper.infoString(this, id, getFactory()), fieldName); if ( hasCache() ) { CacheKey cacheKey = new CacheKey(id, getIdentifierType(), getEntityName(), session.getEntityMode(), getFactory() ); @@ -824,11 +821,9 @@ public abstract class AbstractEntityPersister final Serializable id, final EntityEntry entry) { - if ( !hasLazyProperties() ) { - throw new AssertionFailure("no lazy properties"); - } + if (!hasLazyProperties()) throw new AssertionFailure("no lazy properties"); - log.trace("initializing lazy properties from datastore"); + LOG.initializingLazyPropertiesFromDataStore(); try { @@ -867,7 +862,7 @@ public abstract class AbstractEntityPersister } } - log.trace( "done initializing lazy properties" ); + LOG.initializingLazyPropertiesDone(); return result; @@ -890,7 +885,7 @@ public abstract class AbstractEntityPersister final CacheEntry cacheEntry ) { - log.trace("initializing lazy properties from second-level cache"); + LOG.initializingLazyPropertiesFromSecondLevelCache(); Object result = null; Serializable[] disassembledValues = cacheEntry.getDisassembledState(); @@ -906,7 +901,7 @@ public abstract class AbstractEntityPersister } } - log.trace( "done initializing lazy properties" ); + LOG.initializingLazyPropertiesDone(); return result; } @@ -950,12 +945,12 @@ public abstract class AbstractEntityPersister public String[] getIdentifierColumnReaders() { return rootTableKeyColumnReaders; - } + } public String[] getIdentifierColumnReaderTemplates() { return rootTableKeyColumnReaderTemplates; - } - + } + protected int getIdentifierColumnSpan() { return identifierColumnSpan; } @@ -1084,9 +1079,7 @@ public abstract class AbstractEntityPersister public Object[] getDatabaseSnapshot(Serializable id, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "Getting current persistent state for: " + MessageHelper.infoString( this, id, getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.gettingCurrentPersistentState(MessageHelper.infoString(this, id, getFactory())); try { PreparedStatement ps = session.getJDBCContext().getConnectionManager().prepareSelectStatement( getSQLSnapshotSelectString() ); @@ -1287,13 +1280,7 @@ public abstract class AbstractEntityPersister } Object nextVersion = getVersionType().next( currentVersion, session ); - if ( log.isTraceEnabled() ) { - log.trace( - "Forcing version increment [" + MessageHelper.infoString( this, id, getFactory() ) + - "; " + getVersionType().toLoggableString( currentVersion, getFactory() ) + - " -> " + getVersionType().toLoggableString( nextVersion, getFactory() ) + "]" - ); - } + if (LOG.isTraceEnabled()) LOG.forcingVersionIncrement(MessageHelper.infoString( this, id, getFactory() ), getVersionType().toLoggableString( currentVersion, getFactory() ), getVersionType().toLoggableString( nextVersion, getFactory() )); // todo : cache this sql... String versionIncrementString = generateVersionIncrementUpdateString(); @@ -1342,9 +1329,7 @@ public abstract class AbstractEntityPersister */ public Object getCurrentVersion(Serializable id, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "Getting version: " + MessageHelper.infoString( this, id, getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.gettingVersion(MessageHelper.infoString(this, id, getFactory())); try { @@ -1410,7 +1395,7 @@ public abstract class AbstractEntityPersister SessionImplementor session) throws HibernateException { getLocker( lockMode ).lock( id, version, object, LockOptions.WAIT_FOREVER, session ); } - + public void lock( Serializable id, Object version, @@ -1554,10 +1539,10 @@ public abstract class AbstractEntityPersister public String[] getPropertyColumnNames(int i) { return propertyColumnNames[i]; } - + public String[] getPropertyColumnWriters(int i) { return propertyColumnWriters[i]; - } + } protected int getPropertyColumnSpan(int i) { return propertyColumnSpans[i]; @@ -1606,7 +1591,7 @@ public abstract class AbstractEntityPersister protected String[][] getSubclassPropertyColumnNameClosure() { return subclassPropertyColumnNameClosure; } - + public String[][] getSubclassPropertyColumnReaderClosure() { return subclassPropertyColumnReaderClosure; } @@ -2152,9 +2137,7 @@ public abstract class AbstractEntityPersister final SessionImplementor session, int index) throws SQLException, HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "Dehydrating entity: " + MessageHelper.infoString( this, id, getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.dehydratingEntity(MessageHelper.infoString(this, id, getFactory())); for ( int i = 0; i < entityMetamodel.getPropertySpan(); i++ ) { if ( includeProperty[i] && isPropertyOfTable( i, j ) ) { @@ -2191,9 +2174,7 @@ public abstract class AbstractEntityPersister final boolean allProperties, final SessionImplementor session) throws SQLException, HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "Hydrating entity: " + MessageHelper.infoString( this, id, getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.hydratingEntity(MessageHelper.infoString(this, id, getFactory())); final AbstractEntityPersister rootPersister = (AbstractEntityPersister) rootLoadable; @@ -2304,11 +2285,9 @@ public abstract class AbstractEntityPersister final Object object, final SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( "Inserting entity: " + getEntityName() + " (native id)" ); - if ( isVersioned() ) { - log.trace( "Version: " + Versioning.getVersion( fields, this ) ); - } + if (LOG.isTraceEnabled()) { + LOG.insertingEntityWithNativeId(getEntityName()); + if (isVersioned()) LOG.version(Versioning.getVersion(fields, this)); } Binder binder = new Binder() { @@ -2364,11 +2343,9 @@ public abstract class AbstractEntityPersister return; } - if ( log.isTraceEnabled() ) { - log.trace( "Inserting entity: " + MessageHelper.infoString( this, id, getFactory() ) ); - if ( j == 0 && isVersioned() ) { - log.trace( "Version: " + Versioning.getVersion( fields, this ) ); - } + if (LOG.isTraceEnabled()) { + LOG.insertingEntity(MessageHelper.infoString(this, id, getFactory())); + if (j == 0 && isVersioned()) LOG.version(Versioning.getVersion(fields, this)); } Expectation expectation = Expectations.appropriateExpectation( insertResultCheckStyles[j] ); @@ -2488,11 +2465,9 @@ public abstract class AbstractEntityPersister final boolean callable = isUpdateCallable( j ); final boolean useBatch = j == 0 && expectation.canBeBatched() && isBatchable(); //note: updates to joined tables can't be batched... - if ( log.isTraceEnabled() ) { - log.trace( "Updating entity: " + MessageHelper.infoString( this, id, getFactory() ) ); - if ( useVersion ) { - log.trace( "Existing version: " + oldVersion + " -> New version: " + fields[getVersionProperty()] ); - } + if (LOG.isTraceEnabled()) { + LOG.updatingEntity(MessageHelper.infoString(this, id, getFactory())); + if (useVersion) LOG.updateVersion(oldVersion, fields[getVersionProperty()]); } try { @@ -2594,17 +2569,13 @@ public abstract class AbstractEntityPersister final Expectation expectation = Expectations.appropriateExpectation( deleteResultCheckStyles[j] ); final boolean useBatch = j == 0 && isBatchable() && expectation.canBeBatched(); - if ( log.isTraceEnabled() ) { - log.trace( "Deleting entity: " + MessageHelper.infoString( this, id, getFactory() ) ); - if ( useVersion ) { - log.trace( "Version: " + version ); - } + if (LOG.isTraceEnabled()) { + LOG.deletingEntity(MessageHelper.infoString(this, id, getFactory())); + if (useVersion) LOG.version(version); } if ( isTableCascadeDeleteEnabled( j ) ) { - if ( log.isTraceEnabled() ) { - log.trace( "delete handled by foreign key constraint: " + getTableName( j ) ); - } + LOG.deleteHandledByForeignKeyConstraint(getTableName(j)); return; //EARLY EXIT! } @@ -2892,38 +2863,21 @@ public abstract class AbstractEntityPersister } protected void logStaticSQL() { - if ( log.isDebugEnabled() ) { - 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 ); - } + if (LOG.isDebugEnabled()) { + LOG.staticSqlForEntity(getEntityName()); + if (sqlLazySelectString != null) LOG.lazySelect(sqlLazySelectString); + if (sqlVersionSelectString != null) LOG.versionSelect(sqlVersionSelectString); + if (sqlSnapshotSelectString != null) LOG.snapshotSelect(sqlSnapshotSelectString); for ( int j = 0; j < getTableSpan(); j++ ) { - log.debug( " Insert " + j + ": " + getSQLInsertStrings()[j] ); - log.debug( " Update " + j + ": " + getSQLUpdateStrings()[j] ); - log.debug( " Delete " + j + ": " + getSQLDeleteStrings()[j] ); - - } - 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 ); + LOG.insert(j, getSQLInsertStrings()[j]); + LOG.update(j, getSQLUpdateStrings()[j]); + LOG.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); } } @@ -3187,7 +3141,7 @@ public abstract class AbstractEntityPersister ); loaders.put( LockMode.OPTIMISTIC, createEntityLoader( LockMode.OPTIMISTIC) ); loaders.put( LockMode.OPTIMISTIC_FORCE_INCREMENT, createEntityLoader(LockMode.OPTIMISTIC_FORCE_INCREMENT) ); - + loaders.put( "merge", new CascadeEntityLoader( this, CascadingAction.MERGE, getFactory() ) @@ -3219,12 +3173,7 @@ public abstract class AbstractEntityPersister public Object load(Serializable id, Object optionalObject, LockOptions lockOptions, SessionImplementor session) throws HibernateException { - if ( log.isTraceEnabled() ) { - log.trace( - "Fetching entity: " + - MessageHelper.infoString( this, id, getFactory() ) - ); - } + if (LOG.isTraceEnabled()) LOG.fetchingEntity(MessageHelper.infoString(this, id, getFactory())); final UniqueEntityLoader loader = getAppropriateLoader(lockOptions, session ); return loader.load( id, optionalObject, session, lockOptions ); @@ -3394,10 +3343,10 @@ public abstract class AbstractEntityPersister } private void logDirtyProperties(int[] props) { - if ( log.isTraceEnabled() ) { + if (LOG.isTraceEnabled()) { for ( int i = 0; i < props.length; i++ ) { String propertyName = entityMetamodel.getProperties()[ props[i] ].getName(); - log.trace( StringHelper.qualify( getEntityName(), propertyName ) + " is dirty" ); + LOG.propertyIsDirty(StringHelper.qualify(getEntityName(), propertyName)); } } } @@ -3996,9 +3945,7 @@ public abstract class AbstractEntityPersister if ( !hasNaturalIdentifier() ) { throw new MappingException( "persistent class did not define a natural-id : " + MessageHelper.infoString( this ) ); } - if ( log.isTraceEnabled() ) { - log.trace( "Getting current natural-id snapshot state for: " + MessageHelper.infoString( this, id, getFactory() ) ); - } + if (LOG.isTraceEnabled()) LOG.gettingNaturalIdSnapshotState(MessageHelper.infoString(this, id, getFactory())); int[] naturalIdPropertyIndexes = getNaturalIdentifierProperties(); int naturalIdPropertyCount = naturalIdPropertyIndexes.length; @@ -4087,6 +4034,142 @@ 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 b140f757cd..d7369e38d7 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,12 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.engine.Mapping; @@ -40,6 +37,10 @@ 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. @@ -47,7 +48,9 @@ import org.hibernate.util.StringHelper; * @author Gavin King */ public abstract class AbstractPropertyMapping implements PropertyMapping { - private static final Logger log = LoggerFactory.getLogger( AbstractPropertyMapping.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractPropertyMapping.class.getPackage().getName()); private final Map typesByPropertyPath = new HashMap(); private final Map columnsByPropertyPath = new HashMap(); @@ -66,7 +69,7 @@ public abstract class AbstractPropertyMapping implements PropertyMapping { public String[] getIdentifierColumnReaders() { throw new UnsupportedOperationException("one-to-one is not supported here"); } - + protected abstract String getEntityName(); public Type toType(String propertyName) throws QueryException { @@ -96,7 +99,7 @@ public abstract class AbstractPropertyMapping implements PropertyMapping { throw propertyException( propertyName ); } String[] formulaTemplates = (String[]) formulaTemplatesByPropertyPath.get(propertyName); - String[] columnReaderTemplates = (String[]) columnReaderTemplatesByPropertyPath.get(propertyName); + String[] columnReaderTemplates = (String[]) columnReaderTemplatesByPropertyPath.get(propertyName); String[] result = new String[columns.length]; for ( int i=0; iLoader, just a wrapper around a @@ -46,8 +47,9 @@ import org.hibernate.loader.entity.UniqueEntityLoader; public final class NamedQueryLoader implements UniqueEntityLoader { private final String queryName; private final EntityPersister persister; - - private static final Logger log = LoggerFactory.getLogger(NamedQueryLoader.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NamedQueryLoader.class.getPackage().getName()); public NamedQueryLoader(String queryName, EntityPersister persister) { super(); @@ -56,26 +58,19 @@ public final class NamedQueryLoader implements UniqueEntityLoader { } public Object load(Serializable id, Object optionalObject, SessionImplementor session, LockOptions lockOptions) { - if ( lockOptions != null ) { - log.debug( "Ignoring lock-options passed to named query loader" ); - } + if (lockOptions != null) LOG.ignoringLockOptions(); return load( id, optionalObject, session ); } public Object load(Serializable id, Object optionalObject, SessionImplementor session) { - if ( log.isDebugEnabled() ) { - log.debug( - "loading entity: " + persister.getEntityName() + - " using named query: " + queryName - ); - } - + LOG.loadingEntity(persister.getEntityName(), queryName); + AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedQuery(queryName); if ( query.hasNamedParameters() ) { - query.setParameter( - query.getNamedParameters()[0], - id, - persister.getIdentifierType() + query.setParameter( + query.getNamedParameters()[0], + id, + persister.getIdentifierType() ); } else { @@ -86,7 +81,7 @@ public final class NamedQueryLoader implements UniqueEntityLoader { query.setOptionalObject(optionalObject); query.setFlushMode( FlushMode.MANUAL ); query.list(); - + // now look up the object we are really interested in! // (this lets us correctly handle proxies and multi-row // or multi-column queries) @@ -94,4 +89,20 @@ 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 962de9c905..04cd29a0ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java +++ b/hibernate-core/src/main/java/org/hibernate/pretty/Printer.java @@ -24,21 +24,23 @@ */ package org.hibernate.pretty; +import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.hibernate.HibernateException; import org.hibernate.EntityMode; +import org.hibernate.HibernateException; 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. @@ -46,8 +48,9 @@ import org.hibernate.type.Type; */ public final class Printer { - private SessionFactoryImplementor factory; - private static final Logger log = LoggerFactory.getLogger(Printer.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, Printer.class.getPackage().getName()); + + private SessionFactoryImplementor factory; /** * @param entity an actual entity object, not a proxy! @@ -102,15 +105,15 @@ public final class Printer { } public void toString(Iterator iter, EntityMode entityMode) throws HibernateException { - if ( !log.isDebugEnabled() || !iter.hasNext() ) return; - log.debug("listing entities:"); + if (!LOG.isDebugEnabled() || !iter.hasNext()) return; + LOG.listingEntities(); int i=0; while ( iter.hasNext() ) { if (i++>20) { - log.debug("more......"); + LOG.more(); break; } - log.debug( toString( iter.next(), entityMode ) ); + LOG.debug(toString(iter.next(), entityMode)); } } @@ -118,4 +121,18 @@ public final class Printer { 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 abf641c685..a6e89a6c19 100644 --- a/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java +++ b/hibernate-core/src/main/java/org/hibernate/property/BasicPropertyAccessor.java @@ -23,31 +23,33 @@ */ 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.Method; import java.lang.reflect.Member; +import java.lang.reflect.Method; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; 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. * The default (and recommended strategy). - * + * * @author Gavin King */ public class BasicPropertyAccessor implements PropertyAccessor { - private static final Logger log = LoggerFactory.getLogger(BasicPropertyAccessor.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicPropertyAccessor.class.getPackage().getName()); public static final class BasicSetter implements Setter { private Class clazz; @@ -60,7 +62,7 @@ public class BasicPropertyAccessor implements PropertyAccessor { this.propertyName=propertyName; } - public void set(Object target, Object value, SessionFactoryImplementor factory) + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException { try { method.invoke( target, value ); @@ -68,38 +70,38 @@ public class BasicPropertyAccessor implements PropertyAccessor { catch (NullPointerException npe) { if ( value==null && method.getParameterTypes()[0].isPrimitive() ) { throw new PropertyAccessException( - npe, - "Null value was assigned to a property of primitive type", - true, - clazz, + npe, + "Null value was assigned to a property of primitive type", + true, + clazz, propertyName ); } else { throw new PropertyAccessException( - npe, - "NullPointerException occurred while calling", - true, - clazz, + npe, + "NullPointerException occurred while calling", + true, + clazz, propertyName ); } } catch (InvocationTargetException ite) { throw new PropertyAccessException( - ite, - "Exception occurred inside", - true, - clazz, + ite, + "Exception occurred inside", + true, + clazz, propertyName ); } catch (IllegalAccessException iae) { throw new PropertyAccessException( - iae, - "IllegalAccessException occurred while calling", - true, - clazz, + iae, + "IllegalAccessException occurred while calling", + true, + clazz, propertyName ); //cannot occur @@ -107,29 +109,21 @@ public class BasicPropertyAccessor implements PropertyAccessor { catch (IllegalArgumentException iae) { if ( value==null && method.getParameterTypes()[0].isPrimitive() ) { throw new PropertyAccessException( - iae, - "Null value was assigned to a property of primitive type", - true, - clazz, + iae, + "Null value was assigned to a property of primitive type", + true, + clazz, propertyName ); } else { - log.error( - "IllegalArgumentException in class: " + clazz.getName() + - ", setter method of property: " + propertyName - ); - log.error( - "expected type: " + - method.getParameterTypes()[0].getName() + - ", actual value: " + - ( value==null ? null : value.getClass().getName() ) - ); + LOG.illegalPropertySetterArgument(clazz.getName(), propertyName); + LOG.expectedType(method.getParameterTypes()[0].getName(), value == null ? null : value.getClass().getName()); throw new PropertyAccessException( - iae, - "IllegalArgumentException occurred while calling", - true, - clazz, + iae, + "IllegalArgumentException occurred while calling", + true, + clazz, propertyName ); } @@ -148,7 +142,8 @@ public class BasicPropertyAccessor implements PropertyAccessor { return createSetter(clazz, propertyName); } - public String toString() { + @Override + public String toString() { return "BasicSetter(" + clazz.getName() + '.' + propertyName + ')'; } } @@ -173,33 +168,30 @@ public class BasicPropertyAccessor implements PropertyAccessor { } catch (InvocationTargetException ite) { throw new PropertyAccessException( - ite, - "Exception occurred inside", - false, - clazz, + ite, + "Exception occurred inside", + false, + clazz, propertyName ); } catch (IllegalAccessException iae) { throw new PropertyAccessException( - iae, - "IllegalAccessException occurred while calling", - false, - clazz, + iae, + "IllegalAccessException occurred while calling", + false, + clazz, propertyName ); //cannot occur } catch (IllegalArgumentException iae) { - log.error( - "IllegalArgumentException in class: " + clazz.getName() + - ", getter method of property: " + propertyName - ); + LOG.illegalPropertyGetterArgument(clazz.getName(), propertyName); throw new PropertyAccessException( - iae, - "IllegalArgumentException occurred calling", - false, - clazz, + iae, + "IllegalArgumentException occurred calling", + false, + clazz, propertyName ); } @@ -240,30 +232,31 @@ public class BasicPropertyAccessor implements PropertyAccessor { return method.getName(); } - public String toString() { + @Override + public String toString() { return "BasicGetter(" + clazz.getName() + '.' + propertyName + ')'; } - + Object readResolve() { return createGetter(clazz, propertyName); } } - public Setter getSetter(Class theClass, String propertyName) + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException { return createSetter(theClass, propertyName); } - - private static Setter createSetter(Class theClass, String propertyName) + + private static Setter createSetter(Class theClass, String propertyName) throws PropertyNotFoundException { BasicSetter result = getSetterOrNull(theClass, propertyName); if (result==null) { - throw new PropertyNotFoundException( - "Could not find a setter for property " + - propertyName + - " in class " + - theClass.getName() + throw new PropertyNotFoundException( + "Could not find a setter for property " + + propertyName + + " in class " + + theClass.getName() ); } return result; @@ -319,15 +312,15 @@ public class BasicPropertyAccessor implements PropertyAccessor { public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException { return createGetter(theClass, propertyName); } - + public static Getter createGetter(Class theClass, String propertyName) throws PropertyNotFoundException { BasicGetter result = getGetterOrNull(theClass, propertyName); if (result==null) { - throw new PropertyNotFoundException( - "Could not find a getter for " + - propertyName + - " in class " + - theClass.getName() + throw new PropertyNotFoundException( + "Could not find a getter for " + + propertyName + + " in class " + + theClass.getName() ); } return result; @@ -394,4 +387,25 @@ 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 2535c4ddc2..cd9c0fbdd6 100755 --- a/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/secure/JACCConfiguration.java @@ -24,25 +24,27 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Adds Hibernate permissions to roles via JACC - * + * * @author Gavin King */ public class JACCConfiguration { - private static final Logger log = LoggerFactory.getLogger( JACCConfiguration.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JACCConfiguration.class.getPackage().getName()); private final PolicyConfiguration policyConfiguration; @@ -70,16 +72,14 @@ public class JACCConfiguration { while ( tok.hasMoreTokens() ) { String methodName = tok.nextToken().trim(); - EJBMethodPermission permission = new EJBMethodPermission( - entityName, - methodName, + EJBMethodPermission permission = new EJBMethodPermission( + entityName, + methodName, null, // interfaces null // arguments ); - if ( log.isDebugEnabled() ) { - log.debug( "adding permission to role " + role + ": " + permission ); - } + LOG.addingPermissionToRole(role, permission); try { policyConfiguration.addToRole( role, permission ); } @@ -89,4 +89,15 @@ 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 975c8b4771..4a3e873e1d 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,14 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.service.jmx.spi.JmxService; import org.hibernate.service.spi.Configurable; import org.hibernate.service.spi.InjectService; @@ -41,6 +38,10 @@ 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 @@ -48,7 +49,9 @@ import org.hibernate.service.spi.UnknownServiceException; * @author Steve Ebersole */ public class ServicesInitializer { - private static final Logger log = LoggerFactory.getLogger( ServicesInitializer.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ServicesInitializer.class.getPackage().getName()); private final ServicesRegistryImpl servicesRegistry; private final Map serviceInitiatorMap; @@ -89,7 +92,7 @@ public class ServicesInitializer { * @return The intiialized instance of the service */ public T initializeService(Class serviceRole) { - log.trace( "Initializing service [role=" + serviceRole.getName() + "]" ); + LOG.initializingService(serviceRole.getName()); // PHASE 1 : create service T service = createService( serviceRole ); @@ -105,7 +108,7 @@ public class ServicesInitializer { @SuppressWarnings({ "unchecked" }) private T createService(Class serviceRole) { - ServiceInitiator initiator = (ServiceInitiator) serviceInitiatorMap.get( serviceRole ); + ServiceInitiator initiator = serviceInitiatorMap.get( serviceRole ); if ( initiator == null ) { throw new UnknownServiceException( serviceRole ); } @@ -189,4 +192,14 @@ public class ServicesInitializer { } } + /** + * 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 ac0f916e8d..c1c866c2ce 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,22 +23,23 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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. @@ -46,7 +47,9 @@ import org.hibernate.service.spi.UnknownServiceException; * @author Steve Ebersole */ public class ServicesRegistryImpl implements ServicesRegistry { - private static final Logger log = LoggerFactory.getLogger( ServicesRegistryImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ServicesRegistryImpl.class.getPackage().getName()); private final List serviceInitiators; private ServicesInitializer initializer; @@ -73,7 +76,7 @@ public class ServicesRegistryImpl implements ServicesRegistry { ( (Stoppable) service ).stop(); } catch ( Exception e ) { - log.info( "Error stopping service [" + service.getClass() + "] : " + e.toString() ); + LOG.unableToStopService(service.getClass(), e.toString()); } } } @@ -110,4 +113,16 @@ 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 3a33891dac..67a6be3b09 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,6 +23,8 @@ */ 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; @@ -31,17 +33,17 @@ import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; +import org.hibernate.internal.util.beans.BeanInfoHelper; import org.hibernate.service.classloading.spi.ClassLoaderService; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.internal.util.beans.BeanInfoHelper; -import org.hibernate.service.spi.ServicesRegistry; 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}. @@ -52,7 +54,8 @@ import org.hibernate.service.spi.ServiceInitiator; public class ConnectionProviderInitiator implements ServiceInitiator { public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator(); - private static final Logger log = LoggerFactory.getLogger( ConnectionProviderInitiator.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ConnectionProviderInitiator.class.getPackage().getName()); public static final String C3P0_CONFIG_PREFIX = "hibernate.c3p0"; public static final String C3P0_PROVIDER_CLASS_NAME = @@ -138,7 +141,7 @@ public class ConnectionProviderInitiator implements ServiceInitiator resolvers; @@ -70,7 +73,7 @@ public class DialectResolverSet implements DialectResolver { throw e; } catch ( Exception e ) { - log.info( "sub-resolver threw unexpected exception, continuing to next : " + e.getMessage() ); + LOG.exceptionInSubResolver(e.getMessage()); } } return null; @@ -95,4 +98,15 @@ 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 exceptionInSubResolver( String message ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/jdbc/dialect/internal/StandardDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/service/jdbc/dialect/internal/StandardDialectResolver.java index 1475ddc406..b4aeba3a97 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/jdbc/dialect/internal/StandardDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/service/jdbc/dialect/internal/StandardDialectResolver.java @@ -23,12 +23,9 @@ */ package org.hibernate.service.jdbc.dialect.internal; +import static org.jboss.logging.Logger.Level.WARN; import java.sql.DatabaseMetaData; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.dialect.DB2Dialect; import org.hibernate.dialect.DerbyDialect; import org.hibernate.dialect.Dialect; @@ -48,6 +45,10 @@ import org.hibernate.dialect.SQLServer2008Dialect; 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 Dialect resolver. @@ -55,9 +56,12 @@ import org.hibernate.dialect.SybaseAnywhereDialect; * @author Steve Ebersole */ public class StandardDialectResolver extends AbstractDialectResolver { - private static final Logger log = LoggerFactory.getLogger( StandardDialectResolver.class ); - protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StandardDialectResolver.class.getPackage().getName()); + + @Override + protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { String databaseName = metaData.getDatabaseProductName(); int databaseMajorVersion = metaData.getDatabaseMajorVersion(); @@ -92,7 +96,7 @@ public class StandardDialectResolver extends AbstractDialectResolver { case 10: return new Ingres10Dialect(); default: - log.warn( "Unknown Ingres major version [" + databaseMajorVersion + "] using Ingres 9.2 dialect" ); + LOG.unknownIngresVersion(databaseMajorVersion); } return new IngresDialect(); } @@ -138,10 +142,33 @@ public class StandardDialectResolver extends AbstractDialectResolver { case 8: return new Oracle8iDialect(); default: - log.warn( "unknown Oracle major version [" + databaseMajorVersion + "]" ); + LOG.unknownOracleVersion(databaseMajorVersion); } } return null; } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = WARN ) + @Message( value = "Ingres %d is not yet fully supported; using Ingres 9.3 dialect" ) + void ingresVersionNotFullySupported( int databaseMajorVersion ); + + @LogMessage( level = WARN ) + @Message( value = "Oracle 11g is not yet fully supported; using 10g dialect" ) + void oracleVersionNotFullySupported(); + + @LogMessage( level = WARN ) + @Message( value = "Unknown Ingres major version [%d] using Ingres 9.2 dialect" ) + void unknownIngresVersion( int databaseMajorVersion ); + + @LogMessage( level = WARN ) + @Message( value = "Unknown Oracle major version [%d]" ) + void unknownOracleVersion( int databaseMajorVersion ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/jmx/internal/JmxServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/service/jmx/internal/JmxServiceImpl.java index cb08e3d935..d4d203ea70 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/jmx/internal/JmxServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/jmx/internal/JmxServiceImpl.java @@ -23,6 +23,9 @@ */ package org.hibernate.service.jmx.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.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Map; @@ -30,17 +33,17 @@ import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; +import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.jmx.spi.JmxService; import org.hibernate.service.spi.Manageable; import org.hibernate.service.spi.Service; import org.hibernate.service.spi.Stoppable; -import org.hibernate.internal.util.config.ConfigurationHelper; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Standard implementation of JMX services @@ -48,7 +51,9 @@ import org.hibernate.internal.util.config.ConfigurationHelper; * @author Steve Ebersole */ public class JmxServiceImpl implements JmxService, Stoppable { - private static final Logger log = LoggerFactory.getLogger( JmxServiceImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JmxServiceImpl.class.getPackage().getName()); public static final String JMX_PLATFORM_SERVER = "hibernate.jmx.usePlatformServer"; public static final String JMX_AGENT_ID = "hibernate.jmx.agentId"; @@ -82,7 +87,7 @@ public class JmxServiceImpl implements JmxService, Stoppable { if ( startedServer || registeredMBeans != null ) { MBeanServer mBeanServer = findServer(); if ( mBeanServer == null ) { - log.warn( "Unable to locate MBeanServer on JMX service shutdown" ); + LOG.unableToLocateMBeanServer(); return; } @@ -90,23 +95,23 @@ public class JmxServiceImpl implements JmxService, Stoppable { if ( registeredMBeans != null ) { for ( ObjectName objectName : registeredMBeans ) { try { - log.trace( "Unregistering registered MBean [ON=" + objectName + "]" ); + LOG.unregisteringMBean(objectName); mBeanServer.unregisterMBean( objectName ); } catch ( Exception e ) { - log.debug( "Unable to unregsiter registered MBean [ON=" + objectName + "] : " + e.toString() ); + LOG.unableToUnregisterMBean(objectName, e.toString()); } } } // stop the MBean server if we started it if ( startedServer ) { - log.trace( "Attempting to release created MBeanServer" ); + LOG.attemptingToReleaseCreatedMBeanServer(); try { MBeanServerFactory.releaseMBeanServer( mBeanServer ); } catch ( Exception e ) { - log.warn( "Unable to release created MBeanServer : " + e.toString() ); + LOG.unableToReleaseCreatedMBeanServer(e.toString()); } } } @@ -217,4 +222,32 @@ public class JmxServiceImpl implements JmxService, Stoppable { throw new HibernateException( "Unable to start MBeanServer", e ); } } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = TRACE ) + @Message( value = "Attempting to release created MBeanServer" ) + void attemptingToReleaseCreatedMBeanServer(); + + @LogMessage( level = WARN ) + @Message( value = "Unable to locate MBeanServer on JMX service shutdown" ) + void unableToLocateMBeanServer(); + + @LogMessage( level = WARN ) + @Message( value = "Unable to release created MBeanServer : %s" ) + void unableToReleaseCreatedMBeanServer( String string ); + + @LogMessage( level = DEBUG ) + @Message( value = "Unable to unregsiter registered MBean [ON=%s] : %s" ) + void unableToUnregisterMBean( ObjectName objectName, + String string ); + + @LogMessage( level = TRACE ) + @Message( value = "Unregistering registered MBean [ON=%s]" ) + void unregisteringMBean( ObjectName objectName ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/jndi/internal/JndiServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/service/jndi/internal/JndiServiceImpl.java index 246ae370dc..616c5ed7d8 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/jndi/internal/JndiServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/jndi/internal/JndiServiceImpl.java @@ -23,18 +23,18 @@ */ package org.hibernate.service.jndi.internal; +import static org.jboss.logging.Logger.Level.INFO; import java.util.Hashtable; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - import org.hibernate.internal.util.jndi.JndiException; import org.hibernate.internal.util.jndi.JndiHelper; import org.hibernate.service.jndi.spi.JndiService; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * Standard implementation of JNDI services. @@ -42,7 +42,9 @@ import org.hibernate.service.jndi.spi.JndiService; * @author Steve Ebersole */ public class JndiServiceImpl implements JndiService { - private static final Logger log = LoggerFactory.getLogger( JndiServiceImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JndiServiceImpl.class.getPackage().getName()); private final Hashtable initialContextSettings; @@ -61,7 +63,7 @@ public class JndiServiceImpl implements JndiService { initialContext.close(); } catch ( NamingException e ) { - log.info( "error closing InitialContext [" + e.toString() + "]" ); + LOG.unableToCloseInitialContext(e.toString()); } } } @@ -86,8 +88,19 @@ public class JndiServiceImpl implements JndiService { initialContext.close(); } catch ( NamingException e ) { - log.info( "error closing InitialContet [" + e.toString() + "]" ); + LOG.unableToCloseInitialContext(e.toString()); } } } + + /** + * Interface defining messages that may be logged by the outer class + */ + @MessageLogger + interface Logger extends BasicLogger { + + @LogMessage( level = INFO ) + @Message( value = "Error closing InitialContext [%s]" ) + void unableToCloseInitialContext( String string ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentParser.java b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentParser.java index c7b0ed79e0..18fc0b5bf3 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentParser.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentParser.java @@ -25,17 +25,14 @@ package org.hibernate.sql.ordering.antlr; import java.util.ArrayList; - -import antlr.TokenStream; -import antlr.CommonAST; -import antlr.collections.AST; - -import org.hibernate.sql.Template; import org.hibernate.dialect.function.SQLFunction; +import org.hibernate.sql.Template; import org.hibernate.util.StringHelper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.MessageLogger; +import antlr.CommonAST; +import antlr.TokenStream; +import antlr.collections.AST; /** * Extension of the Antlr-generated parser for the purpose of adding our custom parsing behavior. @@ -43,7 +40,9 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { - private static final Logger log = LoggerFactory.getLogger( OrderByFragmentParser.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OrderByFragmentParser.class.getPackage().getName()); private final TranslationContext context; @@ -59,33 +58,37 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { private int traceDepth = 0; - public void traceIn(String ruleName) { + @Override + public void traceIn(String ruleName) { if ( inputState.guessing > 0 ) { return; } String prefix = StringHelper.repeat( '-', (traceDepth++ * 2) ) + "-> "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } - public void traceOut(String ruleName) { + @Override + public void traceOut(String ruleName) { if ( inputState.guessing > 0 ) { return; } String prefix = "<-" + StringHelper.repeat( '-', (--traceDepth * 2) ) + " "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } /** * {@inheritDoc} */ - protected void trace(String msg) { - log.trace( msg ); + @Override + protected void trace(String msg) { + LOG.trace(msg); } /** * {@inheritDoc} */ - protected AST quotedIdentifier(AST ident) { + @Override + protected AST quotedIdentifier(AST ident) { return getASTFactory().create( OrderByTemplateTokenTypes.IDENT, Template.TEMPLATE + "." + context.getDialect().quote( '`' + ident.getText() + '`' ) @@ -95,14 +98,16 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { /** * {@inheritDoc} */ - protected AST quotedString(AST ident) { + @Override + protected AST quotedString(AST ident) { return getASTFactory().create( OrderByTemplateTokenTypes.IDENT, context.getDialect().quote( ident.getText() ) ); } /** * {@inheritDoc} */ - protected boolean isFunctionName(AST ast) { + @Override + protected boolean isFunctionName(AST ast) { AST child = ast.getFirstChild(); // assume it is a function if it has parameters if ( child != null && "{param list}".equals( child.getText() ) ) { @@ -122,7 +127,8 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { /** * {@inheritDoc} */ - protected AST resolveFunction(AST ast) { + @Override + protected AST resolveFunction(AST ast) { AST child = ast.getFirstChild(); if ( child != null ) { assert "{param list}".equals( child.getText() ); @@ -160,7 +166,8 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { /** * {@inheritDoc} */ - protected AST resolveIdent(AST ident) { + @Override + protected AST resolveIdent(AST ident) { String text = ident.getText(); String[] replacements; try { @@ -189,7 +196,8 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { /** * {@inheritDoc} */ - protected AST postProcessSortSpecification(AST sortSpec) { + @Override + protected AST postProcessSortSpecification(AST sortSpec) { assert SORT_SPEC == sortSpec.getType(); SortSpecification sortSpecification = ( SortSpecification ) sortSpec; AST sortKey = sortSpecification.getSortKey(); @@ -229,4 +237,11 @@ public class OrderByFragmentParser extends GeneratedOrderByFragmentParser { } return ( SortSpecification ) sortSpecification; } + + /** + * 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/sql/ordering/antlr/OrderByFragmentRenderer.java b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentRenderer.java index 163ec4b1df..c6ef29d5a4 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentRenderer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentRenderer.java @@ -24,13 +24,11 @@ */ package org.hibernate.sql.ordering.antlr; -import antlr.collections.AST; - -import org.hibernate.util.StringHelper; import org.hibernate.hql.ast.util.ASTPrinter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.util.StringHelper; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.MessageLogger; +import antlr.collections.AST; /** * TODO : javadoc @@ -38,10 +36,13 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class OrderByFragmentRenderer extends GeneratedOrderByFragmentRenderer { - private static final Logger log = LoggerFactory.getLogger( OrderByFragmentRenderer.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OrderByFragmentRenderer.class.getPackage().getName()); private static final ASTPrinter printer = new ASTPrinter( GeneratedOrderByFragmentRendererTokenTypes.class ); - protected void out(AST ast) { + @Override + protected void out(AST ast) { out( ( ( Node ) ast ).getRenderableText() ); } @@ -50,13 +51,14 @@ public class OrderByFragmentRenderer extends GeneratedOrderByFragmentRenderer { private int traceDepth = 0; - public void traceIn(String ruleName, AST tree) { + @Override + public void traceIn(String ruleName, AST tree) { if ( inputState.guessing > 0 ) { return; } String prefix = StringHelper.repeat( '-', (traceDepth++ * 2) ) + "-> "; String traceText = ruleName + " (" + buildTraceNodeName(tree) + ")"; - log.trace( prefix + traceText ); + LOG.trace(prefix + traceText); } private String buildTraceNodeName(AST tree) { @@ -65,11 +67,19 @@ public class OrderByFragmentRenderer extends GeneratedOrderByFragmentRenderer { : tree.getText() + " [" + printer.getTokenTypeName( tree.getType() ) + "]"; } - public void traceOut(String ruleName, AST tree) { + @Override + public void traceOut(String ruleName, AST tree) { if ( inputState.guessing > 0 ) { return; } String prefix = "<-" + StringHelper.repeat( '-', (--traceDepth * 2) ) + " "; - log.trace( prefix + ruleName ); + LOG.trace(prefix + ruleName); } + + /** + * 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/sql/ordering/antlr/OrderByFragmentTranslator.java b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentTranslator.java index 32f39f97d5..1d3fdeef70 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentTranslator.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ordering/antlr/OrderByFragmentTranslator.java @@ -25,12 +25,11 @@ package org.hibernate.sql.ordering.antlr; import java.io.StringReader; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.hql.ast.util.ASTPrinter; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * A translator which coordinates translation of an order-by mapping. @@ -38,7 +37,9 @@ import org.hibernate.hql.ast.util.ASTPrinter; * @author Steve Ebersole */ public class OrderByFragmentTranslator { - private static final Logger log = LoggerFactory.getLogger( OrderByFragmentTranslator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + OrderByFragmentTranslator.class.getPackage().getName()); public final TranslationContext context; @@ -66,9 +67,9 @@ public class OrderByFragmentTranslator { throw new HibernateException( "Unable to parse order-by fragment", t ); } - if ( log.isTraceEnabled() ) { + if (LOG.isTraceEnabled()) { ASTPrinter printer = new ASTPrinter( OrderByTemplateTokenTypes.class ); - log.trace( printer.showAsString( parser.getAST(), "--- {order-by fragment} ---" ) ); + LOG.trace(printer.showAsString(parser.getAST(), LOG.orderByFragmentHeader())); } OrderByFragmentRenderer renderer = new OrderByFragmentRenderer(); @@ -84,4 +85,14 @@ 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 c18e3e6932..b669d2a95a 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/ConcurrentStatisticsImpl.java @@ -26,10 +26,6 @@ package org.hibernate.stat; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.cache.Region; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.ArrayHelper; @@ -42,8 +38,9 @@ import org.hibernate.util.ArrayHelper; */ @SuppressWarnings({ "unchecked" }) public class ConcurrentStatisticsImpl implements Statistics, StatisticsImplementor { - private static final Logger log = LoggerFactory.getLogger( ConcurrentStatisticsImpl.class ); - private static final Logger PERF_LOG = LoggerFactory.getLogger( Statistics.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ConcurrentStatisticsImpl.class.getPackage().getName()); private SessionFactoryImplementor sessionFactory; @@ -316,7 +313,7 @@ public class ConcurrentStatisticsImpl implements Statistics, StatisticsImplement @SuppressWarnings({ "UnnecessaryBoxing" }) public void queryExecuted(String hql, int rows, long time) { - PERF_LOG.info( "HQL: {}, time: {}ms, rows: {}", new Object[] {hql, Long.valueOf( time ), Long.valueOf(rows)} ); + LOG.hql(hql, Long.valueOf(time), Long.valueOf(rows)); queryExecutionCount.getAndIncrement(); boolean isLongestQuery = false; for ( long old = queryExecutionMaxTime.get(); @@ -537,35 +534,35 @@ public class ConcurrentStatisticsImpl implements Statistics, StatisticsImplement * log in info level the main statistics */ public void logSummary() { - log.info( "Logging statistics...." ); - log.info( "start time: " + startTime ); - log.info( "sessions opened: " + sessionOpenCount ); - log.info( "sessions closed: " + sessionCloseCount ); - log.info( "transactions: " + transactionCount ); - log.info( "successful transactions: " + committedTransactionCount ); - log.info( "optimistic lock failures: " + optimisticFailureCount ); - log.info( "flushes: " + flushCount ); - log.info( "connections obtained: " + connectCount ); - log.info( "statements prepared: " + prepareStatementCount ); - log.info( "statements closed: " + closeStatementCount ); - log.info( "second level cache puts: " + secondLevelCachePutCount ); - log.info( "second level cache hits: " + secondLevelCacheHitCount ); - log.info( "second level cache misses: " + secondLevelCacheMissCount ); - log.info( "entities loaded: " + entityLoadCount ); - log.info( "entities updated: " + entityUpdateCount ); - log.info( "entities inserted: " + entityInsertCount ); - log.info( "entities deleted: " + entityDeleteCount ); - log.info( "entities fetched (minimize this): " + entityFetchCount ); - log.info( "collections loaded: " + collectionLoadCount ); - log.info( "collections updated: " + collectionUpdateCount ); - log.info( "collections removed: " + collectionRemoveCount ); - log.info( "collections recreated: " + collectionRecreateCount ); - log.info( "collections fetched (minimize this): " + collectionFetchCount ); - log.info( "queries executed to database: " + queryExecutionCount ); - log.info( "query cache puts: " + queryCachePutCount ); - log.info( "query cache hits: " + queryCacheHitCount ); - log.info( "query cache misses: " + queryCacheMissCount ); - log.info( "max query time: " + queryExecutionMaxTime + "ms" ); + LOG.loggingStatistics(); + LOG.startTime(startTime); + LOG.sessionsOpened(sessionOpenCount); + LOG.sessionsClosed(sessionCloseCount); + LOG.transactions(transactionCount); + LOG.successfulTransactions(committedTransactionCount); + LOG.optimisticLockFailures(optimisticFailureCount); + LOG.flushes(flushCount); + LOG.connectionsObtained(connectCount); + LOG.statementsPrepared(prepareStatementCount); + LOG.statementsClosed(closeStatementCount); + LOG.secondLevelCachePuts(secondLevelCachePutCount); + LOG.secondLevelCacheHits(secondLevelCacheHitCount); + LOG.secondLevelCacheMisses(secondLevelCacheMissCount); + LOG.entitiesLoaded(entityLoadCount); + LOG.entitiesUpdated(entityUpdateCount); + LOG.entitiesInserted(entityInsertCount); + LOG.entitiesDeleted(entityDeleteCount); + LOG.entitiesFetched(entityFetchCount); + LOG.collectionsLoaded(collectionLoadCount); + LOG.collectionsUpdated(collectionUpdateCount); + LOG.collectionsRemoved(collectionRemoveCount); + LOG.collectionsRecreated(collectionRecreateCount); + LOG.collectionsFetched(collectionFetchCount); + LOG.queriesExecuted(queryExecutionCount); + LOG.queryCachePuts(queryCachePutCount); + LOG.queryCacheHits(queryCacheHitCount); + LOG.queryCacheMisses(queryCacheMissCount); + LOG.maxQueryTime(queryExecutionMaxTime); } /** @@ -673,7 +670,8 @@ public class ConcurrentStatisticsImpl implements Statistics, StatisticsImplement return optimisticFailureCount.get(); } - public String toString() { + @Override + public String toString() { return new StringBuilder() .append( "Statistics[" ) .append( "start time=" ).append( startTime ) @@ -711,5 +709,4 @@ public class ConcurrentStatisticsImpl implements Statistics, StatisticsImplement public String getQueryExecutionMaxTimeQueryString() { return queryExecutionMaxTimeQueryString; } - } 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 ee425cbc13..d4485c8eb7 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/StatisticsImpl.java @@ -23,28 +23,27 @@ * */ package org.hibernate.stat; + import java.util.HashMap; import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.cache.Region; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.util.ArrayHelper; /** - * @see org.hibernate.stat.Statistics - * + * @see org.hibernate.stat.Statistics + * * @author Gavin King * * @deprecated Use {@link org.hibernate.stat.ConcurrentStatisticsImpl} instead */ @Deprecated public class StatisticsImpl implements Statistics, StatisticsImplementor { - + //TODO: we should provide some way to get keys of collection of statistics to make it easier to retrieve from a GUI perspective - - private static final Logger log = LoggerFactory.getLogger(StatisticsImpl.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + StatisticsImpl.class.getPackage().getName()); private SessionFactoryImplementor sessionFactory; @@ -54,10 +53,10 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { private long sessionCloseCount; private long flushCount; private long connectCount; - + private long prepareStatementCount; private long closeStatementCount; - + private long entityLoadCount; private long entityUpdateCount; private long entityInsertCount; @@ -68,23 +67,23 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { private long collectionRemoveCount; private long collectionRecreateCount; private long collectionFetchCount; - + private long secondLevelCacheHitCount; private long secondLevelCacheMissCount; private long secondLevelCachePutCount; - + private long queryExecutionCount; private long queryExecutionMaxTime; private String queryExecutionMaxTimeQueryString; private long queryCacheHitCount; private long queryCacheMissCount; private long queryCachePutCount; - + private long commitedTransactionCount; private long transactionCount; - + private long optimisticFailureCount; - + /** second level cache statistics per region */ private final Map secondLevelCacheStatistics = new HashMap(); /** entity statistics per name */ @@ -102,7 +101,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { clear(); this.sessionFactory = sessionFactory; } - + /** * reset all statistics */ @@ -110,63 +109,63 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { secondLevelCacheHitCount = 0; secondLevelCacheMissCount = 0; secondLevelCachePutCount = 0; - + sessionCloseCount = 0; sessionOpenCount = 0; flushCount = 0; connectCount = 0; - + prepareStatementCount = 0; closeStatementCount = 0; - + entityDeleteCount = 0; entityInsertCount = 0; entityUpdateCount = 0; entityLoadCount = 0; entityFetchCount = 0; - + collectionRemoveCount = 0; collectionUpdateCount = 0; collectionRecreateCount = 0; collectionLoadCount = 0; collectionFetchCount = 0; - + queryExecutionCount = 0; queryCacheHitCount = 0; queryExecutionMaxTime = 0; queryExecutionMaxTimeQueryString = null; queryCacheMissCount = 0; queryCachePutCount = 0; - + transactionCount = 0; commitedTransactionCount = 0; - + optimisticFailureCount = 0; - + secondLevelCacheStatistics.clear(); entityStatistics.clear(); collectionStatistics.clear(); queryStatistics.clear(); - + startTime = System.currentTimeMillis(); } - + public synchronized void openSession() { sessionOpenCount++; } - + public synchronized void closeSession() { sessionCloseCount++; } - + public synchronized void flush() { flushCount++; } - + public synchronized void connect() { connectCount++; } - + public synchronized void loadEntity(String entityName) { entityLoadCount++; ((EntityStatisticsImpl) getEntityStatistics(entityName)).loadCount++; @@ -179,7 +178,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { /** * find entity statistics per name - * + * * @param entityName entity name * @return EntityStatistics object */ @@ -191,7 +190,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { } return es; } - + public synchronized void updateEntity(String entityName) { entityUpdateCount++; EntityStatisticsImpl es = (EntityStatisticsImpl) getEntityStatistics(entityName); @@ -212,7 +211,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { /** * Get collection statistics per role - * + * * @param role collection role * @return CollectionStatistics */ @@ -224,7 +223,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { } return cs; } - + public synchronized void loadCollection(String role) { collectionLoadCount++; ((CollectionStatisticsImpl) getCollectionStatistics(role)).loadCount++; @@ -249,10 +248,10 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { collectionRemoveCount++; ((CollectionStatisticsImpl) getCollectionStatistics(role)).removeCount++; } - + /** * Second level cache statistics per region - * + * * @param regionName region name * @return SecondLevelCacheStatistics */ @@ -296,10 +295,10 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { if (hql!=null) { QueryStatisticsImpl qs = (QueryStatisticsImpl) getQueryStatistics(hql); qs.executed(rows, time); - log.info( "HQL: {}, time: {}ms, rows: {}", new Object[]{hql, new Long( time ), new Long( rows )} ); + LOG.hql(hql, new Long(time), new Long(rows)); } } - + public synchronized void queryCacheHit(String hql, String regionName) { queryCacheHitCount++; if (hql!=null) { @@ -332,7 +331,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { /** * Query statistics from query string (HQL or SQL) - * + * * @param queryString query string * @return QueryStatistics */ @@ -351,21 +350,21 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getEntityDeleteCount() { return entityDeleteCount; } - + /** * @return entity insertion count */ public long getEntityInsertCount() { return entityInsertCount; } - + /** * @return entity load (from DB) */ public long getEntityLoadCount() { return entityLoadCount; } - + /** * @return entity fetch (from DB) */ @@ -383,26 +382,26 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getQueryExecutionCount() { return queryExecutionCount; } - + public long getQueryCacheHitCount() { return queryCacheHitCount; } - + public long getQueryCacheMissCount() { return queryCacheMissCount; } - + public long getQueryCachePutCount() { return queryCachePutCount; } - + /** * @return flush */ public long getFlushCount() { return flushCount; } - + /** * @return session connect */ @@ -423,7 +422,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getSecondLevelCacheMissCount() { return secondLevelCacheMissCount; } - + /** * @return second level cache put */ @@ -437,7 +436,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getSessionCloseCount() { return sessionCloseCount; } - + /** * @return session opening */ @@ -458,7 +457,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getCollectionFetchCount() { return collectionFetchCount; } - + /** * @return collection update */ @@ -486,49 +485,49 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getStartTime() { return startTime; } - + /** * log in info level the main statistics */ public void logSummary() { - log.info("Logging statistics...."); - log.info("start time: " + startTime); - log.info("sessions opened: " + sessionOpenCount); - log.info("sessions closed: " + sessionCloseCount); - log.info("transactions: " + transactionCount); - log.info("successful transactions: " + commitedTransactionCount); - log.info("optimistic lock failures: " + optimisticFailureCount); - log.info("flushes: " + flushCount); - log.info("connections obtained: " + connectCount); - log.info("statements prepared: " + prepareStatementCount); - log.info("statements closed: " + closeStatementCount); - log.info("second level cache puts: " + secondLevelCachePutCount); - log.info("second level cache hits: " + secondLevelCacheHitCount); - log.info("second level cache misses: " + secondLevelCacheMissCount); - log.info("entities loaded: " + entityLoadCount); - log.info("entities updated: " + entityUpdateCount); - log.info("entities inserted: " + entityInsertCount); - log.info("entities deleted: " + entityDeleteCount); - log.info("entities fetched (minimize this): " + entityFetchCount); - log.info("collections loaded: " + collectionLoadCount); - log.info("collections updated: " + collectionUpdateCount); - log.info("collections removed: " + collectionRemoveCount); - log.info("collections recreated: " + collectionRecreateCount); - log.info("collections fetched (minimize this): " + collectionFetchCount); - log.info("queries executed to database: " + queryExecutionCount); - log.info("query cache puts: " + queryCachePutCount); - log.info("query cache hits: " + queryCacheHitCount); - log.info("query cache misses: " + queryCacheMissCount); - log.info("max query time: " + queryExecutionMaxTime + "ms"); + LOG.loggingStatistics(); + LOG.startTime(startTime); + LOG.sessionsOpened(sessionOpenCount); + LOG.sessionsClosed(sessionCloseCount); + LOG.transactions(transactionCount); + LOG.successfulTransactions(commitedTransactionCount); + LOG.optimisticLockFailures(optimisticFailureCount); + LOG.flushes(flushCount); + LOG.connectionsObtained(connectCount); + LOG.statementsPrepared(prepareStatementCount); + LOG.statementsClosed(closeStatementCount); + LOG.secondLevelCachePuts(secondLevelCachePutCount); + LOG.secondLevelCacheHits(secondLevelCacheHitCount); + LOG.secondLevelCacheMisses(secondLevelCacheMissCount); + LOG.entitiesLoaded(entityLoadCount); + LOG.entitiesUpdated(entityUpdateCount); + LOG.entitiesInserted(entityInsertCount); + LOG.entitiesDeleted(entityDeleteCount); + LOG.entitiesFetched(entityFetchCount); + LOG.collectionsLoaded(collectionLoadCount); + LOG.collectionsUpdated(collectionUpdateCount); + LOG.collectionsRemoved(collectionRemoveCount); + LOG.collectionsRecreated(collectionRecreateCount); + LOG.collectionsFetched(collectionFetchCount); + LOG.queriesExecuted(queryExecutionCount); + LOG.queryCachePuts(queryCachePutCount); + LOG.queryCacheHits(queryCacheHitCount); + LOG.queryCacheMisses(queryCacheMissCount); + LOG.maxQueryTime(queryExecutionMaxTime); } - + /** * Are statistics logged */ public boolean isStatisticsEnabled() { return isStatisticsEnabled; } - + /** * Enable statistics logs (this is a dynamic parameter) */ @@ -543,14 +542,14 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getQueryExecutionMaxTime() { return queryExecutionMaxTime; } - + /** * Get all executed query strings */ public String[] getQueries() { return ArrayHelper.toStringArray( queryStatistics.keySet() ); } - + /** * Get the names of all entities */ @@ -574,7 +573,7 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { return ArrayHelper.toStringArray( sessionFactory.getAllCollectionMetadata().keySet() ); } } - + /** * Get all second-level cache region names */ @@ -591,11 +590,11 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { transactionCount++; if (success) commitedTransactionCount++; } - + public long getSuccessfulTransactionCount() { return commitedTransactionCount; } - + public long getTransactionCount() { return transactionCount; } @@ -624,7 +623,8 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public long getOptimisticFailureCount() { return optimisticFailureCount; } - public String toString() { + @Override + public String toString() { return new StringBuffer() .append("Statistics[") .append("start time=").append(startTime) @@ -662,5 +662,4 @@ public class StatisticsImpl implements Statistics, StatisticsImplementor { public String getQueryExecutionMaxTimeQueryString() { return queryExecutionMaxTimeQueryString; } - } 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 801410375c..bbdfcdc138 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,6 +24,7 @@ */ 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; @@ -33,24 +34,26 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; +import org.hibernate.dialect.Dialect; import org.hibernate.exception.JDBCExceptionHelper; import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.mapping.Table; -import org.hibernate.dialect.Dialect; 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 * @author Christoph Sturm, Teodor Danciu */ public class DatabaseMetadata { - - private static final Logger log = LoggerFactory.getLogger(DatabaseMetadata.class); - + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DatabaseMetaData.class.getPackage().getName()); + private final Map tables = new HashMap(); private final Set sequences = new HashSet(); private final boolean extras; @@ -79,34 +82,34 @@ public class DatabaseMetadata { return table; } else { - + try { ResultSet rs = null; try { if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) { rs = meta.getTables(catalog, schema, name, TYPES); - } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers()) + } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers()) || (!isQuoted && meta.storesUpperCaseIdentifiers() )) { - rs = meta.getTables( - StringHelper.toUpperCase(catalog), - StringHelper.toUpperCase(schema), - StringHelper.toUpperCase(name), - TYPES + rs = meta.getTables( + StringHelper.toUpperCase(catalog), + StringHelper.toUpperCase(schema), + StringHelper.toUpperCase(name), + TYPES ); } else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers()) || (!isQuoted && meta.storesLowerCaseIdentifiers() )) { - rs = meta.getTables( - StringHelper.toLowerCase(catalog), - StringHelper.toLowerCase(schema), - StringHelper.toLowerCase(name), - TYPES + rs = meta.getTables( + StringHelper.toLowerCase(catalog), + StringHelper.toLowerCase(schema), + StringHelper.toLowerCase(name), + TYPES ); } else { rs = meta.getTables(catalog, schema, name, TYPES); } - + while ( rs.next() ) { String tableName = rs.getString("TABLE_NAME"); if ( name.equalsIgnoreCase(tableName) ) { @@ -115,8 +118,8 @@ public class DatabaseMetadata { return table; } } - - log.info("table not found: " + name); + + LOG.tableNotFound(name); return null; } @@ -143,13 +146,13 @@ public class DatabaseMetadata { if ( dialect.supportsSequences() ) { String sql = dialect.getQuerySequencesString(); if (sql!=null) { - + Statement statement = null; ResultSet rs = null; try { statement = connection.createStatement(); rs = statement.executeQuery(sql); - + while ( rs.next() ) { sequences.add( rs.getString(1).toLowerCase().trim() ); } @@ -158,7 +161,7 @@ public class DatabaseMetadata { if (rs!=null) rs.close(); if (statement!=null) statement.close(); } - + } } } @@ -192,13 +195,20 @@ public class DatabaseMetadata { } return false; } - - public String toString() { + + @Override + 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 4916f13734..3baff52b56 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,6 +24,10 @@ */ 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; @@ -40,10 +44,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.cfg.Configuration; @@ -58,6 +58,10 @@ 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. @@ -67,7 +71,8 @@ import org.hibernate.util.ReflectHelper; */ public class SchemaExport { - private static final Logger log = LoggerFactory.getLogger( SchemaExport.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SchemaExport.class.getPackage().getName()); private ConnectionHelper connectionHelper; private String[] dropSQL; @@ -122,7 +127,8 @@ public class SchemaExport { * * @deprecated properties may be specified via the Configuration object */ - public SchemaExport(Configuration cfg, Properties properties) throws HibernateException { + @Deprecated + public SchemaExport(Configuration cfg, Properties properties) throws HibernateException { dialect = Dialect.getDialect( properties ); Properties props = new Properties(); @@ -174,7 +180,8 @@ public class SchemaExport { * @return this * @deprecated use {@link org.hibernate.cfg.Environment.HBM2DDL_IMPORT_FILE} */ - public SchemaExport setImportFile(String filename) { + @Deprecated + public SchemaExport setImportFile(String filename) { importFiles = filename; return this; } @@ -234,7 +241,7 @@ public class SchemaExport { public void execute(boolean script, boolean export, boolean justDrop, boolean justCreate) { - log.info( "Running hbm2ddl schema export" ); + LOG.runningHbm2ddlSchemaExport(); Connection connection = null; Writer outputFileWriter = null; @@ -252,17 +259,17 @@ public class SchemaExport { importFileReaders.add( new NamedReader( resourceName, stream ) ); } catch ( HibernateException e ) { - log.debug( "import file not found: " + currentFile ); + LOG.importFileNotFound(currentFile); } } if ( outputFile != null ) { - log.info( "writing generated schema to file: " + outputFile ); + LOG.writingGeneratedSchemaToFile(outputFile); outputFileWriter = new FileWriter( outputFile ); } if ( export ) { - log.info( "exporting generated schema to database" ); + LOG.exportingGeneratedSchemaToDatabase(); connectionHelper.prepare( true ); connection = connectionHelper.getConnection(); statement = connection.createStatement(); @@ -281,13 +288,13 @@ public class SchemaExport { } } - log.info( "schema export complete" ); + LOG.schemaExportComplete(); } catch ( Exception e ) { exceptions.add( e ); - log.error( "schema export unsuccessful", e ); + LOG.error(LOG.schemaExportUnsuccessful(), e); } finally { @@ -302,7 +309,7 @@ public class SchemaExport { } catch ( Exception e ) { exceptions.add( e ); - log.error( "Could not close connection", e ); + LOG.error(LOG.unableToCloseConnection(), e); } try { @@ -312,7 +319,7 @@ public class SchemaExport { } catch ( IOException ioe ) { exceptions.add( ioe ); - log.error( "Error closing output file: " + outputFile, ioe ); + LOG.error(LOG.unableToCloseOutputFile(outputFile), ioe); } for (NamedReader reader : importFileReaders) { try { @@ -320,7 +327,7 @@ public class SchemaExport { } catch ( IOException ioe ) { exceptions.add( ioe ); - log.error( "Error closing imput files: " + reader.getName(), ioe ); + LOG.error(LOG.unableToCloseInputFiles(reader.getName()), ioe); } } @@ -348,7 +355,7 @@ public class SchemaExport { private void importScript(NamedReader importFileReader, Statement statement) throws IOException { - log.info( "Executing import script: " + importFileReader.getName() ); + LOG.executingImportScript(importFileReader.getName()); BufferedReader reader = new BufferedReader( importFileReader.getReader() ); long lineNo = 0; for ( String sql = reader.readLine(); sql != null; sql = reader.readLine() ) { @@ -361,13 +368,9 @@ public class SchemaExport { trimmedSql.startsWith( "/*" ) ) { continue; } - else { - if ( trimmedSql.endsWith( ";" ) ) { - trimmedSql = trimmedSql.substring( 0, trimmedSql.length() - 1 ); - } - log.debug( trimmedSql ); - statement.execute( trimmedSql ); - } + if (trimmedSql.endsWith(";")) trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1); + LOG.debug(trimmedSql); + statement.execute(trimmedSql); } catch ( SQLException e ) { throw new JDBCException( "Error during import script execution at line " + lineNo, e ); @@ -386,8 +389,8 @@ public class SchemaExport { throw new JDBCException( "Error during DDL export", e ); } exceptions.add( e ); - log.error( "Unsuccessful: " + createSQL[j] ); - log.error( e.getMessage() ); + LOG.unsuccessfulCreate(createSQL[j]); + LOG.error(e.getMessage()); } } } @@ -400,8 +403,8 @@ public class SchemaExport { } catch ( SQLException e ) { exceptions.add( e ); - log.debug( "Unsuccessful: " + dropSQL[i] ); - log.debug( e.getMessage() ); + LOG.unsuccessfulDrop(dropSQL[i]); + LOG.debug(e.getMessage()); } } } @@ -415,7 +418,7 @@ public class SchemaExport { if ( script ) { System.out.println( formatted ); } - log.debug( formatted ); + LOG.debug(formatted); if ( outputFile != null ) { fileOutput.write( formatted + "\n" ); } @@ -429,11 +432,11 @@ public class SchemaExport { } } catch( SQLException sqle ) { - log.warn( "unable to log SQLWarnings : " + sqle ); + LOG.unableToLogSqlWarnings(sqle); } } - + } public static void main(String[] args) { @@ -526,7 +529,7 @@ public class SchemaExport { } catch ( Exception e ) { - log.error( "Error creating schema ", e ); + LOG.error(LOG.unableToCreateSchema(), e); e.printStackTrace(); } } @@ -539,4 +542,62 @@ 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 09bf4db55c..d6b303408d 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,6 +24,8 @@ */ 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; @@ -33,22 +35,22 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; - import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; -import org.hibernate.cfg.Settings; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.jdbc.util.FormatStyle; -import org.hibernate.jdbc.util.Formatter; import org.hibernate.engine.jdbc.spi.SQLStatementLogger; import org.hibernate.internal.util.config.ConfigurationHelper; +import org.hibernate.jdbc.util.FormatStyle; +import org.hibernate.jdbc.util.Formatter; import org.hibernate.util.ReflectHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -58,7 +60,8 @@ import org.slf4j.LoggerFactory; */ public class SchemaUpdate { - private static final Logger log = LoggerFactory.getLogger( SchemaUpdate.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SchemaUpdate.class.getPackage().getName()); private ConnectionHelper connectionHelper; private Configuration configuration; private Dialect dialect; @@ -141,7 +144,7 @@ public class SchemaUpdate { new SchemaUpdate( cfg ).execute( script, doUpdate ); } catch ( Exception e ) { - log.error( "Error running schema update", e ); + LOG.error(LOG.unableToRunSchemaUpdate(), e); e.printStackTrace(); } } @@ -153,7 +156,7 @@ public class SchemaUpdate { */ public void execute(boolean script, boolean doUpdate) { - log.info( "Running hbm2ddl schema update" ); + LOG.runningHbm2ddlSchemaUpdate(); Connection connection = null; Statement stmt = null; @@ -165,7 +168,7 @@ public class SchemaUpdate { DatabaseMetadata meta; try { - log.info( "fetching database metadata" ); + LOG.fetchingDatabaseMetadata(); connectionHelper.prepare( true ); connection = connectionHelper.getConnection(); meta = new DatabaseMetadata( connection, dialect ); @@ -173,18 +176,18 @@ public class SchemaUpdate { } catch ( SQLException sqle ) { exceptions.add( sqle ); - log.error( "could not get database metadata", sqle ); + LOG.error(LOG.unableToGetDatabaseMetadata(), sqle); throw sqle; } - log.info( "updating schema" ); + LOG.updatingSchema(); + - if ( outputFile != null ) { - log.info( "writing generated schema to file: " + outputFile ); + LOG.writingGeneratedSchemaToFile(outputFile); outputFileWriter = new FileWriter( outputFile ); } - + String[] createSQL = configuration.generateSchemaUpdateScript( dialect, meta ); for ( int j = 0; j < createSQL.length; j++ ) { @@ -201,7 +204,7 @@ public class SchemaUpdate { outputFileWriter.write( formatted + "\n" ); } if ( doUpdate ) { - log.debug( sql ); + LOG.debug(sql); stmt.executeUpdate( formatted ); } } @@ -210,17 +213,17 @@ public class SchemaUpdate { throw new JDBCException( "Error during DDL export", e ); } exceptions.add( e ); - log.error( "Unsuccessful: " + sql ); - log.error( e.getMessage() ); + LOG.unsuccessful(sql); + LOG.error(e.getMessage()); } } - log.info( "schema update complete" ); + LOG.schemaUpdateComplete(); } catch ( Exception e ) { exceptions.add( e ); - log.error( "could not complete schema update", e ); + LOG.error(LOG.unableToCompleteSchemaUpdate(), e); } finally { @@ -232,7 +235,7 @@ public class SchemaUpdate { } catch ( Exception e ) { exceptions.add( e ); - log.error( "Error closing connection", e ); + LOG.error(LOG.unableToCloseConnection(), e); } try { if( outputFileWriter != null ) { @@ -241,7 +244,7 @@ public class SchemaUpdate { } catch(Exception e) { exceptions.add(e); - log.error( "Error closing connection", e ); + LOG.error(LOG.unableToCloseConnection(), e); } } } @@ -271,4 +274,46 @@ public class SchemaUpdate { 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 04f9985220..d5b29794d1 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,13 +24,11 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.NamingStrategy; @@ -38,6 +36,10 @@ 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 @@ -47,7 +49,9 @@ import org.hibernate.util.ReflectHelper; */ public class SchemaValidator { - private static final Logger log = LoggerFactory.getLogger( SchemaValidator.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SchemaValidator.class.getPackage().getName()); + private ConnectionHelper connectionHelper; private Configuration configuration; private Dialect dialect; @@ -109,7 +113,7 @@ public class SchemaValidator { new SchemaValidator( cfg ).validate(); } catch ( Exception e ) { - log.error( "Error running schema update", e ); + LOG.error(LOG.unableToRunSchemaUpdate(), e); e.printStackTrace(); } } @@ -119,7 +123,7 @@ public class SchemaValidator { */ public void validate() { - log.info( "Running schema validator" ); + LOG.runningSchemaValidator(); Connection connection = null; @@ -127,13 +131,13 @@ public class SchemaValidator { DatabaseMetadata meta; try { - log.info( "fetching database metadata" ); + LOG.fetchingDatabaseMetadata(); connectionHelper.prepare( false ); connection = connectionHelper.getConnection(); meta = new DatabaseMetadata( connection, dialect, false ); } catch ( SQLException sqle ) { - log.error( "could not get database metadata", sqle ); + LOG.error(LOG.unableToGetDatabaseMetadata(), sqle); throw sqle; } @@ -141,7 +145,7 @@ public class SchemaValidator { } catch ( SQLException e ) { - log.error( "could not complete schema validation", e ); + LOG.error(LOG.unableToCompleteSchemaValidation(), e); } finally { @@ -149,10 +153,36 @@ public class SchemaValidator { connectionHelper.release(); } catch ( Exception e ) { - log.error( "Error closing connection", e ); + LOG.error(LOG.unableToCloseConnection(), e); } } } + /** + * 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 1d487d2b5a..14ac66fda7 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,17 +23,19 @@ */ 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.Map; import java.util.Iterator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.util.Map; +import java.util.Set; 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 @@ -42,8 +44,10 @@ import org.hibernate.mapping.ForeignKey; * @author Max Rydahl Andersen */ public class TableMetadata { - private static final Logger log = LoggerFactory.getLogger(TableMetadata.class); - + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TableMetadata.class.getPackage().getName()); + private final String catalog; private final String schema; private final String name; @@ -62,11 +66,11 @@ public class TableMetadata { } String cat = catalog==null ? "" : catalog + '.'; String schem = schema==null ? "" : schema + '.'; - log.info( "table found: " + cat + schem + name ); - log.info( "columns: " + columns.keySet() ); + LOG.tableFound(cat + schem + name); + LOG.columns(columns.keySet()); if (extras) { - log.info( "foreign keys: " + foreignKeys.keySet() ); - log.info( "indexes: " + indexes.keySet() ); + LOG.foreignKeys(foreignKeys.keySet()); + LOG.indexes(indexes.keySet()); } } @@ -77,12 +81,13 @@ public class TableMetadata { public String getCatalog() { return catalog; } - + public String getSchema() { return schema; } - - public String toString() { + + @Override + public String toString() { return "TableMetadata(" + name + ')'; } @@ -175,7 +180,7 @@ public class TableMetadata { try { rs = meta.getIndexInfo(catalog, schema, name, false, true); - + while ( rs.next() ) { if ( rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic ) { continue; @@ -192,7 +197,7 @@ public class TableMetadata { private void initColumns(DatabaseMetaData meta) throws SQLException { ResultSet rs = null; - + try { rs = meta.getColumns(catalog, schema, name, "%"); while ( rs.next() ) { @@ -205,11 +210,27 @@ 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 ab56daed6d..b4455ee720 100755 --- a/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/CMTTransaction.java @@ -27,9 +27,6 @@ package org.hibernate.transaction; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.TransactionException; @@ -48,7 +45,8 @@ import org.hibernate.util.JTAHelper; */ public class CMTTransaction implements Transaction { - private static final Logger log = LoggerFactory.getLogger(CMTTransaction.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CMTTransaction.class.getPackage().getName()); protected final JDBCContext jdbcContext; protected final TransactionFactory.Context transactionContext; @@ -68,8 +66,8 @@ public class CMTTransaction implements Transaction { return; } - log.debug("begin"); - + LOG.begin(); + boolean synchronization = jdbcContext.registerSynchronizationIfPossible(); if ( !synchronization ) { @@ -77,7 +75,7 @@ public class CMTTransaction implements Transaction { } begun = true; - + jdbcContext.afterTransactionBegin(this); } @@ -89,7 +87,7 @@ public class CMTTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - log.debug("commit"); + LOG.commit(); boolean flush = !transactionContext.isFlushModeNever() && !transactionContext.isFlushBeforeCompletionEnabled(); @@ -110,13 +108,13 @@ public class CMTTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - log.debug("rollback"); + LOG.rollback(); try { getTransaction().setRollbackOnly(); } catch (SystemException se) { - log.error("Could not set transaction to rollback only", se); + LOG.error(LOG.unableToSetTransactionToRollbackOnly(), se); throw new TransactionException("Could not set transaction to rollback only", se); } @@ -145,11 +143,11 @@ public class CMTTransaction implements Transaction { status = getTransaction().getStatus(); } catch (SystemException se) { - log.error("Could not determine transaction status", se); - throw new TransactionException("Could not determine transaction status: ", se); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); + throw new TransactionException(LOG.unableToDetermineTransactionStatus(), se); } if (status==Status.STATUS_UNKNOWN) { - throw new TransactionException("Could not determine transaction status"); + throw new TransactionException(LOG.unableToDetermineTransactionStatus()); } else { return status==Status.STATUS_ACTIVE; @@ -168,11 +166,11 @@ public class CMTTransaction implements Transaction { status = getTransaction().getStatus(); } catch (SystemException se) { - log.error("Could not determine transaction status", se); - throw new TransactionException("Could not determine transaction status", se); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); + throw new TransactionException(LOG.unableToDetermineTransactionStatus(), se); } if (status==Status.STATUS_UNKNOWN) { - throw new TransactionException("Could not determine transaction status"); + throw new TransactionException(LOG.unableToDetermineTransactionStatus()); } else { return JTAHelper.isRollback(status); @@ -191,11 +189,11 @@ public class CMTTransaction implements Transaction { status = getTransaction().getStatus(); } catch (SystemException se) { - log.error("Could not determine transaction status", se); - throw new TransactionException("Could not determine transaction status: ", se); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); + throw new TransactionException(LOG.unableToDetermineTransactionStatus(), se); } if (status==Status.STATUS_UNKNOWN) { - throw new TransactionException("Could not determine transaction status"); + throw new TransactionException(LOG.unableToDetermineTransactionStatus()); } else { return status==Status.STATUS_COMMITTED; 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 885443f9f3..3c19c20ac4 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/CacheSynchronization.java @@ -28,10 +28,6 @@ import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.TransactionException; import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.util.JTAHelper; @@ -44,7 +40,8 @@ import org.hibernate.util.JTAHelper; */ public final class CacheSynchronization implements Synchronization { - private static final Logger log = LoggerFactory.getLogger(CacheSynchronization.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CacheSynchronization.class.getPackage().getName()); private final TransactionFactory.Context ctx; private JDBCContext jdbcContext; @@ -66,25 +63,25 @@ public final class CacheSynchronization implements Synchronization { * {@inheritDoc} */ public void beforeCompletion() { - log.trace("transaction before completion callback"); + LOG.transactionBeforeCompletionCallback(); boolean flush; try { flush = !ctx.isFlushModeNever() && - ctx.isFlushBeforeCompletionEnabled() && - !JTAHelper.isRollback( transaction.getStatus() ); - //actually, this last test is probably unnecessary, since + ctx.isFlushBeforeCompletionEnabled() && + !JTAHelper.isRollback( transaction.getStatus() ); + //actually, this last test is probably unnecessary, since //beforeCompletion() doesn't get called during rollback } catch (SystemException se) { - log.error("could not determine transaction status", se); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); setRollbackOnly(); throw new TransactionException("could not determine transaction status in beforeCompletion()", se); } - + try { if (flush) { - log.trace("automatically flushing session"); + LOG.automaticallyFlushingSession(); ctx.managedFlush(); } } @@ -102,7 +99,7 @@ public final class CacheSynchronization implements Synchronization { transaction.setRollbackOnly(); } catch (SystemException se) { - log.error("could not set transaction to rollback only", se); + LOG.error(LOG.unableToSetTransactionToRollbackOnly(), se); } } @@ -110,25 +107,23 @@ public final class CacheSynchronization implements Synchronization { * {@inheritDoc} */ public void afterCompletion(int status) { - if ( log.isTraceEnabled() ) { - log.trace("transaction after completion callback, status: " + status); - } + LOG.transactionAfterCompletionCallback(status); try { jdbcContext.afterTransactionCompletion(status==Status.STATUS_COMMITTED, hibernateTransaction); } finally { if ( ctx.shouldAutoClose() && !ctx.isClosed() ) { - log.trace("automatically closing session"); + LOG.automaticallyClosingSession(); ctx.managedClose(); } } } - + /** * {@inheritDoc} */ - public String toString() { + @Override + public String toString() { return CacheSynchronization.class.getName(); } - } 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 f89813b646..c719e13966 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JDBCTransaction.java @@ -26,10 +26,6 @@ package org.hibernate.transaction; import java.sql.SQLException; import javax.transaction.Status; import javax.transaction.Synchronization; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.TransactionException; @@ -45,7 +41,9 @@ import org.hibernate.engine.transaction.SynchronizationRegistry; * @author Gavin King */ public class JDBCTransaction implements Transaction { - private static final Logger log = LoggerFactory.getLogger(JDBCTransaction.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JDBCTransaction.class.getPackage().getName()); private final SynchronizationRegistry synchronizationRegistry = new SynchronizationRegistry(); private final JDBCContext jdbcContext; @@ -75,21 +73,19 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("cannot re-start transaction after failed commit"); } - log.debug("begin"); + LOG.begin(); try { toggleAutoCommit = jdbcContext.connection().getAutoCommit(); - if ( log.isDebugEnabled() ) { - log.debug("current autocommit status: " + toggleAutoCommit); - } + LOG.currentAutoCommitStatus(toggleAutoCommit); if (toggleAutoCommit) { - log.debug("disabling autocommit"); + LOG.disablingAutoCommit(); jdbcContext.connection().setAutoCommit(false); } } catch (SQLException e) { - log.error("JDBC begin failed", e); - throw new TransactionException("JDBC begin failed: ", e); + LOG.error(LOG.jdbcBeginFailed(), e); + throw new TransactionException(LOG.jdbcBeginFailed(), e); } callback = jdbcContext.registerCallbackIfNecessary(); @@ -112,7 +108,7 @@ public class JDBCTransaction implements Transaction { transactionContext.managedClose(); } catch (HibernateException he) { - log.error("Could not close session", he); + LOG.error(LOG.unableToCloseSession(), he); //swallow, the transaction was finished } } @@ -126,7 +122,7 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - log.debug("commit"); + LOG.commit(); if ( !transactionContext.isFlushModeNever() && callback ) { transactionContext.managedFlush(); //if an exception occurs during flush, user must call rollback() @@ -139,7 +135,7 @@ public class JDBCTransaction implements Transaction { try { commitAndResetAutoCommit(); - log.debug("committed JDBC Connection"); + LOG.commitedJdbcConnection(); committed = true; if ( callback ) { jdbcContext.afterTransactionCompletion( true, this ); @@ -147,13 +143,13 @@ public class JDBCTransaction implements Transaction { notifySynchronizationsAfterTransactionCompletion( Status.STATUS_COMMITTED ); } catch (SQLException e) { - log.error("JDBC commit failed", e); + LOG.error(LOG.unableToPerformJdbcCommit(), e); commitFailed = true; if ( callback ) { jdbcContext.afterTransactionCompletion( false, this ); } notifySynchronizationsAfterTransactionCompletion( Status.STATUS_UNKNOWN ); - throw new TransactionException("JDBC commit failed", e); + throw new TransactionException(LOG.unableToPerformJdbcCommit(), e); } finally { closeIfRequired(); @@ -178,7 +174,7 @@ public class JDBCTransaction implements Transaction { throw new TransactionException("Transaction not successfully started"); } - log.debug("rollback"); + LOG.rollback(); if (!commitFailed) { @@ -189,14 +185,14 @@ public class JDBCTransaction implements Transaction { try { rollbackAndResetAutoCommit(); - log.debug("rolled back JDBC Connection"); + LOG.rolledBackJdbcConnection(); rolledBack = true; notifySynchronizationsAfterTransactionCompletion(Status.STATUS_ROLLEDBACK); } catch (SQLException e) { - log.error("JDBC rollback failed", e); + LOG.error(LOG.jdbcRollbackFailed(), e); notifySynchronizationsAfterTransactionCompletion(Status.STATUS_UNKNOWN); - throw new TransactionException("JDBC rollback failed", e); + throw new TransactionException(LOG.jdbcRollbackFailed(), e); } finally { if ( callback ) { @@ -219,12 +215,12 @@ public class JDBCTransaction implements Transaction { private void toggleAutoCommit() { try { if (toggleAutoCommit) { - log.debug("re-enabling autocommit"); + LOG.reenablingAutoCommit(); jdbcContext.connection().setAutoCommit( true ); } } catch (Exception sqle) { - log.error("Could not toggle autocommit", sqle); + LOG.error(LOG.unableToToggleAutoCommit(), sqle); //swallow it (the transaction _was_ successful or successfully rolled back) } } 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 856362414e..5bc034075c 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransaction.java @@ -29,10 +29,6 @@ import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.TransactionException; @@ -51,7 +47,8 @@ import org.hibernate.util.JTAHelper; */ public class JTATransaction implements Transaction { - private static final Logger log = LoggerFactory.getLogger( JTATransaction.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JTATransaction.class.getPackage().getName()); private final JDBCContext jdbcContext; private final TransactionFactory.Context transactionContext; @@ -83,18 +80,18 @@ public class JTATransaction implements Transaction { throw new TransactionException( "cannot re-start transaction after failed commit" ); } - log.debug( "begin" ); + LOG.begin(); try { newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION; if ( newTransaction ) { userTransaction.begin(); - log.debug( "Began a new JTA transaction" ); + LOG.beganNewJtaTransaction(); } } catch ( Exception e ) { - log.error( "JTA transaction begin failed", e ); - throw new TransactionException( "JTA transaction begin failed", e ); + LOG.error(LOG.unableToBeginJtaTransaction(), e); + throw new TransactionException(LOG.unableToBeginJtaTransaction(), e); } /*if (newTransaction) { @@ -106,9 +103,7 @@ public class JTATransaction implements Transaction { boolean synchronization = jdbcContext.registerSynchronizationIfPossible(); - if ( !newTransaction && !synchronization ) { - log.warn( "You should set hibernate.transaction.manager_lookup_class if cache is enabled" ); - } + if (!newTransaction && !synchronization) LOG.managerLookupClassShouldBeSet(); if ( !synchronization ) { //if we could not register a synchronization, @@ -134,7 +129,7 @@ public class JTATransaction implements Transaction { throw new TransactionException( "Transaction not successfully started" ); } - log.debug( "commit" ); + LOG.commit(); boolean flush = !transactionContext.isFlushModeNever() && ( callback || !transactionContext.isFlushBeforeCompletionEnabled() ); @@ -153,12 +148,12 @@ public class JTATransaction implements Transaction { try { userTransaction.commit(); commitSucceeded = true; - log.debug( "Committed JTA UserTransaction" ); + LOG.commitedJtaUserTransaction(); } catch ( Exception e ) { commitFailed = true; // so the transaction is already rolled back, by JTA spec - log.error( "JTA commit failed", e ); - throw new TransactionException( "JTA commit failed: ", e ); + LOG.error(LOG.unableToCommitJta(), e); + throw new TransactionException(LOG.unableToCommitJta(), e); } finally { afterCommitRollback(); @@ -182,31 +177,31 @@ public class JTATransaction implements Transaction { throw new TransactionException( "Transaction not successfully started" ); } - log.debug( "rollback" ); + LOG.rollback(); try { closeIfRequired(); } catch ( Exception e ) { // swallow it, and continue to roll back JTA transaction - log.error( "could not close session during rollback", e ); + LOG.error(LOG.unableToCloseSessionDuringRollback(), e); } try { if ( newTransaction ) { if ( !commitFailed ) { userTransaction.rollback(); - log.debug( "Rolled back JTA UserTransaction" ); + LOG.rolledBackJtaUserTransaction(); } } else { userTransaction.setRollbackOnly(); - log.debug( "set JTA UserTransaction to rollback only" ); + LOG.jtaUserTransactionSetToRollbackOnly(); } } catch ( Exception e ) { - log.error( "JTA rollback failed", e ); - throw new TransactionException( "JTA rollback failed", e ); + LOG.error(LOG.unableToRollbackJta(), e); + throw new TransactionException(LOG.unableToRollbackJta(), e); } finally { afterCommitRollback(); @@ -220,16 +215,14 @@ public class JTATransaction implements Transaction { begun = false; // this method is a noop if there is a Synchronization! if ( callback ) { - if ( !newTransaction ) { - log.warn( "You should set hibernate.transaction.manager_lookup_class if cache is enabled" ); - } + if (!newTransaction) LOG.managerLookupClassShouldBeSet(); int status = NULL; try { status = userTransaction.getStatus(); } catch ( Exception e ) { - log.error( "Could not determine transaction status after commit", e ); - throw new TransactionException( "Could not determine transaction status after commit", e ); + LOG.error(LOG.unableToDetermineTransactionStatusAfterCommit(), e); + throw new TransactionException(LOG.unableToDetermineTransactionStatusAfterCommit(), e); } finally { jdbcContext.afterTransactionCompletion( status == Status.STATUS_COMMITTED, this ); @@ -246,15 +239,11 @@ public class JTATransaction implements Transaction { status = userTransaction.getStatus(); } catch ( SystemException se ) { - log.error( "Could not determine transaction status", se ); - throw new TransactionException( "Could not determine transaction status", se ); - } - if ( status == Status.STATUS_UNKNOWN ) { - throw new TransactionException( "Could not determine transaction status" ); - } - else { - return JTAHelper.isRollback( status ); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); + throw new TransactionException(LOG.unableToDetermineTransactionStatus(), se); } + if (status == Status.STATUS_UNKNOWN) throw new TransactionException(LOG.unableToDetermineTransactionStatus()); + return JTAHelper.isRollback(status); } /** @@ -266,15 +255,11 @@ public class JTATransaction implements Transaction { status = userTransaction.getStatus(); } catch ( SystemException se ) { - log.error( "Could not determine transaction status", se ); - throw new TransactionException( "Could not determine transaction status: ", se ); - } - if ( status == Status.STATUS_UNKNOWN ) { - throw new TransactionException( "Could not determine transaction status" ); - } - else { - return status == Status.STATUS_COMMITTED; + LOG.error(LOG.unableToDetermineTransactionStatus(), se); + throw new TransactionException(LOG.unableToDetermineTransactionStatus(), se); } + if (status == Status.STATUS_UNKNOWN) throw new TransactionException(LOG.unableToDetermineTransactionStatus()); + return status == Status.STATUS_COMMITTED; } /** @@ -290,15 +275,11 @@ public class JTATransaction implements Transaction { status = userTransaction.getStatus(); } catch ( SystemException se ) { - log.error( "Could not determine transaction status", se ); + LOG.error(LOG.unableToDetermineTransactionStatus(), se); throw new TransactionException( "Could not determine transaction status: ", se ); } - if ( status == Status.STATUS_UNKNOWN ) { - throw new TransactionException( "Could not determine transaction status" ); - } - else { - return status == Status.STATUS_ACTIVE; - } + if (status == Status.STATUS_UNKNOWN) throw new TransactionException("Could not determine transaction status"); + return status == Status.STATUS_ACTIVE; } /** 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 82b2713545..65f1c6a149 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/JTATransactionFactory.java @@ -25,22 +25,17 @@ package org.hibernate.transaction; import java.util.Properties; - import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.TransactionException; +import org.hibernate.cfg.Environment; import org.hibernate.engine.jdbc.spi.JDBCContext; import org.hibernate.internal.util.jndi.JndiHelper; -import org.hibernate.cfg.Environment; import org.hibernate.util.JTAHelper; /** @@ -75,7 +70,9 @@ import org.hibernate.util.JTAHelper; */ public class JTATransactionFactory implements TransactionFactory { public static final String DEFAULT_USER_TRANSACTION_NAME = "java:comp/UserTransaction"; - private static final Logger log = LoggerFactory.getLogger( JTATransactionFactory.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JTATransactionFactory.class.getPackage().getName()); protected InitialContext initialContext; protected String userTransactionName; @@ -92,7 +89,7 @@ public class JTATransactionFactory implements TransactionFactory { public void configure(Properties props) throws HibernateException { this.initialContext = resolveInitialContext( props ); this.userTransactionName = resolveUserTransactionName( props ); - log.trace( "Configured JTATransactionFactory to use [{}] for UserTransaction JDNI namespace", userTransactionName ); + LOG.configuredJtaTransactionFactoryForUserTransactionJndiNamespace(userTransactionName); } /** @@ -157,7 +154,7 @@ public class JTATransactionFactory implements TransactionFactory { */ protected UserTransaction getUserTransaction() { final String utName = getUserTransactionName(); - log.trace( "Attempting to locate UserTransaction via JNDI [{}]", utName ); + LOG.attemptingToLocateUserTransactionViaJndi(utName); try { UserTransaction ut = ( UserTransaction ) getInitialContext().lookup( utName ); @@ -165,7 +162,7 @@ public class JTATransactionFactory implements TransactionFactory { throw new TransactionException( "Naming service lookup for UserTransaction returned null [" + utName +"]" ); } - log.trace( "Obtained UserTransaction" ); + LOG.obtainedUserTransaction(); return ut; } 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 903ae90faa..b18f71a312 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionFactoryFactory.java @@ -25,10 +25,6 @@ package org.hibernate.transaction; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.util.ReflectHelper; @@ -40,7 +36,8 @@ import org.hibernate.util.ReflectHelper; */ public final class TransactionFactoryFactory { - private static final Logger log = LoggerFactory.getLogger( TransactionFactoryFactory.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TransactionFactoryFactory.class.getPackage().getName()); /** * Create an appropriate transaction factory based on the given configuration @@ -56,25 +53,25 @@ public final class TransactionFactoryFactory { public static TransactionFactory buildTransactionFactory(Properties transactionProps) throws HibernateException { String strategyClassName = transactionProps.getProperty( Environment.TRANSACTION_STRATEGY ); if ( strategyClassName == null ) { - log.info( "Using default transaction strategy (direct JDBC transactions)" ); + LOG.usingDefaultTransactionStrategy(); return new JDBCTransactionFactory(); } - log.info( "Transaction strategy: " + strategyClassName ); + LOG.transactionStrategy(strategyClassName); TransactionFactory factory; try { factory = ( TransactionFactory ) ReflectHelper.classForName( strategyClassName ).newInstance(); } catch ( ClassNotFoundException e ) { - log.error( "TransactionFactory class not found", e ); - throw new HibernateException( "TransactionFactory class not found: " + strategyClassName ); + LOG.error(LOG.transactionFactoryClassNotFound(), e); + throw new HibernateException(LOG.transactionFactoryClassNotFound(strategyClassName)); } catch ( IllegalAccessException e ) { - log.error( "Failed to instantiate TransactionFactory", e ); - throw new HibernateException( "Failed to instantiate TransactionFactory: " + e ); + LOG.error(LOG.unableToInstantiateTransactionFactory(), e); + throw new HibernateException(LOG.unableToInstantiateTransactionFactory(e)); } catch ( java.lang.InstantiationException e ) { - log.error( "Failed to instantiate TransactionFactory", e ); - throw new HibernateException( "Failed to instantiate TransactionFactory: " + e ); + LOG.error(LOG.unableToInstantiateTransactionFactory(), e); + throw new HibernateException(LOG.unableToInstantiateTransactionFactory(e)); } factory.configure( transactionProps ); return factory; 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 11509cd508..5a8c58fe4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/TransactionManagerLookupFactory.java @@ -25,12 +25,7 @@ package org.hibernate.transaction; import java.util.Properties; - import javax.transaction.TransactionManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.util.ReflectHelper; @@ -42,7 +37,8 @@ import org.hibernate.util.ReflectHelper; */ public final class TransactionManagerLookupFactory { - private static final Logger log = LoggerFactory.getLogger(TransactionManagerLookupFactory.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TransactionManagerLookupFactory.class.getPackage().getName()); /** * Disallow instantiation @@ -62,7 +58,7 @@ public final class TransactionManagerLookupFactory { * {@link TransactionManagerLookup} or (b) asking it to locate the {@link TransactionManager}. */ public static TransactionManager getTransactionManager(Properties props) throws HibernateException { - log.info( "obtaining TransactionManager" ); + LOG.obtainingTransactionManager(); return getTransactionManagerLookup( props ).getTransactionManager( props ); } @@ -77,21 +73,17 @@ public final class TransactionManagerLookupFactory { public static TransactionManagerLookup getTransactionManagerLookup(Properties props) throws HibernateException { String tmLookupClass = props.getProperty( Environment.TRANSACTION_MANAGER_STRATEGY ); if ( tmLookupClass == null ) { - log.info( "No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)" ); + LOG.transactionManagerLookupNotConfigured(); return null; } - else { - log.info( "instantiating TransactionManagerLookup: " + tmLookupClass ); - try { - TransactionManagerLookup lookup = ( TransactionManagerLookup ) - ReflectHelper.classForName( tmLookupClass ).newInstance(); - log.info( "instantiated TransactionManagerLookup" ); - return lookup; - } - catch ( Exception e ) { - log.error( "Could not instantiate TransactionManagerLookup", e ); - throw new HibernateException( "Could not instantiate TransactionManagerLookup '" + tmLookupClass + "'" ); - } + LOG.instantiatingTransactionManagerLookup(tmLookupClass); + try { + TransactionManagerLookup lookup = (TransactionManagerLookup)ReflectHelper.classForName(tmLookupClass).newInstance(); + LOG.instantiatedTransactionManagerLookup(); + return lookup; + } catch (Exception e) { + LOG.error(LOG.unableToInstantiateTransactionManagerLookup(), e); + throw new HibernateException(LOG.unableToInstantiateTransactionManagerLookup(tmLookupClass)); } } } 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 57d9efdd8a..917f8c64a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java +++ b/hibernate-core/src/main/java/org/hibernate/transaction/WebSphereTransactionManagerLookup.java @@ -25,13 +25,8 @@ package org.hibernate.transaction; import java.util.Properties; - -import javax.transaction.TransactionManager; import javax.transaction.Transaction; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import javax.transaction.TransactionManager; import org.hibernate.HibernateException; /** @@ -41,10 +36,11 @@ import org.hibernate.HibernateException; */ public class WebSphereTransactionManagerLookup implements TransactionManagerLookup { - private static final Logger log = LoggerFactory.getLogger(WebSphereTransactionManagerLookup.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + WebSphereTransactionManagerLookup.class.getPackage().getName()); private final int wsVersion; private final Class tmfClass; - + /** * Constructs a new WebSphereTransactionManagerLookup. */ @@ -55,18 +51,18 @@ public class WebSphereTransactionManagerLookup implements TransactionManagerLook try { clazz = Class.forName( "com.ibm.ws.Transaction.TransactionManagerFactory" ); version = 5; - log.info( "WebSphere 5.1" ); + LOG.info("WebSphere 5.1"); } catch ( Exception e ) { try { clazz = Class.forName( "com.ibm.ejs.jts.jta.TransactionManagerFactory" ); version = 5; - log.info( "WebSphere 5.0" ); - } + LOG.info("WebSphere 5.0"); + } catch ( Exception e2 ) { clazz = Class.forName( "com.ibm.ejs.jts.jta.JTSXA" ); version = 4; - log.info( "WebSphere 4" ); + LOG.info("WebSphere 4"); } } 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 3f42cc2d8c..73ec4df3b7 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,17 +23,19 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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. @@ -41,7 +43,9 @@ import org.hibernate.util.JTAHelper; * @author Steve Ebersole */ public class CallbackCoordinator { - private static final Logger log = LoggerFactory.getLogger( CallbackCoordinator.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + CallbackCoordinator.class.getPackage().getName()); private final TransactionFactory.Context ctx; private JDBCContext jdbcContext; @@ -98,7 +102,7 @@ public class CallbackCoordinator { // sync callbacks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public void beforeCompletion() { - log.trace( "transaction before completion callback" ); + LOG.transactionBeforeCompletionCallback(); boolean flush; try { @@ -111,7 +115,7 @@ public class CallbackCoordinator { try { if ( flush ) { - log.trace( "automatically flushing session" ); + LOG.automaticallyFlushingSession(); ctx.managedFlush(); } } @@ -130,12 +134,12 @@ public class CallbackCoordinator { } catch ( SystemException se ) { // best effort - log.error( "could not set transaction to rollback only", se ); + LOG.error( LOG.unableToSetTransactionToRollbackOnly(), se ); } } public void afterCompletion(int status) { - log.trace( "transaction after completion callback [status={}]", status ); + LOG.transactionAfterCompletionCallback(status); try { afterCompletionAction.doAction( ctx, status ); @@ -147,7 +151,7 @@ public class CallbackCoordinator { reset(); jdbcContext.cleanUpJtaSynchronizationCallbackCoordinator(); if ( ctx.shouldAutoClose() && !ctx.isClosed() ) { - log.trace( "automatically closing session" ); + LOG.automaticallyClosingSession(); ctx.managedClose(); } } @@ -167,12 +171,12 @@ public class CallbackCoordinator { private static final ExceptionMapper STANDARD_EXCEPTION_MAPPER = new ExceptionMapper() { public RuntimeException mapStatusCheckFailure(String message, SystemException systemException) { - log.error( "could not determine transaction status [{}]", systemException.getMessage() ); + LOG.unableToDetermineTransactionStatus(systemException.getMessage()); return new TransactionException( "could not determine transaction status in beforeCompletion()", systemException ); } public RuntimeException mapManagedFlushFailure(String message, RuntimeException failure) { - log.error( "Error during managed flush [{}]", failure.getMessage() ); + LOG.unableToPerformManagedFlush(failure.getMessage()); return failure; } }; @@ -182,4 +186,38 @@ 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 5cd3c5ba48..bd63475bdf 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,10 +23,12 @@ */ package org.hibernate.transaction.synchronization; +import static org.jboss.logging.Logger.Level.TRACE; import javax.transaction.Synchronization; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * The {@link Synchronization} implementation Hibernate registers with the JTA {@link javax.transaction.Transaction} @@ -35,7 +37,9 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class HibernateSynchronizationImpl implements Synchronization { - private static final Logger log = LoggerFactory.getLogger( HibernateSynchronizationImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + HibernateSynchronizationImpl.class.getPackage().getName()); private final CallbackCoordinator coordinator; @@ -47,7 +51,7 @@ public class HibernateSynchronizationImpl implements Synchronization { * {@inheritDoc} */ public void beforeCompletion() { - log.trace( "JTA sync : beforeCompletion()" ); + LOG.jtaSyncBeforeCompletion(); coordinator.beforeCompletion(); } @@ -55,7 +59,22 @@ public class HibernateSynchronizationImpl implements Synchronization { * {@inheritDoc} */ public void afterCompletion(int status) { - log.trace( "JTA sync : afterCompletion({})", status ); + LOG.jtaSyncAfterCompletion(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 e255dedb09..4a3cdd1a13 100644 --- a/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/transform/DistinctResultTransformer.java @@ -24,14 +24,15 @@ */ package org.hibernate.transform; -import java.util.List; +import static org.jboss.logging.Logger.Level.DEBUG; import java.util.ArrayList; -import java.util.Set; import java.util.HashSet; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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; /** * Distinctions the result tuples in the final result based on the defined @@ -46,7 +47,8 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { public static final DistinctResultTransformer INSTANCE = new DistinctResultTransformer(); - private static final Logger log = LoggerFactory.getLogger( DistinctResultTransformer.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DistinctResultTransformer.class.getPackage().getName()); /** * Helper class to handle distincting @@ -61,7 +63,8 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { /** * {@inheritDoc} */ - public boolean equals(Object other) { + @Override + public boolean equals(Object other) { return Identity.class.isInstance( other ) && this.entity == ( ( Identity ) other ).entity; } @@ -69,7 +72,8 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { /** * {@inheritDoc} */ - public int hashCode() { + @Override + public int hashCode() { return System.identityHashCode( entity ); } } @@ -83,7 +87,8 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { /** * Uniquely distinct each tuple row here. */ - public List transformList(List list) { + @Override + public List transformList(List list) { List result = new ArrayList( list.size() ); Set distinct = new HashSet(); for ( int i = 0; i < list.size(); i++ ) { @@ -92,13 +97,7 @@ public class DistinctResultTransformer extends BasicTransformerAdapter { result.add( entity ); } } - if ( log.isDebugEnabled() ) { - log.debug( - "transformed: " + - list.size() + " rows to: " + - result.size() + " distinct results" - ); - } + LOG.transformed(list.size(), result.size()); return result; } @@ -110,4 +109,16 @@ 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 b295d925f2..43fc4b32f4 100755 --- a/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/PojoInstantiator.java @@ -24,25 +24,28 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.InstantiationException; import org.hibernate.PropertyNotFoundException; import org.hibernate.bytecode.ReflectionOptimizer; -import org.hibernate.mapping.PersistentClass; 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. */ public class PojoInstantiator implements Instantiator, Serializable { - private static final Logger log = LoggerFactory.getLogger(PojoInstantiator.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PojoInstantiator.class.getPackage().getName()); private transient Constructor constructor; @@ -62,11 +65,7 @@ public class PojoInstantiator implements Instantiator, Serializable { constructor = ReflectHelper.getDefaultConstructor(mappedClass); } catch ( PropertyNotFoundException pnfe ) { - log.info( - "no default (no-argument) constructor for class: " + - mappedClass.getName() + - " (class must be instantiated by Interceptor)" - ); + LOG.noDefaultConstructor(mappedClass.getName()); constructor = null; } } @@ -81,11 +80,7 @@ public class PojoInstantiator implements Instantiator, Serializable { constructor = ReflectHelper.getDefaultConstructor( mappedClass ); } catch ( PropertyNotFoundException pnfe ) { - log.info( - "no default (no-argument) constructor for class: " + - mappedClass.getName() + - " (class must be instantiated by Interceptor)" - ); + LOG.noDefaultConstructor(mappedClass.getName()); constructor = null; } } @@ -115,16 +110,27 @@ public class PojoInstantiator implements Instantiator, Serializable { } } } - + public Object instantiate(Serializable id) { - final boolean useEmbeddedIdentifierInstanceAsEntity = embeddedIdentifier && - id != null && + final boolean useEmbeddedIdentifierInstanceAsEntity = embeddedIdentifier && + id != null && id.getClass().equals(mappedClass); return useEmbeddedIdentifierInstanceAsEntity ? id : instantiate(); } public boolean isInstance(Object object) { - return mappedClass.isInstance(object) || + 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 2b8d9be929..4c9e62aab2 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,14 +23,11 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.MappingException; @@ -56,6 +53,10 @@ 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; /** @@ -66,7 +67,8 @@ import org.hibernate.type.Type; */ public abstract class AbstractEntityTuplizer implements EntityTuplizer { - private static final Logger log = LoggerFactory.getLogger( AbstractEntityTuplizer.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + AbstractEntityTuplizer.class.getPackage().getName()); //TODO: currently keeps Getters and Setters (instead of PropertyAccessors) because of the way getGetter() and getSetter() are implemented currently; yuck! @@ -172,7 +174,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { else { proxyFactory = null; } - + Component mapper = mappingInfo.getIdentifierMapper(); if ( mapper == null ) { identifierMapperType = null; @@ -369,7 +371,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { subId = pcEntry.getId(); } else { - log.debug( "Performing implicit derived identity cascade" ); + LOG.performingImplicitDerivedIdentityCascade(); 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 ); @@ -488,7 +490,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { return result; } - public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session) + public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session) throws HibernateException { final int span = entityMetamodel.getPropertySpan(); final Object[] result = new Object[span]; @@ -562,7 +564,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { else { return baseValue; } - + } private int findSubPropertyIndex(ComponentType type, String subPropertyName) { @@ -638,7 +640,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { public boolean isValidatableImplementor() { return false; } - + protected final EntityMetamodel getEntityMetamodel() { return entityMetamodel; } @@ -654,8 +656,9 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer { protected final ProxyFactory getProxyFactory() { return proxyFactory; } - - public String toString() { + + @Override + public String toString() { return getClass().getName() + '(' + getEntityMetamodel().getName() + ')'; } @@ -673,4 +676,15 @@ 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 c371ec9335..b7edffae2b 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 @@ -28,11 +28,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; - import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; @@ -50,6 +46,9 @@ 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. @@ -59,7 +58,8 @@ import org.hibernate.type.CompositeType; */ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { - static final Logger log = LoggerFactory.getLogger( Dom4jEntityTuplizer.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + Dom4jEntityTuplizer.class.getPackage().getName()); private Map inheritenceNodeNameMap = new HashMap(); @@ -72,7 +72,7 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { inheritenceNodeNameMap.put( mapping.getNodeName(), mapping.getEntityName() ); } } - + /** * {@inheritDoc} */ @@ -85,8 +85,8 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { return mappedProperty.getPropertyAccessor(null); } else { - return PropertyAccessorFactory.getDom4jPropertyAccessor( - mappedProperty.getNodeName(), + return PropertyAccessorFactory.getDom4jPropertyAccessor( + mappedProperty.getNodeName(), mappedProperty.getType(), getEntityMetamodel().getSessionFactory() ); @@ -96,35 +96,40 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { return buildPropertyAccessor(mappedProperty).getGetter( null, mappedProperty.getName() ); } /** * {@inheritDoc} */ - protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { return buildPropertyAccessor(mappedProperty).getSetter( null, mappedProperty.getName() ); } /** * {@inheritDoc} */ - protected Instantiator buildInstantiator(PersistentClass persistentClass) { + @Override + protected Instantiator buildInstantiator(PersistentClass persistentClass) { return new Dom4jInstantiator( persistentClass ); } /** * {@inheritDoc} */ - public Serializable getIdentifier(Object entityOrId) throws HibernateException { + @Override + public Serializable getIdentifier(Object entityOrId) throws HibernateException { return getIdentifier( entityOrId, null ); } /** * {@inheritDoc} */ - public Serializable getIdentifier(Object entityOrId, SessionImplementor session) { + @Override + public Serializable getIdentifier(Object entityOrId, SessionImplementor session) { if ( entityOrId instanceof Element ) { return super.getIdentifier( entityOrId, session ); } @@ -137,7 +142,8 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) { + @Override + protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) { HashSet proxyInterfaces = new HashSet(); proxyInterfaces.add( HibernateProxy.class ); proxyInterfaces.add( Element.class ); @@ -156,7 +162,7 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { ); } catch ( HibernateException he ) { - log.warn( "could not create proxy factory for:" + getEntityName(), he ); + LOG.warn(LOG.unableToCreateProxyFactory(getEntityName()), he); pf = null; } return pf; @@ -220,15 +226,27 @@ public class Dom4jEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) { return rootEntityName.equals( ( ( BasicEntityNameResolver ) obj ).rootEntityName ); } /** * {@inheritDoc} */ - public int hashCode() { + @Override + public int hashCode() { 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 1bbdea3445..174e53afbe 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 @@ -24,23 +24,23 @@ package org.hibernate.tuple.entity; import java.util.Map; - import org.hibernate.EntityMode; -import org.hibernate.HibernateException; import org.hibernate.EntityNameResolver; +import org.hibernate.HibernateException; import org.hibernate.engine.SessionFactoryImplementor; -import org.hibernate.tuple.Instantiator; -import org.hibernate.tuple.DynamicMapInstantiator; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.property.Getter; import org.hibernate.property.PropertyAccessor; import org.hibernate.property.PropertyAccessorFactory; import org.hibernate.property.Setter; -import org.hibernate.proxy.map.MapProxyFactory; import org.hibernate.proxy.ProxyFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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. @@ -50,12 +50,13 @@ import org.slf4j.LoggerFactory; */ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer { - static final Logger log = LoggerFactory.getLogger( DynamicMapEntityTuplizer.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DynamicMapEntityTuplizer.class.getPackage().getName()); DynamicMapEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) { super(entityMetamodel, mappedEntity); } - + /** * {@inheritDoc} */ @@ -75,28 +76,32 @@ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { return buildPropertyAccessor(mappedProperty).getGetter( null, mappedProperty.getName() ); } /** * {@inheritDoc} */ - protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { return buildPropertyAccessor(mappedProperty).getSetter( null, mappedProperty.getName() ); } /** * {@inheritDoc} */ - protected Instantiator buildInstantiator(PersistentClass mappingInfo) { + @Override + protected Instantiator buildInstantiator(PersistentClass mappingInfo) { return new DynamicMapInstantiator( mappingInfo ); } /** * {@inheritDoc} */ - protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) { + @Override + protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) { ProxyFactory pf = new MapProxyFactory(); try { @@ -111,7 +116,7 @@ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer { ); } catch ( HibernateException he ) { - log.warn( "could not create proxy factory for:" + getEntityName(), he ); + LOG.warn(LOG.unableToCreateProxyFactory(getEntityName()), he); pf = null; } return pf; @@ -173,15 +178,27 @@ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) { return getClass().equals( obj.getClass() ); } /** * {@inheritDoc} */ - public int hashCode() { + @Override + public int hashCode() { 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 919cc64a52..46cda4abfb 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,6 +23,8 @@ */ 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; @@ -31,10 +33,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.MappingException; @@ -57,6 +55,10 @@ 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. @@ -65,7 +67,8 @@ import org.hibernate.util.ReflectHelper; */ public class EntityMetamodel implements Serializable { - private static final Logger log = LoggerFactory.getLogger(EntityMetamodel.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + EntityMetamodel.class.getPackage().getName()); private static final int NO_VERSION_INDX = -66; @@ -259,9 +262,7 @@ public class EntityMetamodel implements Serializable { hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId; versionPropertyIndex = tempVersionProperty; hasLazyProperties = hasLazy; - if ( hasLazyProperties ) { - log.info( "lazy property fetching available for: " + name ); - } + if (hasLazyProperties) LOG.lazyPropertyFetchingAvailable(name); lazy = persistentClass.isLazy() && ( // TODO: this disables laziness even in non-pojo entity modes: @@ -278,7 +279,7 @@ public class EntityMetamodel implements Serializable { isAbstract = persistentClass.isAbstract().booleanValue(); if ( !isAbstract && persistentClass.hasPojoRepresentation() && ReflectHelper.isAbstractClass( persistentClass.getMappedClass() ) ) { - log.warn( "entity [" + name + "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names" ); + LOG.entityMappedAsNonAbstract(name); } } selectBeforeUpdate = persistentClass.hasSelectBeforeUpdate(); @@ -578,7 +579,8 @@ public class EntityMetamodel implements Serializable { return ( String ) entityNameByInheritenceClassMap.get( inheritenceClass ); } - public String toString() { + @Override + public String toString() { return "EntityMetamodel(" + name + ':' + ArrayHelper.toString(properties) + ')'; } @@ -639,5 +641,18 @@ public class EntityMetamodel implements Serializable { 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 fdae321808..6287d51de9 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,16 +23,13 @@ */ 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; import java.util.Iterator; import java.util.Map; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.EntityMode; import org.hibernate.EntityNameResolver; import org.hibernate.HibernateException; @@ -56,6 +53,10 @@ 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. @@ -64,7 +65,9 @@ import org.hibernate.util.ReflectHelper; * @author Gavin King */ public class PojoEntityTuplizer extends AbstractEntityTuplizer { - static final Logger log = LoggerFactory.getLogger( PojoEntityTuplizer.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + PojoEntityTuplizer.class.getPackage().getName()); private final Class mappedClass; private final Class proxyInterface; @@ -107,18 +110,19 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { // mappedClass, getterNames, setterNames, propTypes // ); } - + } /** * {@inheritDoc} */ - protected ProxyFactory buildProxyFactory(PersistentClass persistentClass, Getter idGetter, Setter idSetter) { + @Override + protected ProxyFactory buildProxyFactory(PersistentClass persistentClass, Getter idGetter, Setter idSetter) { // determine the id getter and setter methods from the proxy interface (if any) // determine all interfaces needed by the resulting proxy HashSet proxyInterfaces = new HashSet(); proxyInterfaces.add( HibernateProxy.class ); - + Class mappedClass = persistentClass.getMappedClass(); Class proxyInterface = persistentClass.getProxyInterface(); @@ -156,27 +160,21 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { Property property = (Property) properties.next(); Method method = property.getGetter(clazz).getMethod(); if ( method != null && Modifier.isFinal( method.getModifiers() ) ) { - log.error( - "Getters of lazy classes cannot be final: " + persistentClass.getEntityName() + - "." + property.getName() - ); + LOG.gettersOfLazyClassesCannotBeFinal(persistentClass.getEntityName(), property.getName()); } method = property.getSetter(clazz).getMethod(); if ( method != null && Modifier.isFinal( method.getModifiers() ) ) { - log.error( - "Setters of lazy classes cannot be final: " + persistentClass.getEntityName() + - "." + property.getName() - ); + LOG.settersOfLazyClassesCannotBeFinal(persistentClass.getEntityName(), property.getName()); } } Method idGetterMethod = idGetter==null ? null : idGetter.getMethod(); Method idSetterMethod = idSetter==null ? null : idSetter.getMethod(); - Method proxyGetIdentifierMethod = idGetterMethod==null || proxyInterface==null ? + Method proxyGetIdentifierMethod = idGetterMethod==null || proxyInterface==null ? null : ReflectHelper.getMethod(proxyInterface, idGetterMethod); - Method proxySetIdentifierMethod = idSetterMethod==null || proxyInterface==null ? + Method proxySetIdentifierMethod = idSetterMethod==null || proxyInterface==null ? null : ReflectHelper.getMethod(proxyInterface, idSetterMethod); @@ -194,7 +192,7 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { ); } catch ( HibernateException he ) { - log.warn( "could not create proxy factory for:" + getEntityName(), he ); + LOG.warn(LOG.unableToCreateProxyFactory(getEntityName()), he); pf = null; } return pf; @@ -209,7 +207,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - protected Instantiator buildInstantiator(PersistentClass persistentClass) { + @Override + protected Instantiator buildInstantiator(PersistentClass persistentClass) { if ( optimizer == null ) { return new PojoInstantiator( persistentClass, null ); } @@ -221,7 +220,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public void setPropertyValues(Object entity, Object[] values) throws HibernateException { + @Override + public void setPropertyValues(Object entity, Object[] values) throws HibernateException { if ( !getEntityMetamodel().hasLazyProperties() && optimizer != null && optimizer.getAccessOptimizer() != null ) { setPropertyValuesWithOptimizer( entity, values ); } @@ -233,7 +233,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public Object[] getPropertyValues(Object entity) throws HibernateException { + @Override + public Object[] getPropertyValues(Object entity) throws HibernateException { if ( shouldGetAllProperties( entity ) && optimizer != null && optimizer.getAccessOptimizer() != null ) { return getPropertyValuesWithOptimizer( entity ); } @@ -245,7 +246,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session) throws HibernateException { + @Override + public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session) throws HibernateException { if ( shouldGetAllProperties( entity ) && optimizer != null && optimizer.getAccessOptimizer() != null ) { return getPropertyValuesWithOptimizer( entity ); } @@ -279,28 +281,32 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public boolean isLifecycleImplementor() { + @Override + public boolean isLifecycleImplementor() { return lifecycleImplementor; } /** * {@inheritDoc} */ - public boolean isValidatableImplementor() { + @Override + public boolean isValidatableImplementor() { return validatableImplementor; } /** * {@inheritDoc} */ - protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) { return mappedProperty.getGetter( mappedEntity.getMappedClass() ); } /** * {@inheritDoc} */ - protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { + @Override + protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) { return mappedProperty.getSetter( mappedEntity.getMappedClass() ); } @@ -316,7 +322,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session) { + @Override + public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session) { if ( isInstrumented() ) { Set lazyProps = lazyPropertiesAreUnfetched && getEntityMetamodel().hasLazyProperties() ? lazyPropertyNames : null; @@ -329,7 +336,8 @@ public class PojoEntityTuplizer extends AbstractEntityTuplizer { /** * {@inheritDoc} */ - public boolean hasUninitializedLazyProperties(Object entity) { + @Override + public boolean hasUninitializedLazyProperties(Object entity) { if ( getEntityMetamodel().hasLazyProperties() ) { FieldInterceptor callback = FieldInterceptionHelper.extractFieldInterceptor( entity ); return callback != null && !callback.isInitialized(); @@ -372,4 +380,24 @@ 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 7e9789ba16..8dc9225f9f 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java @@ -23,16 +23,19 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; 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 @@ -40,7 +43,9 @@ import org.hibernate.usertype.UserType; * @author Steve Ebersole */ public class BasicTypeRegistry implements Serializable { - private static final Logger log = LoggerFactory.getLogger( BasicTypeRegistry.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicTypeRegistry.class.getPackage().getName()); // TODO : analyze these sizing params; unfortunately this seems to be the only way to give a "concurrencyLevel" private Map registry = new ConcurrentHashMap( 100, .75f, 1 ); @@ -132,20 +137,14 @@ public class BasicTypeRegistry implements Serializable { throw new HibernateException( "Type to register cannot be null" ); } - if ( type.getRegistrationKeys() == null || type.getRegistrationKeys().length == 0 ) { - log.warn( "Type [{}] defined no registration keys; ignoring", type ); - } + if (type.getRegistrationKeys() == null || type.getRegistrationKeys().length == 0) LOG.typeDefinedNoRegistrationKeys(type); for ( String key : type.getRegistrationKeys() ) { // be safe... - if ( key == null ) { - continue; - } - log.debug( "Adding type registration {} -> {}", key, type ); + if (key == null) continue; + LOG.addingTypeRegistration(key, type); final Type old = registry.put( key, type ); - if ( old != null && old != type ) { - log.info( "Type registration [{}] overrides previous : {}", key, old ); - } + if (old != null && old != type) LOG.typeRegistrationOverridesPrevious(key, old); } } @@ -164,4 +163,25 @@ 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 46df7b29c0..1dd57ad318 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/DbTimestampType.java @@ -23,18 +23,20 @@ */ package org.hibernate.type; -import java.sql.Timestamp; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.ResultSet; +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.engine.SessionImplementor; import org.hibernate.dialect.Dialect; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -50,9 +52,11 @@ import org.slf4j.LoggerFactory; public class DbTimestampType extends TimestampType { public static final DbTimestampType INSTANCE = new DbTimestampType(); - private static final Logger log = LoggerFactory.getLogger( DbTimestampType.class ); - - public String getName() { + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DbTimestampType.class.getPackage().getName()); + + @Override + public String getName() { return "dbtimestamp"; } @@ -61,13 +65,14 @@ public class DbTimestampType extends TimestampType { return new String[] { getName() }; } - public Date seed(SessionImplementor session) { + @Override + public Date seed(SessionImplementor session) { if ( session == null ) { - log.trace( "incoming session was null; using current jvm time" ); + LOG.incomingSessionWasNull(); return super.seed( session ); } else if ( !session.getFactory().getDialect().supportsCurrentTimestampSelection() ) { - log.debug( "falling back to vm-based timestamp, as dialect does not support current timestamp selection" ); + LOG.fallingBackToVmBasedTimestamp(); return super.seed( session ); } else { @@ -93,13 +98,7 @@ public class DbTimestampType extends TimestampType { ResultSet rs = ps.executeQuery(); rs.next(); Timestamp ts = rs.getTimestamp( 1 ); - if ( log.isTraceEnabled() ) { - log.trace( - "current timestamp retreived from db : " + ts + - " (nanos=" + ts.getNanos() + - ", time=" + ts.getTime() + ")" - ); - } + LOG.currentTimestampRetrievedFromDatabase(ts, ts.getNanos(), ts.getTime()); return ts; } catch( SQLException sqle ) { @@ -115,7 +114,7 @@ public class DbTimestampType extends TimestampType { ps.close(); } catch( SQLException sqle ) { - log.warn( "unable to clean up prepared statement", sqle ); + LOG.warn(LOG.unableToCleanUpPreparedStatement(), sqle); } } } @@ -128,13 +127,7 @@ public class DbTimestampType extends TimestampType { cs.registerOutParameter( 1, java.sql.Types.TIMESTAMP ); cs.execute(); Timestamp ts = cs.getTimestamp( 1 ); - if ( log.isTraceEnabled() ) { - log.trace( - "current timestamp retreived from db : " + ts + - " (nanos=" + ts.getNanos() + - ", time=" + ts.getTime() + ")" - ); - } + LOG.currentTimestampRetrievedFromDatabase(ts, ts.getNanos(), ts.getTime()); return ts; } catch( SQLException sqle ) { @@ -150,9 +143,36 @@ public class DbTimestampType extends TimestampType { cs.close(); } catch( SQLException sqle ) { - log.warn( "unable to clean up callable statement", sqle ); + LOG.warn(LOG.unableToCleanUpCallableStatement(), sqle); } } } } + + /** + * 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 b30571ad2a..75135a00e3 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/EnumType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/EnumType.java @@ -29,15 +29,10 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.usertype.EnhancedUserType; import org.hibernate.usertype.ParameterizedType; import org.hibernate.util.ReflectHelper; -import org.hibernate.util.StringHelper; /** * Enum type mapper @@ -50,24 +45,8 @@ import org.hibernate.util.StringHelper; */ @SuppressWarnings("unchecked") public class EnumType implements EnhancedUserType, ParameterizedType, Serializable { - /** - * This is the old scheme where logging of parameter bindings and value extractions - * was controlled by the trace level enablement on the 'org.hibernate.type' package... - *

        - * Originally was cached such because of performance of looking up the logger each time - * in order to check the trace-enablement. Driving this via a central Log-specific class - * would alleviate that performance hit, and yet still allow more "normal" logging usage/config. - */ - private static final boolean IS_VALUE_TRACING_ENABLED = LoggerFactory.getLogger( StringHelper.qualifier( Type.class.getName() ) ) - .isTraceEnabled(); - private transient Logger log; - private Logger log() { - if ( log == null ) { - log = LoggerFactory.getLogger( getClass() ); - } - return log; - } + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, EnumType.class.getPackage().getName()); public static final String ENUM = "enumClass"; public static final String SCHEMA = "schema"; @@ -100,27 +79,20 @@ 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 ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Returning null as column {}", names[0] ); - } + if (LOG.isTraceEnabled()) LOG.returningAsColumn(names[0]); return null; } if ( object instanceof Number ) { initEnumValues(); int ordinal = ( ( Number ) object ).intValue(); - if ( ordinal < 0 || ordinal >= enumValues.length ) { - throw new IllegalArgumentException( "Unknown ordinal value for enum " + enumClass + ": " + ordinal ); - } - if ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Returning '{}' as column {}", ordinal, names[0] ); - } + if (ordinal < 0 || ordinal >= enumValues.length) throw new IllegalArgumentException("Unknown ordinal value for enum " + + enumClass + ": " + ordinal); + if (LOG.isTraceEnabled()) LOG.returningAsColumn(ordinal, names[0]); return enumValues[ordinal]; } else { String name = ( String ) object; - if ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Returning '{}' as column {}", name, names[0] ); - } + if (LOG.isTraceEnabled()) LOG.returningAsColumn(name, names[0]); try { return Enum.valueOf( enumClass, name ); } @@ -132,25 +104,19 @@ public class EnumType implements EnhancedUserType, ParameterizedType, Serializab public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if ( value == null ) { - if ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Binding null to parameter: {}", index ); - } + if (LOG.isTraceEnabled()) LOG.bindingToParameter(index); st.setNull( index, sqlType ); } else { boolean isOrdinal = isOrdinal( sqlType ); if ( isOrdinal ) { int ordinal = ( ( Enum ) value ).ordinal(); - if ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Binding '{}' to parameter: {}", ordinal, index ); - } + if (LOG.isTraceEnabled()) LOG.bindingToParameter(ordinal, index); st.setObject( index, Integer.valueOf( ordinal ), sqlType ); } else { String enumString = ( ( Enum ) value ).name(); - if ( IS_VALUE_TRACING_ENABLED ) { - log().debug( "Binding '{}' to parameter: {}", enumString, index ); - } + if (LOG.isTraceEnabled()) LOG.bindingToParameter(enumString, index); st.setObject( index, enumString, sqlType ); } } 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 d024a8b97e..3de5a459d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/NullableType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/NullableType.java @@ -26,11 +26,7 @@ package org.hibernate.type; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; import org.dom4j.Node; - import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.engine.Mapping; @@ -38,34 +34,20 @@ import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; import org.hibernate.util.ArrayHelper; import org.hibernate.util.EqualsHelper; -import org.hibernate.util.StringHelper; /** * Superclass of single-column nullable types. - * + * * @author Gavin King * * @deprecated Use the {@link AbstractStandardBasicType} approach instead */ +@Deprecated public abstract class NullableType extends AbstractType implements StringRepresentableType, XmlRepresentableType { - /** - * This is the old scheme where logging of parameter bindings and value extractions - * was controlled by the trace level enablement on the 'org.hibernate.type' package... - *

        - * Originally was cached such because of performance of looking up the logger each time - * in order to check the trace-enablement. Driving this via a central Log-specific class - * would alleviate that performance hit, and yet still allow more "normal" logging usage/config. - */ - private static final boolean IS_VALUE_TRACING_ENABLED = LoggerFactory.getLogger( StringHelper.qualifier( Type.class.getName() ) ).isTraceEnabled(); - private transient Logger log; - private Logger log() { - if ( log == null ) { - log = LoggerFactory.getLogger( getClass() ); - } - return log; - } + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + NullableType.class.getPackage().getName()); /** * Get a column value from a result set, without worrying about the @@ -141,26 +123,22 @@ public abstract class NullableType extends AbstractType implements StringReprese throws HibernateException, SQLException { try { if ( value == null ) { - if ( IS_VALUE_TRACING_ENABLED ) { - log().trace( "binding null to parameter: " + index ); - } + if (LOG.isTraceEnabled()) LOG.bindingToParameter(index); st.setNull( index, sqlType() ); } else { - if ( IS_VALUE_TRACING_ENABLED ) { - log().trace( "binding '" + toString( value ) + "' to parameter: " + index ); - } + if (LOG.isTraceEnabled()) LOG.bindingToParameter(toString(value), index); set( st, value, index ); } } catch ( RuntimeException re ) { - log().info( "could not bind value '" + nullSafeToString( value ) + "' to parameter: " + index + "; " + re.getMessage() ); + LOG.unableToBindValueToParameter(nullSafeToString(value), index, re.getMessage()); throw re; } catch ( SQLException se ) { - log().info( "could not bind value '" + nullSafeToString( value ) + "' to parameter: " + index + "; " + se.getMessage() ); + LOG.unableToBindValueToParameter(nullSafeToString(value), index, se.getMessage()); throw se; } } @@ -184,24 +162,18 @@ public abstract class NullableType extends AbstractType implements StringReprese try { Object value = get(rs, name); if ( value == null || rs.wasNull() ) { - if ( IS_VALUE_TRACING_ENABLED ) { - log().trace( "returning null as column: " + name ); - } + if (LOG.isTraceEnabled()) LOG.returningAsColumn(name); return null; } - else { - if ( IS_VALUE_TRACING_ENABLED ) { - log().trace( "returning '" + toString( value ) + "' as column: " + name ); - } - return value; - } + if (LOG.isTraceEnabled()) LOG.returningAsColumn(toString(value), name); + return value; } catch ( RuntimeException re ) { - log().info( "could not read column value from result set: " + name + "; " + re.getMessage() ); + LOG.unableToReadColumnValueFromResultSet(name, re.getMessage()); throw re; } catch ( SQLException se ) { - log().info( "could not read column value from result set: " + name + "; " + se.getMessage() ); + LOG.unableToReadColumnValueFromResultSet(name, se.getMessage()); throw se; } } @@ -228,7 +200,8 @@ public abstract class NullableType extends AbstractType implements StringReprese return new int[] { sqlType() }; } - public final boolean isEqual(Object x, Object y, EntityMode entityMode) { + @Override + public final boolean isEqual(Object x, Object y, EntityMode entityMode) { return isEqual(x, y); } 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 5a08ec00f2..b2fd85342c 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/type/TypeFactory.java @@ -26,10 +26,6 @@ package org.hibernate.type; import java.io.Serializable; import java.util.Comparator; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.classic.Lifecycle; @@ -44,7 +40,7 @@ import org.hibernate.util.ReflectHelper; /** * Used internally to build instances of {@link Type}, specifically it builds instances of * - * + * * Used internally to obtain instances of Type. Applications should use static methods * and constants on org.hibernate.Hibernate. * @@ -53,7 +49,9 @@ import org.hibernate.util.ReflectHelper; */ @SuppressWarnings({ "unchecked" }) public final class TypeFactory implements Serializable { - private static final Logger log = LoggerFactory.getLogger( TypeFactory.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + TypeFactory.class.getPackage().getName()); private final TypeScopeImpl typeScope = new TypeScopeImpl(); @@ -65,12 +63,8 @@ public final class TypeFactory implements Serializable { private SessionFactoryImplementor factory; public void injectSessionFactory(SessionFactoryImplementor factory) { - if ( this.factory != null ) { - log.warn( "Scoping types to session factory {} after already scoped {}", this.factory, factory ); - } - else { - log.trace( "Scoping types to session factory {}", factory ); - } + if (this.factory != null) LOG.scopingTypesToSessionFactoryAfterAlreadyScoped(this.factory, factory); + else LOG.scopingTypesToSessionFactory(factory); this.factory = factory; } @@ -88,15 +82,15 @@ public final class TypeFactory implements Serializable { public Type byClass(Class clazz, Properties parameters) { if ( Type.class.isAssignableFrom( clazz ) ) { - return type( (Class) clazz, parameters ); + return type( clazz, parameters ); } if ( CompositeUserType.class.isAssignableFrom( clazz ) ) { - return customComponent( (Class) clazz, parameters ); + return customComponent( clazz, parameters ); } if ( UserType.class.isAssignableFrom( clazz ) ) { - return custom( (Class) clazz, parameters ); + return custom( clazz, parameters ); } if ( Lifecycle.class.isAssignableFrom( clazz ) || Validatable.class.isAssignableFrom( clazz ) ) { @@ -138,7 +132,8 @@ public final class TypeFactory implements Serializable { /** * @deprecated Only for use temporary use by {@link org.hibernate.Hibernate} */ - @SuppressWarnings({ "JavaDoc" }) + @Deprecated + @SuppressWarnings({ "JavaDoc" }) public static CompositeCustomType customComponent(Class typeClass, Properties parameters, TypeScope scope) { try { CompositeUserType userType = typeClass.newInstance(); @@ -177,7 +172,8 @@ public final class TypeFactory implements Serializable { /** * @deprecated Only for use temporary use by {@link org.hibernate.Hibernate} */ - public static CustomType custom(Class typeClass, Properties parameters, TypeScope scope) { + @Deprecated + public static CustomType custom(Class typeClass, Properties parameters, TypeScope scope) { try { UserType userType = typeClass.newInstance(); injectParameters( userType, parameters ); 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 36ca04de98..4b50cc9847 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,16 +23,17 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; /** * TODO : javadoc @@ -40,7 +41,9 @@ import org.hibernate.HibernateException; * @author Steve Ebersole */ public class JdbcTypeNameMapper { - private static final Logger log = LoggerFactory.getLogger( JdbcTypeNameMapper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JdbcTypeNameMapper.class.getPackage().getName()); private static Map JDBC_TYPE_MAP = buildJdbcTypeMap(); private static Map buildJdbcTypeMap() { @@ -56,9 +59,7 @@ public class JdbcTypeNameMapper { Integer.valueOf( code ), field.getName() ); - if ( old != null ) { - log.info( "java.sql.Types mapped the same code [" + code + "] multiple times; was [" + old + "]; now [" + field.getName() + "]" ); - } + if (old != null) LOG.JavaSqlTypesMappedSameCodeMultipleTimes(code, old, field.getName()); } catch ( IllegalAccessException e ) { throw new HibernateException( "Unable to access JDBC type mapping [" + field.getName() + "]", e ); @@ -78,4 +79,17 @@ 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 6e1ce56330..c844309c22 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,18 +23,19 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.HibernateException; 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 @@ -42,7 +43,9 @@ import org.hibernate.util.ReflectHelper; * @author Steve Ebersole */ public class DataHelper { - private static final Logger log = LoggerFactory.getLogger( DataHelper.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DataHelper.class.getPackage().getName()); private static Class nClobClass; static { @@ -51,7 +54,7 @@ public class DataHelper { nClobClass = ReflectHelper.classForName( "java.sql.NClob", DataHelper.class ); } catch ( ClassNotFoundException e ) { - log.info( "Could not locate 'java.sql.NClob' class; assuming JDBC 3" ); + LOG.unableToLocateNClobClass(); } } @@ -87,7 +90,7 @@ public class DataHelper { reader.close(); } catch (IOException e) { - log.warn( "IOException occurred closing stream", e ); + LOG.warn(LOG.unableToCloseStream(), e); } } return stringBuilder.toString(); @@ -178,13 +181,13 @@ public class DataHelper { inputStream.close(); } catch ( IOException e ) { - log.warn( "IOException occurred closing input stream", e ); + LOG.warn(LOG.unableToCloseInputStream(), e); } try { outputStream.close(); } catch ( IOException e ) { - log.warn( "IOException occurred closing output stream", e ); + LOG.warn(LOG.unableToCloseOutputStream(), e); } } return outputStream.toByteArray(); @@ -250,4 +253,24 @@ 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 c3e7e83162..f75812a4d4 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,14 +25,12 @@ package org.hibernate.type.descriptor.sql; import java.sql.PreparedStatement; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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} @@ -40,7 +38,9 @@ import org.hibernate.type.descriptor.java.JavaTypeDescriptor; * @author Steve Ebersole */ public abstract class BasicBinder implements ValueBinder { - private static final Logger log = LoggerFactory.getLogger( BasicBinder.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicBinder.class.getPackage().getName()); private static final String BIND_MSG_TEMPLATE = "binding parameter [%d] as [%s] - %s"; private static final String NULL_BIND_MSG_TEMPLATE = "binding parameter [%d] as [%s] - "; @@ -66,26 +66,14 @@ public abstract class BasicBinder implements ValueBinder { */ public final void bind(PreparedStatement st, J value, int index, WrapperOptions options) throws SQLException { if ( value == null ) { - if ( log.isTraceEnabled() ) { - log.trace( - String.format( - NULL_BIND_MSG_TEMPLATE, - index, - JdbcTypeNameMapper.getTypeName( sqlDescriptor.getSqlType() ) - ) - ); - } + LOG.trace(String.format(NULL_BIND_MSG_TEMPLATE, index, JdbcTypeNameMapper.getTypeName(sqlDescriptor.getSqlType()))); st.setNull( index, sqlDescriptor.getSqlType() ); } else { - log.trace( - String.format( - BIND_MSG_TEMPLATE, - index, - JdbcTypeNameMapper.getTypeName( sqlDescriptor.getSqlType() ), - getJavaDescriptor().extractLoggableRepresentation( value ) - ) - ); + LOG.trace(String.format(BIND_MSG_TEMPLATE, + index, + JdbcTypeNameMapper.getTypeName(sqlDescriptor.getSqlType()), + getJavaDescriptor().extractLoggableRepresentation(value))); doBind( st, value, index, options ); } } @@ -101,4 +89,11 @@ 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 63dcee2347..f24fb0ef01 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,15 +23,16 @@ */ package org.hibernate.type.descriptor.sql; +import static org.jboss.logging.Logger.Level.TRACE; import java.sql.ResultSet; import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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} @@ -39,7 +40,9 @@ import org.hibernate.type.descriptor.java.JavaTypeDescriptor; * @author Steve Ebersole */ public abstract class BasicExtractor implements ValueExtractor { - private static final Logger log = LoggerFactory.getLogger( BasicExtractor.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + BasicExtractor.class.getPackage().getName()); private final JavaTypeDescriptor javaDescriptor; private final SqlTypeDescriptor sqlDescriptor; @@ -63,11 +66,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.trace( "found [null] as column [{}]", name ); + LOG.foundAsColumn( name ); return null; } else { - log.trace( "found [{}] as column [{}]", getJavaDescriptor().extractLoggableRepresentation( value ), name ); + LOG.foundAsColumn(getJavaDescriptor().extractLoggableRepresentation(value), name); return value; } } @@ -87,4 +90,20 @@ 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 16308632e2..165e5932eb 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/ConfigHelper.java @@ -31,11 +31,11 @@ import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.hibernate.HibernateException; 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. @@ -43,7 +43,9 @@ import org.hibernate.cfg.Environment; * @author Steve */ public final class ConfigHelper { - private static final Logger log = LoggerFactory.getLogger(ConfigHelper.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ConfigHelper.class.getPackage().getName()); /** Try to locate a local URL representing the incoming path. The first attempt * assumes that the incoming path is an actual URL string (file://, etc). If this @@ -62,9 +64,9 @@ public final class ConfigHelper { } } - /** - * Try to locate a local URL representing the incoming path. - * This method only attempts to locate this URL as a + /** + * Try to locate a local URL representing the incoming path. + * This method only attempts to locate this URL as a * java system resource. * * @param path The path representing the config location. @@ -106,8 +108,8 @@ public final class ConfigHelper { final URL url = ConfigHelper.locateConfig(path); if (url == null) { - String msg = "Unable to locate config file: " + path; - log.error( msg ); + String msg = LOG.unableToLocateConfigFile(path); + LOG.error(msg); throw new HibernateException(msg); } @@ -148,7 +150,7 @@ public final class ConfigHelper { throw new HibernateException("Unable to load properties from specified config file: " + path, e); } } - + private ConfigHelper() {} public static InputStream getResourceAsStream(String resource) { @@ -201,4 +203,13 @@ 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 a997eb6349..735b444c25 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/util/DTDEntityResolver.java @@ -24,11 +24,15 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +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; @@ -55,7 +59,8 @@ import org.xml.sax.InputSource; */ public class DTDEntityResolver implements EntityResolver, Serializable { - private static final Logger log = LoggerFactory.getLogger( DTDEntityResolver.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + DTDEntityResolver.class.getPackage().getName()); private static final String HIBERNATE_NAMESPACE = "http://www.hibernate.org/dtd/"; private static final String OLD_HIBERNATE_NAMESPACE = "http://hibernate.sourceforge.net/"; @@ -64,28 +69,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.debug( "trying to resolve system-id [" + systemId + "]" ); + LOG.tryingToResolveSystemId(systemId); if ( systemId.startsWith( HIBERNATE_NAMESPACE ) ) { - log.debug( "recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/" ); + LOG.recognizedHibernateNamespace(); source = resolveOnClassPath( publicId, systemId, HIBERNATE_NAMESPACE ); } else if ( systemId.startsWith( OLD_HIBERNATE_NAMESPACE ) ) { - log.warn( - "recognized obsolete hibernate namespace " + OLD_HIBERNATE_NAMESPACE + ". Use namespace " - + HIBERNATE_NAMESPACE + " instead. Refer to Hibernate 3.6 Migration Guide!" - ); - log.debug( "attempting to resolve on classpath under org/hibernate/" ); + LOG.recognizedObsoleteHibernateNamespace(OLD_HIBERNATE_NAMESPACE, HIBERNATE_NAMESPACE); + LOG.attemptingToResolveSystemId(); source = resolveOnClassPath( publicId, systemId, OLD_HIBERNATE_NAMESPACE ); } else if ( systemId.startsWith( USER_NAMESPACE ) ) { - log.debug( "recognized local namespace; attempting to resolve on classpath" ); + LOG.recognizedLocalNamespace(); String path = systemId.substring( USER_NAMESPACE.length() ); InputStream stream = resolveInLocalNamespace( path ); - if ( stream == null ) { - log.debug( "unable to locate [" + systemId + "] on classpath" ); - } + if (stream == null) LOG.unableToLocateSystemId(systemId); else { - log.debug( "located [" + systemId + "] in classpath" ); + LOG.systemIdLocated(systemId); source = new InputSource( stream ); source.setPublicId( publicId ); source.setSystemId( systemId ); @@ -100,13 +100,11 @@ public class DTDEntityResolver implements EntityResolver, Serializable { String path = "org/hibernate/" + systemId.substring( namespace.length() ); InputStream dtdStream = resolveInHibernateNamespace( path ); if ( dtdStream == null ) { - log.debug( "unable to locate [" + systemId + "] on classpath" ); - if ( systemId.substring( namespace.length() ).indexOf( "2.0" ) > -1 ) { - log.error( "Don't use old DTDs, read the Hibernate 3.x Migration Guide!" ); - } + LOG.unableToLocateSystemId(systemId); + if (systemId.substring(namespace.length()).indexOf("2.0") > -1) LOG.usingOldDtd(); } else { - log.debug( "located [" + systemId + "] in classpath" ); + LOG.systemIdLocated(systemId); source = new InputSource( dtdStream ); source.setPublicId( publicId ); source.setSystemId( systemId ); @@ -126,4 +124,44 @@ 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 ca30813741..f293640e7c 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java +++ b/hibernate-core/src/main/java/org/hibernate/util/JDBCExceptionReporter.java @@ -23,16 +23,22 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; public final class JDBCExceptionReporter { - public static final Logger log = LoggerFactory.getLogger(JDBCExceptionReporter.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + JDBCExceptionReporter.class.getPackage().getName()); public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception"; public static final String DEFAULT_WARNING_MSG = "SQL Warning"; @@ -64,14 +70,14 @@ public final class JDBCExceptionReporter { } catch ( SQLException sqle ) { //workaround for WebLogic - log.debug( "could not log warnings", sqle ); + LOG.debug(LOG.unableToLogWarnings(), sqle); } try { //Sybase fail if we don't do that, sigh... connection.clearWarnings(); } catch ( SQLException sqle ) { - log.debug( "could not clear warnings", sqle ); + LOG.debug(LOG.unableToClearWarnings(), sqle); } } @@ -90,14 +96,14 @@ public final class JDBCExceptionReporter { } catch ( SQLException sqle ) { //workaround for WebLogic - log.debug( "could not log warnings", sqle ); + LOG.debug(LOG.unableToLogWarnings(), sqle); } try { //Sybase fail if we don't do that, sigh... statement.clearWarnings(); } catch ( SQLException sqle ) { - log.debug( "could not clear warnings", sqle ); + LOG.debug(LOG.unableToClearWarnings(), sqle); } } @@ -187,17 +193,17 @@ public final class JDBCExceptionReporter { } public boolean doProcess() { - return log.isWarnEnabled(); + return LOG.isEnabled(WARN); } public void prepare(SQLWarning warning) { - log.debug( introMessage, warning ); + LOG.debug(introMessage, warning); } @Override protected void logWarning(String description, String message) { - log.warn( description ); - log.warn( message ); + LOG.warn(description); + LOG.warn(message); } } @@ -219,27 +225,38 @@ public final class JDBCExceptionReporter { } public static void logExceptions(SQLException ex, String message) { - if ( log.isErrorEnabled() ) { - if ( log.isDebugEnabled() ) { + if (LOG.isEnabled(ERROR)) { + if (LOG.isDebugEnabled()) { message = StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG; - log.debug( message, ex ); + LOG.debug(message, ex); } while (ex != null) { - StringBuffer buf = new StringBuffer(30) - .append( "SQL Error: " ) - .append( ex.getErrorCode() ) - .append( ", SQLState: " ) - .append( ex.getSQLState() ); - log.warn( buf.toString() ); - log.error( ex.getMessage() ); + LOG.sqlError(ex.getErrorCode(), ex.getSQLState()); + LOG.error(ex.getMessage()); ex = ex.getNextException(); } } } + + /** + * 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 8f8d44bfc2..dd4b925e4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/SerializationHelper.java @@ -24,21 +24,23 @@ */ 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; import java.io.InputStream; +import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; -import java.io.ObjectStreamClass; -import java.io.ObjectInputStream; - -import org.hibernate.type.SerializationException; import org.hibernate.Hibernate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 @@ -64,7 +66,8 @@ import org.slf4j.LoggerFactory; */ public final class SerializationHelper { - private static final Logger log = LoggerFactory.getLogger( SerializationHelper.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + SerializationHelper.class.getPackage().getName()); private SerializationHelper() { } @@ -88,7 +91,7 @@ public final class SerializationHelper { * @throws SerializationException (runtime) if the serialization fails */ public static Object clone(Serializable object) throws SerializationException { - log.trace( "Starting clone through serialization" ); + LOG.startingCloneThroughSerialization(); if ( object == null ) { return null; } @@ -119,13 +122,9 @@ public final class SerializationHelper { throw new IllegalArgumentException( "The OutputStream must not be null" ); } - if ( log.isTraceEnabled() ) { - if ( Hibernate.isInitialized( obj ) ) { - log.trace( "Starting serialization of object [" + obj + "]" ); - } - else { - log.trace( "Starting serialization of [uninitialized proxy]" ); - } + if (TMP_LOG.isTraceEnabled()) { + if (Hibernate.isInitialized(obj)) LOG.startingSerializationOfObject(obj); + else LOG.startingSerializationOfUninitializedProxy(); } ObjectOutputStream out = null; @@ -231,7 +230,7 @@ public final class SerializationHelper { throw new IllegalArgumentException( "The InputStream must not be null" ); } - log.trace( "Starting deserialization of object" ); + LOG.startingDeserializationOfObject(); try { CustomObjectInputStream in = new CustomObjectInputStream( @@ -334,15 +333,16 @@ public final class SerializationHelper { /** * {@inheritDoc} */ - protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { + @Override + protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { String className = v.getName(); - log.trace( "Attempting to locate class [" + className + "]" ); + LOG.attemptingToLocateClass(className); try { return Class.forName( className, false, loader1 ); } catch ( ClassNotFoundException e ) { - log.trace( "Unable to locate class using given classloader" ); + LOG.unableToLocateClass(); } if ( different( loader1, loader2 ) ) { @@ -350,7 +350,7 @@ public final class SerializationHelper { return Class.forName( className, false, loader2 ); } catch ( ClassNotFoundException e ) { - log.trace( "Unable to locate class using given classloader" ); + LOG.unableToLocateClass(); } } @@ -359,7 +359,7 @@ public final class SerializationHelper { return Class.forName( className, false, loader3 ); } catch ( ClassNotFoundException e ) { - log.trace( "Unable to locate class using given classloader" ); + LOG.unableToLocateClass(); } } @@ -369,12 +369,39 @@ public final class SerializationHelper { } private boolean different(ClassLoader one, ClassLoader other) { - if ( one == null ) { - return other != null; - } - else { - return !one.equals( other ); - } + if (one == null) return other != null; + 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 1c63a089db..fa43600911 100644 --- a/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/util/XMLHelper.java @@ -23,16 +23,19 @@ */ 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; import org.dom4j.io.DOMReader; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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.ErrorHandler; import org.xml.sax.SAXParseException; @@ -42,7 +45,9 @@ import org.xml.sax.SAXParseException; * Small helper class that lazy loads DOM and SAX reader and keep them for fast use afterwards. */ public final class XMLHelper { - private static final Logger log = LoggerFactory.getLogger(XMLHelper.class); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + XMLHelper.class.getPackage().getName()); public static final EntityResolver DEFAULT_DTD_RESOLVER = new DTDEntityResolver(); @@ -86,14 +91,14 @@ public final class XMLHelper { this.errors = errors; } public void error(SAXParseException error) { - log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); + LOG.parsingXmlError(file, error.getLineNumber(), error.getMessage()); errors.add(error); } public void fatalError(SAXParseException error) { error(error); } public void warning(SAXParseException warn) { - log.warn( "Warning parsing XML: " + file + '(' + warn.getLineNumber() + ") " + warn.getMessage() ); + LOG.parsingXmlWarning(file, warn.getLineNumber(), warn.getMessage()); } } @@ -116,4 +121,23 @@ 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 ea5d44f6bc..e95a6bb888 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,10 +23,12 @@ */ package org.hibernate.util.xml; +import static org.jboss.logging.Logger.Level.ERROR; import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.LogMessage; +import org.jboss.logging.Message; +import org.jboss.logging.MessageLogger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; @@ -37,7 +39,9 @@ import org.xml.sax.SAXParseException; * @author Steve Ebersole */ public class ErrorLogger implements ErrorHandler, Serializable { - private static final Logger log = LoggerFactory.getLogger( ErrorLogger.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + ErrorLogger.class.getPackage().getName()); private SAXParseException error; // capture the initial error @@ -54,10 +58,8 @@ public class ErrorLogger implements ErrorHandler, Serializable { * {@inheritDoc} */ public void error(SAXParseException error) { - log.error( "Error parsing XML (" + error.getLineNumber() + ") : " + error.getMessage() ); - if ( this.error == null ) { - this.error = error; - } + LOG.parsingXmlError(error.getLineNumber(), error.getMessage()); + if (this.error == null) this.error = error; } /** @@ -71,10 +73,27 @@ public class ErrorLogger implements ErrorHandler, Serializable { * {@inheritDoc} */ public void warning(SAXParseException warn) { - log.error( "Warning parsing XML (" + error.getLineNumber() + ") : " + error.getMessage() ); + LOG.parsingXmlError(error.getLineNumber(), error.getMessage()); } 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 5bcd7cac2b..cb8efd9492 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,25 +23,28 @@ */ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +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.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import org.hibernate.InvalidMappingException; - /** * Handles reading mapping documents, both {@code hbm} and {@code orm} varieties. * * @author Steve Ebersole */ public class MappingReader { - private static final Logger log = LoggerFactory.getLogger( MappingReader.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, + MappingReader.class.getPackage().getName()); public static final String ASSUMED_ORM_XSD_VERSION = "2.0"; public static final MappingReader INSTANCE = new MappingReader(); @@ -79,7 +82,7 @@ public class MappingReader { return new XmlDocumentImpl( document, origin.getType(), origin.getName() ); } catch ( Exception orm2Problem ) { - log.debug( "Problem parsing XML using orm 2 xsd : {}", orm2Problem.getMessage() ); + LOG.problemParsingXmlUsingOrm2Xsd(orm2Problem.getMessage()); failure = orm2Problem; errorHandler.reset(); @@ -94,7 +97,7 @@ public class MappingReader { return new XmlDocumentImpl( document, origin.getType(), origin.getName() ); } catch ( Exception orm1Problem ) { - log.debug( "Problem parsing XML using orm 1 xsd : {}", orm1Problem.getMessage() ); + LOG.problemParsingXmlUsingOrm1Xsd(orm1Problem.getMessage()); } } } @@ -254,4 +257,19 @@ 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/test/annotations/backquotes/BackquoteTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java index fbb81ff83a..f2b9253bc3 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 @@ -3,34 +3,29 @@ package org.hibernate.test.annotations.backquotes; import java.io.PrintWriter; import java.io.StringWriter; - import junit.framework.TestCase; - import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.test.common.ServiceRegistryHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Testcase for ANN-718 - @JoinTable / @JoinColumn fail when using backquotes in PK field name. - * + * * @author Hardy Ferentschik * */ public class BackquoteTest extends TestCase { - - private Logger log = LoggerFactory.getLogger(BackquoteTest.class); 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(); } @@ -46,16 +41,16 @@ public class BackquoteTest extends TestCase { catch( Exception e ) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } - - /** + + /** * HHH-4647 : Problems with @JoinColumn referencedColumnName and quoted column and table names - * - * An invalid referencedColumnName to an entity having a quoted table name results in an - * infinite loop in o.h.c.Configuration$MappingsImpl#getPhysicalColumnName(). + * + * An invalid referencedColumnName to an entity having a quoted table name results in an + * infinite loop in o.h.c.Configuration$MappingsImpl#getPhysicalColumnName(). * The same issue exists with getLogicalColumnName() */ public void testInvalidReferenceToQuotedTableName() { @@ -67,15 +62,14 @@ public class BackquoteTest extends TestCase { fail("expected MappingException to be thrown"); } //we WANT MappingException to be thrown - catch( MappingException e ) { - assertTrue("MappingException was thrown", true); + catch( MappingException e ) { + assertTrue("MappingException was thrown", true); } catch(Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } - } 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 9872013b99..29ee0626e8 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 @@ -26,11 +26,8 @@ package org.hibernate.test.annotations.fetchprofile; import java.io.InputStream; - import junit.framework.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import org.hibernate.Logger; import org.hibernate.MappingException; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; @@ -44,7 +41,7 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public class FetchProfileTest extends TestCase { - private Logger log = LoggerFactory.getLogger( FetchProfileTest.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); private ServiceRegistryHolder serviceRegistryHolder; @@ -89,7 +86,7 @@ public class FetchProfileTest extends TestCase { fail(); } catch ( MappingException e ) { - log.trace( "success" ); + LOG.trace("success"); } } @@ -104,7 +101,7 @@ public class FetchProfileTest extends TestCase { fail(); } catch ( MappingException e ) { - log.trace( "success" ); + LOG.trace("success"); } } @@ -119,7 +116,7 @@ public class FetchProfileTest extends TestCase { fail(); } catch ( MappingException e ) { - log.trace( "success" ); + LOG.trace("success"); } } @@ -151,7 +148,7 @@ public class FetchProfileTest extends TestCase { fail(); } catch ( MappingException e ) { - log.trace( "success" ); + LOG.trace("success"); } } 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 91165f18b7..6e2c930bcb 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 @@ -3,34 +3,31 @@ package org.hibernate.test.annotations.fkcircularity; import java.io.PrintWriter; import java.io.StringWriter; - import junit.framework.TestCase; - import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.test.common.ServiceRegistryHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Test case for ANN-722 and ANN-730. - * + * * @author Hardy Ferentschik */ public class FkCircularityTest extends TestCase { - private Logger log = LoggerFactory.getLogger(FkCircularityTest.class); + 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(); } @@ -47,13 +44,13 @@ public class FkCircularityTest extends TestCase { String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { - log.debug(s); + LOG.debug(s); } - log.debug("success"); + LOG.debug("success"); } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } @@ -69,13 +66,13 @@ public class FkCircularityTest extends TestCase { String[] schema = config .generateSchemaCreationScript(new HSQLDialect()); for (String s : schema) { - log.debug(s); + LOG.debug(s); } - log.debug("success"); + LOG.debug("success"); } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } 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 59c5de3bd3..eca5a2b91c 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 @@ -6,20 +6,16 @@ import org.hibernate.Transaction; import org.hibernate.test.annotations.TestCase; import org.hibernate.test.annotations.id.entities.Planet; import org.hibernate.test.annotations.id.entities.PlanetCheatSheet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Tests for enum type as id. - * + * * @author Hardy Ferentschik * @see ANN-744 */ @SuppressWarnings("unchecked") public class EnumIdTest extends TestCase { - private Logger log = LoggerFactory.getLogger(EnumIdTest.class); - public EnumIdTest(String x) { super(x); } @@ -40,11 +36,11 @@ public class EnumIdTest extends TestCase { tx = s.beginTransaction(); PlanetCheatSheet mercuryFromDb = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, mercury.getPlanet()); assertNotNull(mercuryFromDb); - log.debug(mercuryFromDb.toString()); + LOG.debug(mercuryFromDb.toString()); s.delete(mercuryFromDb); tx.commit(); s.close(); - + s = openSession(); tx = s.beginTransaction(); mercury = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, Planet.MERCURY); @@ -56,7 +52,8 @@ public class EnumIdTest extends TestCase { /** * @see org.hibernate.test.annotations.TestCase#getAnnotatedClasses() */ - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] { PlanetCheatSheet.class }; } } 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 ef34357258..881ca0be39 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 @@ -3,32 +3,27 @@ package org.hibernate.test.annotations.id; import java.io.PrintWriter; import java.io.StringWriter; - import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.test.annotations.TestCase; import org.hibernate.test.annotations.id.entities.Bunny; import org.hibernate.test.annotations.id.entities.PointyTooth; import org.hibernate.test.annotations.id.entities.TwinkleToes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Tests for JIRA issue ANN-748. - * + * * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class JoinColumnOverrideTest extends TestCase { - private Logger log = LoggerFactory.getLogger(JoinColumnOverrideTest.class); - public JoinColumnOverrideTest(String x) { super(x); } public void testBlownPrecision() throws Exception { - + try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Bunny.class); @@ -38,27 +33,28 @@ public class JoinColumnOverrideTest extends TestCase { String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { - log.debug(s); + LOG.debug(s); } String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " + "bunny_id numeric(128,0) null, primary key (id))"; assertEquals("Wrong SQL", expectedSqlPointyTooth, schema[1]); - + String expectedSqlTwinkleToes = "create table TwinkleToes (id numeric(128,0) not null, " + "bunny_id numeric(128,0) null, primary key (id))"; assertEquals("Wrong SQL", expectedSqlTwinkleToes, schema[2]); } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); - } + } } /** * @see org.hibernate.test.annotations.TestCase#getAnnotatedClasses() */ - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] {}; } } 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 1e7a470750..3926cb3dda 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 @@ -6,20 +6,16 @@ import org.hibernate.Transaction; import org.hibernate.test.annotations.TestCase; import org.hibernate.test.annotations.id.sequences.entities.Planet; import org.hibernate.test.annotations.id.sequences.entities.PlanetCheatSheet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Tests for enum type as id. - * + * * @author Hardy Ferentschik * @see ANN-744 */ @SuppressWarnings("unchecked") public class EnumIdTest extends TestCase { - private Logger log = LoggerFactory.getLogger(EnumIdTest.class); - public EnumIdTest(String x) { super(x); } @@ -40,11 +36,11 @@ public class EnumIdTest extends TestCase { tx = s.beginTransaction(); PlanetCheatSheet mercuryFromDb = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, mercury.getPlanet()); assertNotNull(mercuryFromDb); - log.debug(mercuryFromDb.toString()); + LOG.debug(mercuryFromDb.toString()); s.delete(mercuryFromDb); tx.commit(); s.close(); - + s = openSession(); tx = s.beginTransaction(); mercury = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, Planet.MERCURY); @@ -56,7 +52,8 @@ public class EnumIdTest extends TestCase { /** * @see org.hibernate.test.annotations.TestCase#getAnnotatedClasses() */ - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] { PlanetCheatSheet.class }; } } 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 772107f8a2..a0cc86e836 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 @@ -3,32 +3,27 @@ package org.hibernate.test.annotations.id.sequences; import java.io.PrintWriter; import java.io.StringWriter; - import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.test.annotations.TestCase; import org.hibernate.test.annotations.id.sequences.entities.Bunny; import org.hibernate.test.annotations.id.sequences.entities.PointyTooth; import org.hibernate.test.annotations.id.sequences.entities.TwinkleToes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Tests for JIRA issue ANN-748. - * + * * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class JoinColumnOverrideTest extends TestCase { - private Logger log = LoggerFactory.getLogger(JoinColumnOverrideTest.class); - public JoinColumnOverrideTest(String x) { super(x); } public void testBlownPrecision() throws Exception { - + try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Bunny.class); @@ -38,27 +33,28 @@ public class JoinColumnOverrideTest extends TestCase { String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { - log.debug(s); + LOG.debug(s); } String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " + "bunny_id numeric(128,0) null, primary key (id))"; assertEquals("Wrong SQL", expectedSqlPointyTooth, schema[1]); - + String expectedSqlTwinkleToes = "create table TwinkleToes (id numeric(128,0) not null, " + "bunny_id numeric(128,0) null, primary key (id))"; assertEquals("Wrong SQL", expectedSqlTwinkleToes, schema[2]); } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); - } + } } /** * @see org.hibernate.test.annotations.TestCase#getAnnotatedClasses() */ - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] {}; } } 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 5f0d6a5f16..559bb6fba0 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 @@ -3,7 +3,6 @@ package org.hibernate.test.annotations.immutable; import java.util.ArrayList; import java.util.List; - import org.hibernate.AnnotationException; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -11,19 +10,14 @@ import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.test.annotations.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Tests for Immutable annotation. - * + * * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class ImmutableTest extends TestCase { - private Logger log = LoggerFactory.getLogger(ImmutableTest.class); - public ImmutableTest(String x) { super(x); } @@ -47,7 +41,7 @@ public class ImmutableTest extends TestCase { s.save(germany); tx.commit(); s.close(); - + // retrieving the country again - it should be unmodified s = openSession(); tx = s.beginTransaction(); @@ -56,14 +50,14 @@ public class ImmutableTest extends TestCase { assertEquals("Name should not have changed", "Germany", germany.getName()); tx.commit(); s.close(); - + // // try deletion // s = openSession(); // tx = s.beginTransaction(); // s.delete(germany); // tx.commit(); // s.close(); -// +// // s = openSession(); // tx = s.beginTransaction(); // germany = (Country) s.get(Country.class, country.getId()); @@ -71,7 +65,7 @@ public class ImmutableTest extends TestCase { // assertEquals("Name should not have changed", "Germany", germany.getName()); // s.close(); } - + public void testImmutableCollection() { Country country = new Country(); country.setName("Germany"); @@ -86,19 +80,19 @@ public class ImmutableTest extends TestCase { states.add(hessen); states.add(sachsen); country.setStates(states); - + Session s = openSession(); Transaction tx = s.beginTransaction(); s.persist(country); tx.commit(); s.close(); - + s = openSession(); tx = s.beginTransaction(); Country germany = (Country) s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Wrong number of states", 3, germany.getStates().size()); - + // try adding a state State foobar = new State(); foobar.setName("foobar"); @@ -109,16 +103,16 @@ public class ImmutableTest extends TestCase { fail(); } catch (HibernateException e) { assertTrue(e.getMessage().contains("changed an immutable collection instance")); - log.debug("success"); + LOG.debug("success"); } s.close(); - + s = openSession(); tx = s.beginTransaction(); germany = (Country) s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Wrong number of states", 3, germany.getStates().size()); - + // try deleting a state germany.getStates().remove(0); try { @@ -126,10 +120,10 @@ public class ImmutableTest extends TestCase { fail(); } catch (HibernateException e) { assertTrue(e.getMessage().contains("changed an immutable collection instance")); - log.debug("success"); - } - s.close(); - + LOG.debug("success"); + } + s.close(); + s = openSession(); tx = s.beginTransaction(); germany = (Country) s.get(Country.class, country.getId()); @@ -138,7 +132,7 @@ public class ImmutableTest extends TestCase { tx.commit(); s.close(); } - + public void testMiscplacedImmutableAnnotation() { try { AnnotationConfiguration config = new AnnotationConfiguration(); @@ -146,14 +140,15 @@ public class ImmutableTest extends TestCase { config.buildSessionFactory( getServiceRegistry() ); fail(); } catch (AnnotationException ae) { - log.debug("succes"); + LOG.debug("succes"); } } - + /** * @see org.hibernate.test.annotations.TestCase#getAnnotatedClasses() */ - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] { Country.class, State.class}; } } 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 29c423dfeb..c3d06684b8 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 @@ -4,9 +4,7 @@ package org.hibernate.test.annotations.namingstrategy; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; - import junit.framework.TestCase; - import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.EJB3NamingStrategy; import org.hibernate.cfg.Environment; @@ -14,25 +12,24 @@ import org.hibernate.cfg.Mappings; import org.hibernate.mapping.Table; import org.hibernate.test.common.ServiceRegistryHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Test harness for ANN-716. - * + * * @author Hardy Ferentschik */ public class NamingStrategyTest extends TestCase { - - private Logger log = LoggerFactory.getLogger(NamingStrategyTest.class); + + 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(); } @@ -49,7 +46,7 @@ public class NamingStrategyTest extends TestCase { catch( Exception e ) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } @@ -66,7 +63,7 @@ public class NamingStrategyTest extends TestCase { for ( Iterator iter = mappings.iterateTables(); iter.hasNext(); ) { Table table = (Table) iter.next(); - log.info("testWithEJB3NamingStrategy table = " + table.getName()); + LOG.info("testWithEJB3NamingStrategy table = " + table.getName()); if ( table.getName().equalsIgnoreCase("A_ADDRESS")) { foundIt = true; } @@ -78,7 +75,7 @@ public class NamingStrategyTest extends TestCase { catch( Exception e ) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } } @@ -93,8 +90,8 @@ public class NamingStrategyTest extends TestCase { catch( Exception e ) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - log.debug(writer.toString()); + LOG.debug(writer.toString()); fail(e.getMessage()); } - } + } } 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 2551f84840..624d0d05b5 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 @@ -2,10 +2,6 @@ package org.hibernate.test.annotations.naturalid; import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; @@ -24,10 +20,8 @@ import org.hibernate.test.annotations.TestCase; @SuppressWarnings("unchecked") public class NaturalIdOnSingleManyToOneTest extends TestCase { - private Logger log = LoggerFactory.getLogger( NaturalIdOnManyToOne.class ); - public void testMappingProperties() { - log.warn( "Commented out test" ); + LOG.warn("Commented out test"); ClassMetadata metaData = getSessions().getClassMetadata( NaturalIdOnManyToOne.class @@ -103,14 +97,16 @@ public class NaturalIdOnSingleManyToOneTest extends TestCase { s.close(); } - protected Class[] getAnnotatedClasses() { + @Override + protected Class[] getAnnotatedClasses() { return new Class[] { Citizen.class, State.class, NaturalIdOnManyToOne.class }; } - protected void configure(Configuration cfg) { + @Override + protected void configure(Configuration cfg) { cfg.setProperty( "hibernate.cache.use_query_cache", "true" ); } } 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 692534beed..40562772ff 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 @@ -2,24 +2,20 @@ package org.hibernate.test.annotations.onetoone.primarykey; import junit.framework.TestCase; - import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.test.common.ServiceRegistryHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Test harness for ANN-742. - * + * * @author Hardy Ferentschik - * + * */ public class NullablePrimaryKeyTest extends TestCase { - private Logger log = LoggerFactory.getLogger(NullablePrimaryKeyTest.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); public void testGeneratedSql() { @@ -33,7 +29,7 @@ public class NullablePrimaryKeyTest extends TestCase { String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { - log.debug(s); + LOG.debug(s); } String expectedMappingTableSql = "create table personAddress (address_id numeric(19,0) null, " + "person_id numeric(19,0) not null, primary key (person_id))"; 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 cf83f07447..1e0d3018ae 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,27 +1,26 @@ //$Id$ package org.hibernate.test.annotations.reflection; -import javax.persistence.PrePersist; import javax.persistence.PostPersist; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import javax.persistence.PrePersist; +import org.hibernate.Logger; /** * @author Emmanuel Bernard */ public class LogListener { - private final Logger log = LoggerFactory.getLogger( LogListener.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); @PrePersist @PostPersist public void log(Object entity) { - log.debug( "Logging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() ); + LOG.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } public void noLog(Object entity) { - log.debug( "NoLogging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() ); + LOG.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } } 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 0190bb0e02..3cbc660a5a 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,27 +1,25 @@ //$Id$ package org.hibernate.test.annotations.reflection; -import javax.persistence.PrePersist; import javax.persistence.PostPersist; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import javax.persistence.PrePersist; +import org.hibernate.Logger; /** * @author Emmanuel Bernard */ public class OtherLogListener { - private final Logger log = LoggerFactory.getLogger( OtherLogListener.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); @PrePersist @PostPersist public void log(Object entity) { - log.debug( "Logging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() ); + LOG.debug("Logging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } public void noLog(Object entity) { - log.debug( "NoLogging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() ); + LOG.debug("NoLogging entity " + entity.getClass().getName() + " with hashCode: " + entity.hashCode()); } } 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 f29749d93b..e5b28e094a 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 @@ -32,12 +32,9 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; - import junit.framework.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.LockMode; +import org.hibernate.Logger; import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Transaction; @@ -51,13 +48,13 @@ import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.TimesTenDialect; import org.hibernate.dialect.function.SQLFunction; -import org.hibernate.testing.junit.functional.DatabaseSpecificFunctionalTestCase; -import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.test.legacy.Blobber; import org.hibernate.test.legacy.Broken; import org.hibernate.test.legacy.Fixed; import org.hibernate.test.legacy.Simple; import org.hibernate.test.legacy.Single; +import org.hibernate.testing.junit.functional.DatabaseSpecificFunctionalTestCase; +import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; /** * Tests for function support on CacheSQL... @@ -66,7 +63,7 @@ import org.hibernate.test.legacy.Single; */ public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger(SQLFunctionsInterSystemsTest.class); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); public SQLFunctionsInterSystemsTest(String name) { super(name); @@ -540,7 +537,7 @@ public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTest s.flush(); s.refresh(b); //b.getBlob().setBytes( 2, "abc".getBytes() ); - log.debug("levinson: just bfore b.getClob()"); + LOG.debug("levinson: just bfore b.getClob()"); b.getClob().getSubString(2, 3); //b.getClob().setString(2, "abc"); s.flush(); @@ -611,11 +608,11 @@ public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTest public void testSqlFunctionAsAlias() throws Exception { String functionName = locateAppropriateDialectFunctionNameForAliasTest(); if (functionName == null) { - log.info("Dialect does not list any no-arg functions"); + LOG.info("Dialect does not list any no-arg functions"); return; } - log.info("Using function named [" + functionName + "] for 'function as alias' test"); + LOG.info("Using function named [" + functionName + "] for 'function as alias' test"); String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10"; Session s = openSession(); 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 88ff4efa38..bd47ca90bd 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 @@ -8,9 +8,7 @@ import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; - import junit.framework.Test; - import org.hibernate.Criteria; import org.hibernate.EntityMode; import org.hibernate.FetchMode; @@ -27,12 +25,10 @@ import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Subqueries; import org.hibernate.engine.SessionImplementor; import org.hibernate.impl.SessionFactoryImpl; +import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.transform.DistinctRootEntityResultTransformer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Implementation of DynamicFilterTest. @@ -42,8 +38,6 @@ import org.slf4j.LoggerFactory; @SuppressWarnings({ "WhileLoopReplaceableByForEach", "unchecked" }) public class DynamicFilterTest extends FunctionalTestCase { - private Logger log = LoggerFactory.getLogger( DynamicFilterTest.class ); - public DynamicFilterTest(String testName) { super( testName ); } @@ -60,7 +54,8 @@ public class DynamicFilterTest extends FunctionalTestCase { }; } - public void configure(Configuration cfg) { + @Override + public void configure(Configuration cfg) { cfg.setProperty( Environment.MAX_FETCH_DEPTH, "1" ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); @@ -168,7 +163,7 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HQL test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting HQL filter tests" ); + LOG.info("Starting HQL filter tests"); TestData testData = new TestData(); testData.prepare(); @@ -178,31 +173,31 @@ public class DynamicFilterTest extends FunctionalTestCase { session.enableFilter( "effectiveDate" ) .setParameter( "asOfDate", testData.lastMonth.getTime() ); - log.info( "HQL against Salesperson..." ); + LOG.info("HQL against Salesperson..."); List results = session.createQuery( "select s from Salesperson as s left join fetch s.orders" ).list(); assertTrue( "Incorrect filtered HQL result count [" + results.size() + "]", results.size() == 1 ); Salesperson result = ( Salesperson ) results.get( 0 ); assertTrue( "Incorrect collectionfilter count", result.getOrders().size() == 1 ); - log.info( "HQL against Product..." ); + LOG.info("HQL against Product..."); results = session.createQuery( "from Product as p where p.stockNumber = ?" ).setInteger( 0, 124 ).list(); assertTrue( results.size() == 1 ); session.close(); testData.release(); } - + public void testFiltersWithCustomerReadAndWrite() { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Custom SQL read/write with filter //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting HQL filter with custom SQL get/set tests" ); + LOG.info("Starting HQL filter with custom SQL get/set tests"); TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.enableFilter( "heavyProducts" ).setParameter("weightKilograms", 4d); - log.info( "HQL against Product..." ); + LOG.info("HQL against Product..."); List results = session.createQuery( "from Product").list(); assertEquals( 1, results.size() ); @@ -214,7 +209,7 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Criteria-query test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting Criteria-query filter tests" ); + LOG.info("Starting Criteria-query filter tests"); TestData testData = new TestData(); testData.prepare(); @@ -227,14 +222,14 @@ public class DynamicFilterTest extends FunctionalTestCase { session.enableFilter( "effectiveDate" ) .setParameter( "asOfDate", testData.lastMonth.getTime() ); - log.info( "Criteria query against Salesperson..." ); + LOG.info("Criteria query against Salesperson..."); List salespersons = session.createCriteria( Salesperson.class ) .setFetchMode( "orders", FetchMode.JOIN ) .list(); assertEquals( "Incorrect salesperson count", 1, salespersons.size() ); assertEquals( "Incorrect order count", 1, ( ( Salesperson ) salespersons.get( 0 ) ).getOrders().size() ); - log.info( "Criteria query against Product..." ); + LOG.info("Criteria query against Product..."); List products = session.createCriteria( Product.class ) .add( Restrictions.eq( "stockNumber", 124 ) ) .list(); @@ -272,14 +267,14 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Criteria-subquery test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info("Starting Criteria-subquery filter tests"); + LOG.info("Starting Criteria-subquery filter tests"); TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.enableFilter("region").setParameter("region", "APAC"); - log.info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); + LOG.info("Criteria query against Department with a subquery on Salesperson in the APAC reqion..."); DetachedCriteria salespersonSubquery = DetachedCriteria.forClass(Salesperson.class) .add(Restrictions.eq("name", "steve")) .setProjection(Property.forName("department")); @@ -289,14 +284,14 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect department count", 1, departments.size()); - log.info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); + LOG.info("Criteria query against Department with a subquery on Salesperson in the FooBar reqion..."); session.enableFilter("region").setParameter("region", "Foobar"); departments = departmentsQuery.list(); assertEquals("Incorrect department count", 0, departments.size()); - log.info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); + LOG.info("Criteria query against Order with a subquery for line items with a subquery on product and sold by a given sales person..."); session.enableFilter("region").setParameter("region", "APAC"); DetachedCriteria lineItemSubquery = DetachedCriteria.forClass(LineItem.class) @@ -312,7 +307,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 1, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.lastMonth.getTime()); @@ -334,7 +329,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 1, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.fourMonthsAgo.getTime()); @@ -353,27 +348,27 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HQL subquery with filters test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info("Starting HQL subquery with filters tests"); + LOG.info("Starting HQL subquery with filters tests"); TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.enableFilter("region").setParameter("region", "APAC"); - log.info("query against Department with a subquery on Salesperson in the APAC reqion..."); + LOG.info("query against Department with a subquery on Salesperson in the APAC reqion..."); List departments = session.createQuery("select d from Department as d where d.id in (select s.department from Salesperson s where s.name = ?)").setString(0, "steve").list(); assertEquals("Incorrect department count", 1, departments.size()); - log.info("query against Department with a subquery on Salesperson in the FooBar reqion..."); + LOG.info("query against Department with a subquery on Salesperson in the FooBar reqion..."); session.enableFilter("region").setParameter("region", "Foobar"); departments = session.createQuery("select d from Department as d where d.id in (select s.department from Salesperson s where s.name = ?)").setString(0, "steve").list(); assertEquals("Incorrect department count", 0, departments.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region for a given buyer"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region for a given buyer"); session.enableFilter("region").setParameter("region", "APAC"); List orders = session.createQuery("select o from Order as o where exists (select li.id from LineItem li, Product as p where p.id = li.product and li.quantity >= ? and p.name = ?) and o.buyer = ?") @@ -381,7 +376,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 1, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.lastMonth.getTime()); @@ -392,7 +387,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 1, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of 4 months ago"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.fourMonthsAgo.getTime()); @@ -402,7 +397,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 0, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month with named types"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month with named types"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.lastMonth.getTime()); @@ -412,7 +407,7 @@ public class DynamicFilterTest extends FunctionalTestCase { assertEquals("Incorrect orders count", 1, orders.size()); - log.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month with mixed types"); + LOG.info("query against Order with a subquery for line items with a subquery line items where the product name is Acme Hair Gel and the quantity is greater than 1 in a given region and the product is effective as of last month with mixed types"); session.enableFilter("region").setParameter("region", "APAC"); session.enableFilter("effectiveDate").setParameter("asOfDate", testData.lastMonth.getTime()); @@ -547,14 +542,14 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Get() test //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting get() filter tests (eager assoc. fetching)." ); + LOG.info("Starting get() filter tests (eager assoc. fetching)."); TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.enableFilter( "region" ).setParameter( "region", "APAC" ); - log.info( "Performing get()..." ); + LOG.info("Performing get()..."); Salesperson salesperson = ( Salesperson ) session.get( Salesperson.class, testData.steveId ); assertNotNull( salesperson ); assertEquals( "Incorrect order count", 1, salesperson.getOrders().size() ); @@ -567,7 +562,7 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting one-to-many collection loader filter tests." ); + LOG.info("Starting one-to-many collection loader filter tests."); TestData testData = new TestData(); testData.prepare(); @@ -575,7 +570,7 @@ public class DynamicFilterTest extends FunctionalTestCase { session.enableFilter( "seniorSalespersons" ) .setParameter( "asOfDate", testData.lastMonth.getTime() ); - log.info( "Performing load of Department..." ); + LOG.info("Performing load of Department..."); Department department = ( Department ) session.load( Department.class, testData.deptId ); Set salespersons = department.getSalespersons(); assertEquals( "Incorrect salesperson count", 1, salespersons.size() ); @@ -588,7 +583,7 @@ public class DynamicFilterTest extends FunctionalTestCase { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // one-to-many loading tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - log.info( "Starting one-to-many collection loader filter tests." ); + LOG.info("Starting one-to-many collection loader filter tests."); TestData testData = new TestData(); testData.prepare(); @@ -596,7 +591,7 @@ public class DynamicFilterTest extends FunctionalTestCase { session.enableFilter( "regionlist" ) .setParameterList( "regions", new String[]{"LA", "APAC"} ); - log.debug( "Performing query of Salespersons" ); + LOG.debug("Performing query of Salespersons"); List salespersons = session.createQuery( "from Salesperson" ).list(); assertEquals( "Incorrect salesperson count", 1, salespersons.size() ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java index 38ec1b5eb1..9c2e244d6a 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java @@ -27,44 +27,15 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import junit.framework.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.Hibernate; -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.QueryException; -import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.Transaction; -import org.hibernate.TypeMismatchException; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.IngresDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.Sybase11Dialect; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.dialect.SybaseAnywhereDialect; -import org.hibernate.dialect.SybaseDialect; import org.hibernate.hql.ast.ASTQueryTranslatorFactory; -import org.hibernate.hql.ast.QuerySyntaxException; -import org.hibernate.persister.entity.DiscriminatorType; -import org.hibernate.stat.QueryStatistics; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.hibernate.transform.DistinctRootEntityResultTransformer; -import org.hibernate.transform.Transformers; -import org.hibernate.type.ComponentType; -import org.hibernate.type.ManyToOneType; -import org.hibernate.type.Type; -import org.hibernate.util.StringHelper; /** * Tests AST parser processing of ORDER BY clauses. @@ -73,8 +44,6 @@ import org.hibernate.util.StringHelper; */ public class ASTParserLoadingOrderByTest extends FunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger( ASTParserLoadingOrderByTest.class ); - StateProvince stateProvince; private Zoo zoo1; private Zoo zoo2; @@ -97,7 +66,8 @@ public class ASTParserLoadingOrderByTest extends FunctionalTestCase { }; } - public void configure(Configuration cfg) { + @Override + public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( Environment.USE_QUERY_CACHE, "false" ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); @@ -108,7 +78,8 @@ public class ASTParserLoadingOrderByTest extends FunctionalTestCase { return new FunctionalTestClassTestSuite( ASTParserLoadingOrderByTest.class ); } - protected void prepareTest() { + @Override + protected void prepareTest() { cleanupData(); } 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 a9fae2c83f..1e1e1cd276 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 @@ -12,9 +12,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; - import junit.framework.Test; - import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Query; @@ -37,8 +35,6 @@ import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseAnywhereDialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.hql.ast.ASTQueryTranslatorFactory; -import org.hibernate.testing.junit.functional.FunctionalTestCase; -import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.persister.entity.DiscriminatorType; import org.hibernate.stat.QueryStatistics; import org.hibernate.test.any.IntegerPropertyValue; @@ -47,17 +43,17 @@ import org.hibernate.test.any.PropertyValue; import org.hibernate.test.any.StringPropertyValue; import org.hibernate.test.cid.Customer; import org.hibernate.test.cid.LineItem; +import org.hibernate.test.cid.LineItem.Id; import org.hibernate.test.cid.Order; import org.hibernate.test.cid.Product; -import org.hibernate.test.cid.LineItem.Id; +import org.hibernate.testing.junit.functional.FunctionalTestCase; +import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; import org.hibernate.transform.DistinctRootEntityResultTransformer; import org.hibernate.transform.Transformers; import org.hibernate.type.ComponentType; import org.hibernate.type.ManyToOneType; import org.hibernate.type.Type; import org.hibernate.util.StringHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Tests the integration of the new AST parser into the loading of query results using @@ -71,8 +67,6 @@ import org.slf4j.LoggerFactory; */ public class ASTParserLoadingTest extends FunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger( ASTParserLoadingTest.class ); - private List createdAnimalIds = new ArrayList(); public ASTParserLoadingTest(String name) { @@ -99,7 +93,8 @@ public class ASTParserLoadingTest extends FunctionalTestCase { }; } - public void configure(Configuration cfg) { + @Override + public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); @@ -338,7 +333,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { fail( "illegal collection dereference semantic did not cause failure" ); } catch( QueryException qe ) { - log.trace( "expected failure...", qe ); + LOG.trace("expected failure...", qe); } try { @@ -346,7 +341,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { fail( "illegal collection dereference semantic did not cause failure" ); } catch( QueryException qe ) { - log.trace( "expected failure...", qe ); + LOG.trace("expected failure...", qe); } try { @@ -354,7 +349,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { fail( "illegal collection dereference semantic did not cause failure" ); } catch( QueryException qe ) { - log.trace( "expected failure...", qe ); + LOG.trace("expected failure...", qe); } try { @@ -362,7 +357,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { fail( "illegal collection dereference semantic did not cause failure" ); } catch( QueryException qe ) { - log.trace( "expected failure...", qe ); + LOG.trace("expected failure...", qe); } s.getTransaction().commit(); @@ -393,21 +388,21 @@ public class ASTParserLoadingTest extends FunctionalTestCase { // HSQLDB and DB2 don't like the abs(? - ?) syntax. bit work if at least one parameter is typed... s.createQuery( "from Animal where abs(cast(:x as long) - :y) < 2.0" ).setLong( "x", 1 ).setLong( "y", 1 ).list(); s.createQuery( "from Animal where abs(:x - cast(:y as long)) < 2.0" ).setLong( "x", 1 ).setLong( "y", 1 ).list(); - s.createQuery( "from Animal where abs(cast(:x as long) - cast(:y as long)) < 2.0" ).setLong( "x", 1 ).setLong( "y", 1 ).list(); - } + s.createQuery( "from Animal where abs(cast(:x as long) - cast(:y as long)) < 2.0" ).setLong( "x", 1 ).setLong( "y", 1 ).list(); + } else { s.createQuery( "from Animal where abs(:x - :y) < 2.0" ).setLong( "x", 1 ).setLong( "y", 1 ).list(); } if ( getDialect() instanceof DB2Dialect ) { - s.createQuery( "from Animal where lower(upper(cast(:foo as string))) like 'f%'" ).setString( "foo", "foo" ).list(); + s.createQuery( "from Animal where lower(upper(cast(:foo as string))) like 'f%'" ).setString( "foo", "foo" ).list(); } else { s.createQuery( "from Animal where lower(upper(:foo)) like 'f%'" ).setString( "foo", "foo" ).list(); } s.createQuery( "from Animal a where abs(abs(a.bodyWeight - 1.0 + :param) * abs(length('ffobar')-3)) = 3.0" ).setLong( "param", 1 ).list(); if ( getDialect() instanceof DB2Dialect ) { - s.createQuery( "from Animal where lower(upper('foo') || upper(cast(:bar as string))) like 'f%'" ).setString( "bar", "xyz" ).list(); + s.createQuery( "from Animal where lower(upper('foo') || upper(cast(:bar as string))) like 'f%'" ).setString( "bar", "xyz" ).list(); } else { s.createQuery( "from Animal where lower(upper('foo') || upper(:bar)) like 'f%'" ).setString( "bar", "xyz" ).list(); @@ -500,7 +495,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { product.setPrice( new BigDecimal( 123 ) ); product.setProductId( "4321" ); s.save( product ); - + Customer customer = new Customer(); customer.setCustomerId( "123456789" ); @@ -531,7 +526,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { assertEquals( 2, query.list().size() ); s.getTransaction().rollback(); s.close(); - + } private void checkCounts(String hql, int expected, String testCondition) { Session s = openSession(); @@ -1275,7 +1270,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { t.commit(); s.close(); } - + public void testOrderedWithCustomColumnReadAndWrite() { Session s = openSession(); Transaction t = s.beginTransaction(); @@ -1292,20 +1287,20 @@ public class ASTParserLoadingTest extends FunctionalTestCase { assertEquals(2, listViaSql.size()); assertEquals(second.getId().longValue(), ((Number)listViaSql.get(0)).longValue()); assertEquals(first.getId().longValue(), ((Number)listViaSql.get(1)).longValue()); - + // Check order via HQL. Now first comes first b/c the read negates the DB negation. List listViaHql = s.createQuery("from SimpleEntityWithAssociation order by negatedNumber").list(); assertEquals(2, listViaHql.size()); assertEquals(first.getId(), ((SimpleEntityWithAssociation)listViaHql.get(0)).getId()); assertEquals(second.getId(), ((SimpleEntityWithAssociation)listViaHql.get(1)).getId()); - + s.delete(first); s.delete(second); t.commit(); s.close(); - + } - + public void testHavingWithCustomColumnReadAndWrite() { Session s = openSession(); Transaction t = s.beginTransaction(); @@ -1327,15 +1322,15 @@ public class ASTParserLoadingTest extends FunctionalTestCase { Number r = (Number)s.createQuery("select sum(negatedNumber) from SimpleEntityWithAssociation " + "group by name having sum(negatedNumber) < 20").uniqueResult(); assertEquals(r.intValue(), 15); - + s.delete(first); s.delete(second); s.delete(third); t.commit(); s.close(); - + } - + public void testLoadSnapshotWithCustomColumnReadAndWrite() { // Exercises entity snapshot load when select-before-update is true. Session s = openSession(); @@ -1347,12 +1342,12 @@ public class ASTParserLoadingTest extends FunctionalTestCase { image.setSizeKb(SIZE_IN_KB); s.persist(image); s.flush(); - + Double sizeViaSql = (Double)s.createSQLQuery("select size_mb from image").uniqueResult(); assertEquals(SIZE_IN_MB, sizeViaSql, 0.01d); t.commit(); s.close(); - + s = openSession(); t = s.beginTransaction(); final double NEW_SIZE_IN_KB = 2048d; @@ -1362,14 +1357,14 @@ public class ASTParserLoadingTest extends FunctionalTestCase { s.flush(); sizeViaSql = (Double)s.createSQLQuery("select size_mb from image").uniqueResult(); - assertEquals(NEW_SIZE_IN_MB, sizeViaSql, 0.01d); - + assertEquals(NEW_SIZE_IN_MB, sizeViaSql, 0.01d); + s.delete(image); t.commit(); s.close(); - + } - + private Human genSimpleHuman(String fName, String lName) { Human h = new Human(); @@ -1836,7 +1831,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { txn.commit(); session.close(); } - + public void testFilterWithCustomColumnReadAndWrite() { Session session = openSession(); Transaction txn = session.beginTransaction(); @@ -1868,7 +1863,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { session.delete(friend); txn.commit(); - session.close(); + session.close(); } public void testSelectExpressions() { @@ -2597,7 +2592,7 @@ public class ASTParserLoadingTest extends FunctionalTestCase { hql = "from Animal a where mod(16, 4) = 4"; session.createQuery(hql).list(); /** - * PostgreSQL >= 8.3.7 typecasts are no longer automatically allowed + * PostgreSQL >= 8.3.7 typecasts are no longer automatically allowed * http://www.postgresql.org/docs/current/static/release-8-3.html */ if(getDialect() instanceof PostgreSQLDialect || getDialect() instanceof HSQLDialect){ @@ -2605,14 +2600,14 @@ public class ASTParserLoadingTest extends FunctionalTestCase { }else{ hql = "from Animal a where bit_length(a.bodyWeight) = 24"; } - + session.createQuery(hql).list(); if(getDialect() instanceof PostgreSQLDialect || getDialect() instanceof HSQLDialect){ hql = "select bit_length(str(a.bodyWeight)) from Animal a"; }else{ hql = "select bit_length(a.bodyWeight) from Animal a"; } - + session.createQuery(hql).list(); /*hql = "select object(a) from Animal a where CURRENT_DATE = :p1 or CURRENT_TIME = :p2 or CURRENT_TIMESTAMP = :p3"; 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 835de096d7..e015940f03 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 @@ -4,10 +4,8 @@ package org.hibernate.test.hql; import java.util.ArrayList; import java.util.Date; import java.util.List; - import junit.framework.AssertionFailedError; import junit.framework.Test; - import org.hibernate.QueryException; import org.hibernate.Transaction; import org.hibernate.classic.Session; @@ -15,12 +13,9 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.hql.ast.HqlSqlWalker; import org.hibernate.id.IdentifierGenerator; +import org.hibernate.persister.entity.EntityPersister; import org.hibernate.testing.junit.functional.FunctionalTestCase; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.hibernate.persister.entity.EntityPersister; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** @@ -30,8 +25,6 @@ import org.slf4j.LoggerFactory; */ public class BulkManipulationTest extends FunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger( BulkManipulationTest.class ); - public BulkManipulationTest(String name) { super( name ); } @@ -66,7 +59,7 @@ public class BulkManipulationTest extends FunctionalTestCase { fail( "no exception thrown" ); } catch( QueryException e ) { - log.debug( "Caught expected error type : " + e.getMessage() ); + LOG.debug("Caught expected error type : " + e.getMessage()); } t.commit(); @@ -82,7 +75,7 @@ public class BulkManipulationTest extends FunctionalTestCase { fail( "no exception thrown" ); } catch( QueryException e ) { - log.debug( "Caught expected error type : " + e.getMessage() ); + LOG.debug("Caught expected error type : " + e.getMessage()); } t.commit(); @@ -166,12 +159,12 @@ public class BulkManipulationTest extends FunctionalTestCase { Transaction t = s.beginTransaction(); s.createQuery( "insert into Pickup (id, vin, owner) select id, vin, owner from Car" ).executeUpdate(); - + t.commit(); t = s.beginTransaction(); s.createQuery( "delete Vehicle" ).executeUpdate(); - + t.commit(); s.close(); @@ -205,8 +198,8 @@ public class BulkManipulationTest extends FunctionalTestCase { c.setOwner("NotKirsten"); assertEquals(0,s.getNamedQuery( "native-delete-car" ).setString( 0, "Kirsten" ).executeUpdate()); assertEquals(1,s.getNamedQuery( "native-delete-car" ).setString( 0, "NotKirsten" ).executeUpdate()); - - + + assertEquals(0,s.createSQLQuery( "delete from SUV where owner = :owner" ).setString( "owner", "NotThere" ).executeUpdate()); assertEquals(1,s.createSQLQuery( "delete from SUV where owner = :owner" ).setString( "owner", "Joe" ).executeUpdate()); s.createSQLQuery( "delete from Pickup" ).executeUpdate(); @@ -221,7 +214,7 @@ public class BulkManipulationTest extends FunctionalTestCase { data.cleanup(); } - + public void testInsertWithManyToOne() { TestData data = new TestData(); data.prepare(); @@ -700,7 +693,7 @@ public class BulkManipulationTest extends FunctionalTestCase { fail( "update allowed across implicit join" ); } catch( QueryException e ) { - log.debug( "TEST (OK) : " + e.getMessage() ); + LOG.debug("TEST (OK) : " + e.getMessage()); // expected condition } @@ -1025,7 +1018,7 @@ public class BulkManipulationTest extends FunctionalTestCase { data.cleanup(); } - + public void testDeleteUnionSubclassAbstractRoot() { TestData data = new TestData(); data.prepare(); @@ -1184,7 +1177,7 @@ public class BulkManipulationTest extends FunctionalTestCase { add.setStreet("Main st"); add.setPostalCode("3000"); zoo.setAddress(add); - + pettingZoo = new PettingZoo(); pettingZoo.setName( "Petting Zoo" ); Address addr = new Address(); diff --git a/hibernate-core/src/test/java/org/hibernate/test/hql/FunctionNameAsColumnTest.java b/hibernate-core/src/test/java/org/hibernate/test/hql/FunctionNameAsColumnTest.java index 7933ccf95f..0784ac337b 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/hql/FunctionNameAsColumnTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/hql/FunctionNameAsColumnTest.java @@ -25,11 +25,7 @@ package org.hibernate.test.hql; import java.util.List; - import junit.framework.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.FetchMode; import org.hibernate.Hibernate; import org.hibernate.Session; @@ -49,8 +45,6 @@ import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; */ public class FunctionNameAsColumnTest extends FunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger( FunctionNameAsColumnTest.class ); - public FunctionNameAsColumnTest(String name) { super( name ); } @@ -61,7 +55,8 @@ public class FunctionNameAsColumnTest extends FunctionalTestCase { }; } - public void configure(Configuration cfg) { + @Override + public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( Environment.USE_QUERY_CACHE, "false" ); } 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 8c1f4ef4f1..1bc98d04b0 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,14 +1,11 @@ package org.hibernate.test.jpa.cascade; -import org.hibernate.test.jpa.AbstractJPATest; +import junit.framework.Test; import org.hibernate.Session; import org.hibernate.TransientObjectException; +import org.hibernate.test.jpa.AbstractJPATest; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import junit.framework.Test; - /** * According to the JPA spec, persist()ing an entity should throw an exception * when said entity contains a reference to a transient entity through a mapped @@ -24,13 +21,12 @@ import junit.framework.Test; */ public class CascadeTest extends AbstractJPATest { - public static final Logger log = LoggerFactory.getLogger( CascadeTest.class ); - public CascadeTest(String name) { super( name ); } - public String[] getMappings() { + @Override + public String[] getMappings() { return new String[] { "jpa/cascade/ParentChild.hbm.xml" }; } @@ -55,7 +51,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -84,7 +80,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -113,7 +109,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -140,7 +136,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -167,7 +163,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -193,7 +189,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -219,7 +215,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception", e ); + LOG.trace("handled expected exception", e); s.getTransaction().rollback(); } finally { @@ -246,7 +242,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception : " + e ); + LOG.trace("handled expected exception : " + e); s.getTransaction().rollback(); } finally { @@ -273,7 +269,7 @@ public class CascadeTest extends AbstractJPATest { } catch( TransientObjectException e ) { // expected result - log.trace( "handled expected exception : " + e ); + LOG.trace("handled expected exception : " + e); s.getTransaction().rollback(); } finally { @@ -300,7 +296,7 @@ public class CascadeTest extends AbstractJPATest { s.getTransaction().commit(); } catch( Throwable t ) { - log.warn( "unable to cleanup test data [" + fullTestName() + "] : " + t ); + LOG.warn("unable to cleanup test data [" + fullTestName() + "] : " + t); } finally { if ( s != null ) { 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 390bd85459..b530c3f132 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 @@ -18,10 +18,8 @@ import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; - import junit.framework.Test; import junit.textui.TestRunner; - import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.FlushMode; @@ -35,7 +33,6 @@ import org.hibernate.QueryException; import org.hibernate.ScrollableResults; import org.hibernate.Transaction; import org.hibernate.classic.Session; -import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; @@ -55,18 +52,15 @@ import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.TimesTenDialect; import org.hibernate.engine.SessionFactoryImplementor; +import org.hibernate.proxy.HibernateProxy; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.test.common.ConnectionProviderBuilder; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.hibernate.proxy.HibernateProxy; import org.hibernate.util.JoinedIterator; import org.hibernate.util.SerializationHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class FooBarTest extends LegacyTestCase { - private static final Logger log = LoggerFactory.getLogger( FooBarTest.class ); public FooBarTest(String arg) { super(arg); @@ -450,11 +444,11 @@ public class FooBarTest extends LegacyTestCase { foo.getFoo().setFoo(foo); foo.setString("fizard"); //The following test is disabled for databases with no subselects...also for Interbase (not sure why). - if ( - !(getDialect() instanceof MySQLDialect) && - !(getDialect() instanceof HSQLDialect) && - !(getDialect() instanceof MckoiDialect) && - !(getDialect() instanceof SAPDBDialect) && + if ( + !(getDialect() instanceof MySQLDialect) && + !(getDialect() instanceof HSQLDialect) && + !(getDialect() instanceof MckoiDialect) && + !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof PointbaseDialect) && !(getDialect() instanceof DerbyDialect) ) { @@ -1372,7 +1366,7 @@ public class FooBarTest extends LegacyTestCase { s.evict(baz); tx.commit(); s.disconnect(); - + s.reconnect(); tx = s.beginTransaction(); assertTrue( s.getCurrentLockMode(b)==LockMode.NONE ); @@ -1654,7 +1648,7 @@ public class FooBarTest extends LegacyTestCase { s.createQuery( "from Glarch g where g.multiple.count=12" ).list().get(0); s.getTransaction().commit(); s.close(); - + s = openSession(); s.beginTransaction(); g = (Glarch) s.createQuery( "from Glarch g where g.multiple.glarch=g and g.multiple.count=12" ).list().get(0); @@ -1734,7 +1728,7 @@ public class FooBarTest extends LegacyTestCase { } - if (dialectSupportsEmptyInList("HQL 'x in (:name)' with EMPTY_LIST.")) { + if (dialectSupportsEmptyInList("HQL 'x in (:name)' with EMPTY_LIST.")) { q.setParameterList("nameList", Collections.EMPTY_LIST); list = q.list(); assertTrue( list.size()==0 ); @@ -2330,9 +2324,9 @@ public class FooBarTest extends LegacyTestCase { ).iterate(); while ( iter.hasNext() ) { Object[] arr = (Object[]) iter.next(); - log.info( arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3] ); + LOG.info(arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3]); } - + s.delete(baz); s.delete(baz2); s.delete( foos[1] ); @@ -3526,7 +3520,7 @@ public class FooBarTest extends LegacyTestCase { assertTrue( "multi-column find", row[0]==foo && row[1]==foo.getFoo() ); txn.commit(); s.close(); - + s = openSession(); txn = s.beginTransaction(); Iterator iter = s.createQuery( 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 de43dd9635..5b542bca25 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 @@ -30,11 +30,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; - import junit.framework.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Transaction; @@ -44,21 +40,19 @@ import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.InterbaseDialect; import org.hibernate.dialect.MckoiDialect; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.SybaseDialect; +import org.hibernate.dialect.Oracle9iDialect; +import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.Sybase11Dialect; import org.hibernate.dialect.SybaseASE15Dialect; import org.hibernate.dialect.SybaseAnywhereDialect; +import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.TimesTenDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.Oracle9iDialect; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; public class SQLFunctionsTest extends LegacyTestCase { - private static final Logger log = LoggerFactory.getLogger(SQLFunctionsTest.class); - public SQLFunctionsTest(String name) { super(name); } @@ -189,7 +183,7 @@ public class SQLFunctionsTest extends LegacyTestCase { parameters.put("count", new Integer(simple.getCount())); Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count"); - q.setProperties(((Map)parameters)); + q.setProperties((parameters)); assertTrue( q.list().get(0)==simple ); List l = new ArrayList(); @@ -619,11 +613,11 @@ public class SQLFunctionsTest extends LegacyTestCase { public void testSqlFunctionAsAlias() throws Exception { String functionName = locateAppropriateDialectFunctionNameForAliasTest(); if (functionName == null) { - log.info("Dialect does not list any no-arg functions"); + LOG.info("Dialect does not list any no-arg functions"); return; } - log.info("Using function named [" + functionName + "] for 'function as alias' test"); + LOG.info("Using function named [" + functionName + "] for 'function as alias' test"); String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10"; Session s = openSession(); 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 75934f5e28..99dec7831b 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 @@ -22,20 +22,15 @@ package org.hibernate.test.stateless.fetching; import java.util.Date; - import junit.framework.Test; - -import org.hibernate.testing.junit.functional.FunctionalTestCase; -import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.DefaultNamingStrategy; -import org.hibernate.util.StringHelper; +import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.StatelessSession; -import org.hibernate.Hibernate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.DefaultNamingStrategy; +import org.hibernate.testing.junit.functional.FunctionalTestCase; +import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite; +import org.hibernate.util.StringHelper; /** * TODO : javadoc @@ -43,7 +38,6 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class StatelessSessionFetchingTest extends FunctionalTestCase { - private static final Logger log = LoggerFactory.getLogger( StatelessSessionFetchingTest.class ); public StatelessSessionFetchingTest(String name) { super( name ); @@ -64,7 +58,7 @@ public class StatelessSessionFetchingTest extends FunctionalTestCase { protected String applyPrefix(String baseTableName) { String prefixed = prefix + '_' + baseTableName; - log.debug( "prefixed table name : {} -> {} ", baseTableName, prefixed ); + LOG.debug("prefixed table name : " + baseTableName + " -> " + prefixed); return prefixed; } 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 index 11d4f58446..e1cca6fad7 100644 --- a/hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java +++ b/hibernate-core/src/test/java/org/hibernate/testing/junit/SkipLog.java @@ -23,8 +23,7 @@ */ package org.hibernate.testing.junit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.Logger; /** * Well-known-location lookup for the test-skip log... @@ -32,5 +31,6 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class SkipLog { - public static final Logger LOG = LoggerFactory.getLogger( "org.hibernate.test.SKIPPED" ); + + 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 0726cc837a..c99ab950ab 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 @@ -27,13 +27,11 @@ import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; 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; @@ -49,7 +47,7 @@ import org.hibernate.test.common.ServiceRegistryHolder; */ public abstract class UnitTestCase extends junit.framework.TestCase { - private static final Logger log = LoggerFactory.getLogger( UnitTestCase.class ); + public static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); private ServiceRegistryHolder serviceRegistryHolder; @@ -63,10 +61,11 @@ public abstract class UnitTestCase extends junit.framework.TestCase { * * @throws Throwable */ - public void runBare() throws Throwable { + @Override + public void runBare() throws Throwable { final boolean doValidate = getName().endsWith( "FailureExpected" ) && Boolean.getBoolean( "hibernate.test.validatefailureexpected" ); try { - log.info( "Starting test [" + fullTestName() + "]" ); + LOG.info("Starting test [" + fullTestName() + "]"); super.runBare(); if ( doValidate ) { throw new FailureExpectedTestPassedException(); @@ -84,7 +83,7 @@ public abstract class UnitTestCase extends junit.framework.TestCase { } } finally { - log.info( "Completed test [" + fullTestName() + "]" ); + LOG.info("Completed test [" + fullTestName() + "]"); } } @@ -149,9 +148,9 @@ public abstract class UnitTestCase extends junit.framework.TestCase { protected void reportSkip(String reason, String testDescription) { SkipLog.LOG.warn( "*** skipping [" + fullTestName() + "] - " + testDescription + " : " + reason, new Exception() ); } - + // testsuite utitities --------------------------------------------------- - + /** * Supports easy creation of TestSuites where a subclass' "FailureExpected" * version of a base test is included in the suite, while the base test @@ -161,7 +160,7 @@ public abstract class UnitTestCase extends junit.framework.TestCase { * does not include testBar(). */ public static TestSuite createFailureExpectedSuite(Class testClass) { - + TestSuite allTests = new TestSuite(testClass); Set failureExpected = new HashSet(); Enumeration tests = allTests.tests(); @@ -171,9 +170,9 @@ public abstract class UnitTestCase extends junit.framework.TestCase { String name = ((TestCase) t).getName(); if (name.endsWith("FailureExpected")) failureExpected.add(name); - } + } } - + TestSuite result = new TestSuite(); tests = allTests.tests(); while (tests.hasMoreElements()) { @@ -183,9 +182,9 @@ public abstract class UnitTestCase extends junit.framework.TestCase { if (!failureExpected.contains(name + "FailureExpected")) { result.addTest(t); } - } + } } - + return result; } } 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 da2d44e80d..ed3191e34b 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,27 +23,23 @@ */ package org.hibernate.testing.junit.functional; +import java.sql.Connection; import java.util.Collections; -import java.util.List; -import java.util.Map; import java.util.HashMap; import java.util.Iterator; -import java.sql.Connection; - -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Mappings; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.DerbyDialect; -import org.hibernate.SessionFactory; +import java.util.List; +import java.util.Map; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.Session; -import org.hibernate.testing.junit.UnitTestCase; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Mappings; +import org.hibernate.dialect.DB2Dialect; +import org.hibernate.dialect.DerbyDialect; +import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionFactoryImplementor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.testing.junit.UnitTestCase; /** * Most of the Hibernate test suite in fact is a series of functional tests, not @@ -53,8 +49,6 @@ import org.slf4j.LoggerFactory; */ public abstract class FunctionalTestCase extends UnitTestCase implements ExecutionEnvironment.Settings { - private static final Logger log = LoggerFactory.getLogger( FunctionalTestCase.class ); - private ExecutionEnvironment environment; private boolean isEnvironmentLocallyManaged; @@ -86,9 +80,10 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi * * @throws Exception */ - protected final void setUp() throws Exception { + @Override + protected final void setUp() throws Exception { if ( environment == null ) { - log.info( "Building locally managed execution env" ); + LOG.info("Building locally managed execution env"); isEnvironmentLocallyManaged = true; environment = new ExecutionEnvironment( this ); environment.initialize( getConnectionProviderInjectionProperties() ); @@ -106,10 +101,11 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi * * @throws Exception */ - protected final void tearDown() throws Exception { + @Override + protected final void tearDown() throws Exception { cleanupTest(); if ( isEnvironmentLocallyManaged ) { - log.info( "Destroying locally managed execution env" ); + LOG.info("Destroying locally managed execution env"); environment.complete(); environment = null; } @@ -120,7 +116,8 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi * * @throws Throwable */ - protected void runTest() throws Throwable { + @Override + protected void runTest() throws Throwable { final boolean stats = sfi().getStatistics().isStatisticsEnabled(); try { if ( stats ) { @@ -147,7 +144,7 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi assertAllDataRemoved(); } catch ( Throwable e ) { - log.trace( "test run resulted in error; attempting to cleanup", e ); + LOG.trace("test run resulted in error; attempting to cleanup", e); try { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { @@ -206,7 +203,8 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi } } - protected void skipExpectedFailure(Throwable error) { + @Override + protected void skipExpectedFailure(Throwable error) { super.skipExpectedFailure( error ); try { if ( recreateSchemaAfterFailure() && environment != null ) { 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 1796cf7203..36c6eca732 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 @@ -25,13 +25,9 @@ package org.hibernate.testing.junit.functional; import java.util.Collections; import java.util.Map; - -import junit.framework.TestSuite; import junit.framework.Test; import junit.framework.TestResult; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import junit.framework.TestSuite; /** * A specialized {@link junit.framework.TestSuite} implementation intended @@ -43,7 +39,7 @@ import org.slf4j.LoggerFactory; */ public class FunctionalTestClassTestSuite extends TestSuite { - private static final Logger log = LoggerFactory.getLogger( FunctionalTestClassTestSuite.class ); + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); private ExecutionEnvironment.Settings settings; private ExecutionEnvironment environment; @@ -60,8 +56,9 @@ public class FunctionalTestClassTestSuite extends TestSuite { } - public void addTest(Test test) { - log.trace( "adding test [" + test + "]" ); + @Override + public void addTest(Test test) { + LOG.trace("adding test [" + test + "]"); if ( settings == null ) { if ( test instanceof ExecutionEnvironment.Settings ) { settings = ( ExecutionEnvironment.Settings ) test; @@ -75,13 +72,14 @@ public class FunctionalTestClassTestSuite extends TestSuite { super.addTest( test ); } - public void run(TestResult testResult) { + @Override + public void run(TestResult testResult) { if ( testCount == 0 ) { // might be zero if database-specific... return; } try { - log.info( "Starting test-suite [" + getName() + "]" ); + LOG.info("Starting test-suite [" + getName() + "]"); setUp(); testPosition = 0; super.run( testResult ); @@ -92,11 +90,12 @@ public class FunctionalTestClassTestSuite extends TestSuite { } catch( Throwable ignore ) { } - log.info( "Completed test-suite [" + getName() + "]" ); + LOG.info("Completed test-suite [" + getName() + "]"); } } - public void runTest(Test test, TestResult testResult) { + @Override + public void runTest(Test test, TestResult testResult) { testPosition++; if ( environmentSetupError != null ) { testResult.startTest( test ); @@ -127,7 +126,7 @@ public class FunctionalTestClassTestSuite extends TestSuite { if ( settings == null ) { return; } - log.info( "Building aggregated execution environment" ); + LOG.info("Building aggregated execution environment"); try { environment = new ExecutionEnvironment( settings ); environment.initialize( getConnectionProviderInjectionProperties() ); @@ -143,7 +142,7 @@ public class FunctionalTestClassTestSuite extends TestSuite { protected void tearDown() { if ( environment != null ) { - log.info( "Destroying aggregated execution environment" ); + LOG.info("Destroying aggregated execution environment"); environment.complete(); this.environment = null; } 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 7e2fe5be78..a0cf7e17c2 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 @@ -32,11 +32,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.SQLException; - import junit.framework.TestCase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import org.hibernate.Logger; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; @@ -61,7 +58,7 @@ import org.hibernate.util.StringHelper; */ public abstract class HibernateTestCase extends TestCase { - public static final Logger log = LoggerFactory.getLogger( HibernateTestCase.class ); + public static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); protected static Configuration cfg; private static Class lastTestClass; 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 fe9b5fa5dc..d395874081 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 @@ -34,9 +34,7 @@ import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAResource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.Logger; /** * SimpleJtaTransactionImpl implementation @@ -44,7 +42,8 @@ import org.slf4j.LoggerFactory; * @author Steve Ebersole */ public class SimpleJtaTransactionImpl implements Transaction { - private static final Logger log = LoggerFactory.getLogger( SimpleJtaTransactionImpl.class ); + + private static final Logger LOG = org.jboss.logging.Logger.getMessageLogger(Logger.class, "Test Logger"); private int status; private LinkedList synchronizations; @@ -64,7 +63,7 @@ public class SimpleJtaTransactionImpl implements Transaction { throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { if ( status == Status.STATUS_MARKED_ROLLBACK ) { - log.trace( "on commit, status was marked for rollback-only" ); + LOG.trace("on commit, status was marked for rollback-only"); rollback(); } else {