-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: "Not binding factory to JNDI, no JNDI name configured&a
PostPosted: Fri Jan 27, 2006 11:36 am 
Regular
Regular

Joined: Fri Jan 20, 2006 9:38 am
Posts: 61
Location: Notts, UK
I'm implementing persistent entity auditing using an org.hibernate.event.PostUpdateEventListener

In the listener, I call a session bean, com.fcl.util.EntityAuditorBean which creates an entity bean called AuditLog which is annotated, and deploys just fine. I log all database updates to a log4j log, and it's great: all creates and deletes are logged with the property values, and all updates are logged with the property old and new values eg:

Code:
2006-01-27 13:00:41,062 [EntityAuditorBean] User Animal updated Customer ID 16
Address Forward House, 161 Glaisdale Drive -> Foward Castle
City Nottingham -> Wollaton
County Nottinghamshire -> Notts
PhoneNumber 01159 360 289 -> 0115 663 3355
Postcode NG8 4GY -> NG9 6HG


Problem is, I can't persist the AuditLog entity. I can't use an injected entity manager, ie

Code:
   @PersistenceContext(unitName = "cal")
   private         EntityManager   em;


Because that caused an error. However, when I do

Code:
      em = Persistence.createEntityManagerFactory("cal").createEntityManager();


I get

Code:
11:11:49,890 INFO  [SessionFactoryImpl] building session factory
11:11:49,921 INFO  [SessionFactoryObjectFactory] Not binding factory to JNDI, no JNDI name configured
11:11:49,921 INFO  [SchemaUpdate] Running hbm2ddl schema update
11:11:49,921 INFO  [SchemaUpdate] fetching database metadata
11:11:49,921 ERROR [SchemaUpdate] could not get database metadata
org.jboss.util.NestedSQLException: Transaction is not active: tx=TransactionImpl:XidImpl[FormatId=257, GlobalId=NigelW/88, BranchQua
l=, localId=88]; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImpl:XidImpl[Format
Id=257, GlobalId=NigelW/88, BranchQual=, localId=88])
        at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:79)
        at org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:69)
        at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:127)
        at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:298)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1145)
        at org.hibernate.ejb.Ejb3Configuration.createEntityManagerFactory(Ejb3Configuration.java:358)
        at org.hibernate.ejb.Ejb3Configuration.createEntityManagerFactory(Ejb3Configuration.java:484)
        at org.hibernate.ejb.Ejb3Configuration.createFactory(Ejb3Configuration.java:96)
        at org.hibernate.ejb.Ejb3Configuration.createEntityManagerFactory(Ejb3Configuration.java:142)
        at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:73)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:37)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:27)
        at com.fcl.util.EntityAuditorBean.onPostUpdate(EntityAuditorBean.java:61)


It should be easy shouldn't it? Doesn't Hibernate make it easy to store things? Why is it just giving me this seemingly arbitrary error?


Top
 Profile  
 
 Post subject: Re: "Not binding factory to JNDI, no JNDI name configur
PostPosted: Fri Jan 27, 2006 1:36 pm 
Newbie

Joined: Tue Jan 03, 2006 7:30 am
Posts: 18
Location: Budapest, Hungary
Animal wrote:
Problem is, I can't persist the AuditLog entity. I can't use an injected entity manager, ie

Code:
   @PersistenceContext(unitName = "cal")
   private         EntityManager   em;


Because that caused an error.

I think this is the error you should be working on. Can you post the details? (i.e. what do you exactly do and what error do you get)

Quote:
However, when I do
Code:
      em = Persistence.createEntityManagerFactory("cal").createEntityManager();


Don't. You are creating a new EMF, which is resource-intensive. It will slow down your app a lot if you are calling it often (and it appears you will).

SchemaUpdate and JTA don't really go together... I think that's the cause of your exception. The "no JNDI name" stuff is not an error message, only an informational notice, and is perfectly okay in an EJB3 environment.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 30, 2006 5:51 am 
Regular
Regular

Joined: Fri Jan 20, 2006 9:38 am
Posts: 61
Location: Notts, UK
OK, I'll put that injected EM back, and see what happens. Can't just now, been pulled out to fix something else. Back soon.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 30, 2006 7:27 am 
Regular
Regular

Joined: Fri Jan 20, 2006 9:38 am
Posts: 61
Location: Notts, UK
OK, here's is what happens at the em.persist(entity) call when I use

Code:
   @PersistenceContext(unitName = "cal")
   private         EntityManager   em;


Code:
11:24:59,734 ERROR [TxPolicy] IllegalStateException while setting transaction for rollback only
java.lang.IllegalStateException: Already committed. TransactionImpl:XidImpl[FormatId=257, GlobalId=NigelW/24, BranchQual=, localId=2
4]
        at org.jboss.tm.TransactionImpl.setRollbackOnly(TransactionImpl.java:671)
        at org.jboss.aspects.tx.TxPolicy.setRollbackOnly(TxPolicy.java:199)
        at org.jboss.ejb3.tx.Ejb3TxPolicy.handleInCallerTx(Ejb3TxPolicy.java:63)
        at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:117)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:138)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:148)
        at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:60)
        at $Proxy136.onPostUpdate(Unknown Source)
        at com.fcl.util.HibernateEventListener.onPostUpdate(HibernateEventListener.java:41)
        at org.hibernate.action.EntityUpdateAction.postCommitUpdate(EntityUpdateAction.java:178)
        at org.hibernate.action.EntityUpdateAction.afterTransactionCompletion(EntityUpdateAction.java:243)
        at org.hibernate.engine.ActionQueue.afterTransactionCompletion(ActionQueue.java:171)
        at org.hibernate.impl.SessionImpl.afterTransactionCompletion(SessionImpl.java:427)
        at org.hibernate.jdbc.JDBCContext.afterTransactionCompletion(JDBCContext.java:219)
        at org.hibernate.transaction.CacheSynchronization.afterCompletion(CacheSynchronization.java:85)
        at org.jboss.tm.TransactionImpl.doAfterCompletion(TransactionImpl.java:1508)
        at org.jboss.tm.TransactionImpl.completeTransaction(TransactionImpl.java:1180)
        at org.jboss.tm.TransactionImpl.commit(TransactionImpl.java:359)
        at org.jboss.aspects.tx.TxPolicy.endTransaction(TxPolicy.java:162)
        at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:74)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:189)
        at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:107)
        at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:37)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:88)
        at $Proxy143.updateCustomer(Unknown Source)
        at com.fcl.struts.action.UpdateCustomerAction.execute(UpdateCustomerAction.java:65)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
        at java.lang.Thread.run(Thread.java:595)
11:24:59,781 ERROR [AssertionFailure] an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to
unsafe use of the session)
javax.ejb.EJBTransactionRolledbackException: null; CausedByException is:
        Transaction must be active to access EntityManager
        at org.jboss.ejb3.tx.Ejb3TxPolicy.handleInCallerTx(Ejb3TxPolicy.java:65)
        at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:117)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:138)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:148)
        at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:60)
        at $Proxy136.onPostUpdate(Unknown Source)
        at com.fcl.util.HibernateEventListener.onPostUpdate(HibernateEventListener.java:41)
        at org.hibernate.action.EntityUpdateAction.postCommitUpdate(EntityUpdateAction.java:178)
        at org.hibernate.action.EntityUpdateAction.afterTransactionCompletion(EntityUpdateAction.java:243)
        at org.hibernate.engine.ActionQueue.afterTransactionCompletion(ActionQueue.java:171)
        at org.hibernate.impl.SessionImpl.afterTransactionCompletion(SessionImpl.java:427)
        at org.hibernate.jdbc.JDBCContext.afterTransactionCompletion(JDBCContext.java:219)
        at org.hibernate.transaction.CacheSynchronization.afterCompletion(CacheSynchronization.java:85)
        at org.jboss.tm.TransactionImpl.doAfterCompletion(TransactionImpl.java:1508)
        at org.jboss.tm.TransactionImpl.completeTransaction(TransactionImpl.java:1180)
        at org.jboss.tm.TransactionImpl.commit(TransactionImpl.java:359)
        at org.jboss.aspects.tx.TxPolicy.endTransaction(TxPolicy.java:162)
        at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:74)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:189)
        at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:107)
        at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:37)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:88)
        at $Proxy143.updateCustomer(Unknown Source)
        at com.fcl.struts.action.UpdateCustomerAction.execute(UpdateCustomerAction.java:65)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
        at java.lang.Thread.run(Thread.java:595)
javax.persistence.TransactionRequiredException: Transaction must be active to access EntityManager
        at org.jboss.ejb3.entity.ManagedEntityManagerFactory.getSession(ManagedEntityManagerFactory.java:125)
        at org.jboss.ejb3.entity.InjectedEntityManager.getSession(InjectedEntityManager.java:154)
        at org.jboss.ejb3.entity.InjectedEntityManager.persist(InjectedEntityManager.java:97)
        at com.fcl.util.EntityAuditorBean.onPostUpdate(EntityAuditorBean.java:85)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:109)
        at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:113)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:138)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:148)
        at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:60)
        at $Proxy136.onPostUpdate(Unknown Source)
        at com.fcl.util.HibernateEventListener.onPostUpdate(HibernateEventListener.java:41)
        at org.hibernate.action.EntityUpdateAction.postCommitUpdate(EntityUpdateAction.java:178)
        at org.hibernate.action.EntityUpdateAction.afterTransactionCompletion(EntityUpdateAction.java:243)
        at org.hibernate.engine.ActionQueue.afterTransactionCompletion(ActionQueue.java:171)
        at org.hibernate.impl.SessionImpl.afterTransactionCompletion(SessionImpl.java:427)
        at org.hibernate.jdbc.JDBCContext.afterTransactionCompletion(JDBCContext.java:219)
        at org.hibernate.transaction.CacheSynchronization.afterCompletion(CacheSynchronization.java:85)
        at org.jboss.tm.TransactionImpl.doAfterCompletion(TransactionImpl.java:1508)
        at org.jboss.tm.TransactionImpl.completeTransaction(TransactionImpl.java:1180)
        at org.jboss.tm.TransactionImpl.commit(TransactionImpl.java:359)
        at org.jboss.aspects.tx.TxPolicy.endTransaction(TxPolicy.java:162)
        at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:74)
        at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:61)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:32)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:91)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:189)
        at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:107)
        at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:37)
        at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:98)
        at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:88)
        at $Proxy143.updateCustomer(Unknown Source)
        at com.fcl.struts.action.UpdateCustomerAction.execute(UpdateCustomerAction.java:65)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
        at java.lang.Thread.run(Thread.java:595)


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 30, 2006 10:01 am 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
no code no help

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 30, 2006 1:09 pm 
Regular
Regular

Joined: Fri Jan 20, 2006 9:38 am
Posts: 61
Location: Notts, UK
OK, so you can see what I'm trying to do:

The xml config which sets up the listeners:

Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
   <hibernate-configuration>
      <session-factory>
         <event type="pre-update">
            <listener class="com.fcl.util.HibernateEventListener"/>
         </event>
         <event type="post-commit-update">
            <listener class="com.fcl.util.HibernateEventListener"/>
              <listener class="org.hibernate.lucene.event.LuceneEventListener"/>
         </event>
         <event type="post-commit-insert">
            <listener class="com.fcl.util.HibernateEventListener"/>
              <listener class="org.hibernate.lucene.event.LuceneEventListener"/>
         </event>
         <event type="post-commit-delete">
            <listener class="com.fcl.util.HibernateEventListener"/>
              <listener class="org.hibernate.lucene.event.LuceneEventListener"/>
         </event>
       </session-factory>
   </hibernate-configuration>


The entity representing a database update:

Code:
package entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratorType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;
import java.util.*;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostDeleteEvent;
import javax.ejb.SessionContext;

@Entity
@Table(name = "AUDIT_LOG")
public class AuditLog implements Serializable
{
   public static final int   CREATE = 0;
   public static final int   UPDATE = 1;
   public static final int   DELETE = 2;

   private long            id;
   private String            className;
   private Serializable      entityId;
   private String            userId;
   private int               operation;
   private List<String>      changedProperties;
   private List<Object>      oldValues;
   private List<Object>      newValues;

   public static final long   serialVersionUID   = 0xfc10765;

   public void audit(SessionContext ctx, PostInsertEvent e)
   {
      className = e.getEntity().getClass().getCanonicalName();
      className = className.substring(className.lastIndexOf('.') + 1);
      entityId = e.getId();
      userId = ctx.getCallerPrincipal().getName();
      operation = CREATE;
      changedProperties = Arrays.asList(e.getPersister().getPropertyNames());
      newValues = Arrays.asList(e.getState());
   }
   
   public void audit(SessionContext ctx, PostUpdateEvent e)
   {
      className = e.getEntity().getClass().getCanonicalName();
      className = className.substring(className.lastIndexOf('.') + 1);
      entityId = e.getId();
      userId = ctx.getCallerPrincipal().getName();
      operation = UPDATE;

      changedProperties = new ArrayList<String>();
      oldValues = new ArrayList<Object>();
      newValues = new ArrayList<Object>();
      String[] propNames = e.getPersister().getPropertyNames();
      Object[] oldState = e.getOldState();
      Object[] newState = e.getState();
      for (int i = 0; i < oldState.length; i++)
      {
         if (!newState[i].equals(oldState[i]))
         {
            changedProperties.add(propNames[i]);
            oldValues.add(oldState[i]);
            newValues.add(newState[i]);
         }
      }
   }
   
   public void audit(SessionContext ctx, PostDeleteEvent e)
   {
      className = e.getEntity().getClass().getCanonicalName();
      className = className.substring(className.lastIndexOf('.') + 1);
      entityId = e.getId();
      userId = ctx.getCallerPrincipal().getName();
      operation = DELETE;
      changedProperties = Arrays.asList(e.getPersister().getPropertyNames());
      oldValues = Arrays.asList(e.getDeletedState());
   }
   
   public String getOperation()
   {
      switch (operation)
      {
         case CREATE:
            return "CREATE";
         case UPDATE:
            return "UPDATE";
         case DELETE:
            return "DELETE";
      }
      return "UNKNOWN";
   }
   public void setOperation(int o)
   {
      operation = o;
   }
   
   /**
    */
   @Column(name="CLASS_NAME", nullable=false)
   public String getClassName()
   {
      return this.className;
   }
   public void setClassName(String s)
   {
      className = s;
   }

   /**
    */
   @Column(name="ENTITY_ID", nullable=false)
   public Serializable getEntityId()
   {
      return entityId;
   }
   public void setEntityId(Serializable e)
   {
      this.entityId = e;
   }

   /**
    */
   @Column(name="USER", nullable=false)
   public String getUserId()
   {
      return userId;
   }
   public void setUserId(String u)
   {
      this.userId = u;
   }

   /**
    */
   @Column(name="CHANGED_PROPS", nullable=true)
   @Lob
   public List<String> getChangedProperties()
   {
      return this.changedProperties;
   }
   public void setChangedProperties(List<String> p)
   {
      changedProperties = p;
   }

   /**
    */
   @Column(name="OLD_VALUES", nullable=true)
   @Lob
   public List<Object> getOldValues()
   {
      return oldValues;
   }
   public void setOldValues(List<Object> v)
   {
      oldValues = v;
   }

   /**
    */
   @Column(name="NEW_VALUES", nullable=true)
   @Lob
   public List<Object> getNewValues()
   {
      return newValues;
   }
   public void setNewValues(List<Object> v)
   {
      newValues = v;
   }

   /**
    * @return Returns the id.
    */
   @Column(name = "ID", nullable = false)
   @Id(generate = GeneratorType.AUTO)
   public long getId()
   {
      return id;
   }

   /**
    * @param id
    *            The id to set.
    */
   public void setId(long id)
   {
      this.id = id;
   }

   public String toString()
   {
      StringBuilder sb = new StringBuilder(256);
      if (operation == CREATE)
      {
         sb.append("User ").append(getUserId()).append(" created ")
            .append(getClassName()).append(" ID ").append(getEntityId()).append("\r\n");
         for (int i = 0; i < changedProperties.size(); i++)
         {
            int j = sb.length();
            Object newValue = newValues.get(i);
            if (newValue instanceof Collection)
               displayCollection(sb, changedProperties.get(i), (Collection)newValue);
            else
               sb.append(changedProperties.get(i)).append(" = ").append(newValue).append("\r\n");
            sb.replace(j, j + 1, sb.substring(j, j + 1).toUpperCase());
         }
         return sb.toString();
      }
      if (operation == UPDATE)
      {
         sb.append("User ").append(this.getUserId()).append(" updated ")
            .append(getClassName()).append(" ID ").append(getEntityId()).append("\r\n");
         for (int i = 0; i < changedProperties.size(); i++)
         {
            int j = sb.length();
            Object oldValue = oldValues.get(i);
            Object newValue = newValues.get(i);
            if (newValue instanceof Collection)
               displayCollections(sb, changedProperties.get(i), (Collection)oldValue, (Collection)newValue);
            else
               sb.append(changedProperties.get(i)).append(" ").append(oldValue.toString())
                  .append(" -> ").append(newValue.toString()).append("\r\n");
            sb.replace(j, j + 1, sb.substring(j, j + 1).toUpperCase());
         }
         return sb.toString();
      }
      if (operation == DELETE)
      {
         sb.append("User ").append(this.getUserId()).append(" deleted ")
            .append(getClassName()).append(" ID ").append(getEntityId()).append("\r\n");
         for (int i = 0; i < changedProperties.size(); i++)
         {
            int j = sb.length();
            Object oldValue = oldValues.get(i);
            if (oldValue instanceof Collection)
               displayCollection(sb, changedProperties.get(i), (Collection)oldValue);
            else
               sb.append(changedProperties.get(i)).append(" = ").append(oldValue).append("\r\n");
            sb.replace(j, j + 1, sb.substring(j, j + 1).toUpperCase());
         }
         return sb.toString();
      }
      return "Uknown operation";
   }
   
   private static void displayCollection(StringBuilder sb, String name, Collection c)
   {
      sb.append(name).append(':');
      for (Iterator i = c.iterator(); i.hasNext(); )
      {
         sb.append('\t').append(i.next());
      }
   }

   private static void displayCollections(StringBuilder sb, String name, Collection c, Collection c1)
   {
      sb.append(name).append(':');
      int m = 0;
      Iterator i1 = c1.iterator();
      for (Iterator i = c.iterator(); i.hasNext() || i1.hasNext(); )
      {
         if (i.hasNext())
         {
            String v = i.next().toString();
            if (v.length() > m)
               m = v.length();
            sb.append('\t').append(v);
         }
         else
         {
            sb.append('\t');
            for (int j = 0; j < m; j++)
               sb.append(' ');
         }
         if (i1.hasNext())
            sb.append(' ').append(i1.next());
      }
   }

}


The listener:

Code:
package com.fcl.util;

import com.fcl.util.EntityAuditor;
import com.fcl.util.EntityAuditorBean;
import java.lang.reflect.Method;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostDeleteEventListener;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostUpdateEventListener;

/**
*/
public class HibernateEventListener implements PostDeleteEventListener,
      PostInsertEventListener, PreUpdateEventListener, PostUpdateEventListener
{
   private static final long   serialVersionUID   = 12345678L;
   private EntityAuditor       auditBean         = null;
   
   public HibernateEventListener()
   {
   }
   
   private EntityAuditor getEntityAuditor()
   {
      if (auditBean == null)
         auditBean = EntityAuditorBean.getInstance();
      return auditBean;
   }
   
   public void onPostInsert(PostInsertEvent event)
   {
      getEntityAuditor().onPostInsert(event);
   }
   
   public void onPostUpdate(PostUpdateEvent event)
   {
      getEntityAuditor().onPostUpdate(event);
   }

   public void onPostDelete(PostDeleteEvent event)
   {
      getEntityAuditor().onPostDelete(event);
   }

   public boolean onPreUpdate(PreUpdateEvent event)
   {
      new Exception().printStackTrace();
      final Object entity = event.getEntity();
      System.out.println("About to update " + entity);
      Class c = entity.getClass();
      Class[] intf = c.getInterfaces();
      if (intf != null && intf.length > 0)
      {
         for (int i = 0; i < intf.length; i++)
         {
            System.out.println("Customer entity implements " + intf[i].getName());
         }
      }
      Method[] m = c.getMethods();
      if (m != null && m.length > 0)
      {
         for (int i = 0; i < m.length; i++)
         {
            System.out.println(m[i].getName() + "()");
         }
      }
      Object[] state = event.getState();
      if (state != null && state.length > 0)
      {
         for (int i = 0; i < state.length; i++)
         {
            System.out.println(state[i].toString());
         }
      }
      return true;
   }

}


The EntityAuditorBean

Code:
package com.fcl.util;

import entity.AuditLog;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostUpdateEvent;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ejb.Stateless;
import javax.ejb.SessionContext;
import javax.annotation.Resource;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;

@Stateless
public class EntityAuditorBean implements EntityAuditor
{
   @PersistenceContext(unitName = "cal")
   private         EntityManager   em;

   @Resource
   private         SessionContext ctx;
   
   private static   EntityAuditor   theInstance = null;
   
   private Logger   auditLogger = null;
   
   public static   EntityAuditor getInstance()
   {
      if (theInstance == null)
      {
         try
         {
            InitialContext c = new InitialContext();
            theInstance = (EntityAuditor)c.lookup(EntityAuditor.class.getName());
            theInstance.createEntityManager("cal");
            theInstance.setAuditLogger("entity.log");
            
         }
         catch (Exception e)
         {
            e.printStackTrace();
         }
      }
      return theInstance;
   }

   private static final long   serialVersionUID   = 155266L;
   
   public void setAuditLogger(String fileName)
   {
      auditLogger = Logger.getLogger(getClass());
      auditLogger.removeAllAppenders();
      try
      {
         auditLogger.addAppender(new FileAppender(new PatternLayout("%d{ISO8601} [%C{1}] %m"), fileName));
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }
   
   public void createEntityManager(String persistenceUnitName)
   {
      //em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager();
   }

   public void onPostInsert(PostInsertEvent event)
   {
      AuditLog l = new AuditLog();
      l.audit(ctx, event);
      auditLogger.info(l.toString());
      em.persist(l);
   }
   
   public void onPostUpdate(PostUpdateEvent event)
   {
      AuditLog l = new AuditLog();
      l.audit(ctx, event);
      auditLogger.info(l.toString());
      em.persist(l);
   }
   
   public void onPostDelete(PostDeleteEvent event)
   {
      AuditLog l = new AuditLog();
      l.audit(ctx, event);
      auditLogger.info(l.toString());
      em.persist(l);
   }
}


So Hibernate fires the post-update, post-insert, post-delete event, and in my listener, I invoke a session bean which creates the entity to represent that change, and attempt to persist it.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.