-->
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.  [ 2 posts ] 
Author Message
 Post subject: AuditLogInterceptor does not get triggered
PostPosted: Fri Apr 03, 2009 6:32 am 
Beginner
Beginner

Joined: Mon May 26, 2008 3:34 am
Posts: 31
Hello everyone,

I have am interceptor to log insert and update events, but it seems it does not get triggered.

This is my interceptor:

Code:
package com.elnominal.persistence.audit;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.hibernate.CallbackException;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.type.Type;


public class AuditLogInterceptor implements Interceptor {

   private Session session;
   private int userId;
   private String ipAddress;
   private String userAgent;

   private Set<Object> inserts = new HashSet<Object>();
   private Set<Object> updates = new HashSet<Object>();

   public void setSession(Session session) {
      this.session = session;
   }
   
   public void setUserId(int userId) {
      this.userId = userId;
   }
   
   public void setIpAddress(String ipAddress) {
      this.ipAddress = ipAddress;
   }
   
   public void setUserAgent(String userAgent) {
      this.userAgent = userAgent;
   }

   public boolean onSave(Object entity,
                   Serializable id,
                   Object[] state,
                   String[] propertyNames,
                   Type[] types)
         throws CallbackException {

      if (entity instanceof Auditable)
         inserts.add(entity);

      return false;
   }

   public boolean onFlushDirty(Object entity,
                        Serializable id,
                        Object[] currentState,
                        Object[] previousState,
                        String[] propertyNames,
                        Type[] types)
         throws CallbackException {

      if (entity instanceof Auditable)
         updates.add(entity);

      return false;
   }

   public boolean onLoad(Object o, Serializable serializable, Object[] objects, String[] strings, Type[] types) throws CallbackException {
      return false;
   }

   public void onDelete(Object o, Serializable serializable, Object[] objects, String[] strings, Type[] types) throws CallbackException {
   }

   public void preFlush(Iterator iterator) throws CallbackException {
   }

   public void postFlush(Iterator iterator) throws CallbackException {
      try {
         for (Iterator it = inserts.iterator(); it.hasNext();) {
            Auditable entity = (Auditable) it.next();
            System.out.println("Intercepted creation of : " + entity);
            AuditLog.logEvent("create",
                          entity,
                          userId,
                          ipAddress,
                          userAgent,
                          session.connection());
         }
         for (Iterator it = updates.iterator(); it.hasNext();) {
            Auditable entity = (Auditable) it.next();
            System.out.println("Intercepted modification of : " + entity);
            AuditLog.logEvent("update",
                          entity,
                          userId,
                          ipAddress,
                          userAgent,
                          session.connection());
         }
      } catch (HibernateException ex) {
         throw new CallbackException(ex);
      } finally {
         inserts.clear();
         updates.clear();
      }
   }

   public Boolean isUnsaved(Object o) {
      return null;
   }

   public int[] findDirty(Object o, Serializable serializable, Object[] objects, Object[] objects1, String[] strings, Type[] types) {
      return null;
   }

   public Object instantiate(Class aClass, Serializable serializable) throws CallbackException {
      return null;
   }
   @Override
   public void afterTransactionBegin(Transaction arg0) {
      // TODO Auto-generated method stub
      
   }
   @Override
   public void afterTransactionCompletion(Transaction arg0) {
      // TODO Auto-generated method stub
      
   }
   @Override
   public void beforeTransactionCompletion(Transaction arg0) {
      // TODO Auto-generated method stub
      
   }
   @Override
   public Object getEntity(String arg0, Serializable arg1)
         throws CallbackException {
      // TODO Auto-generated method stub
      return null;
   }
   @Override
   public String getEntityName(Object arg0) throws CallbackException {
      // TODO Auto-generated method stub
      return null;
   }
   @Override
   public Object instantiate(String arg0, EntityMode arg1, Serializable arg2)
         throws CallbackException {
      // TODO Auto-generated method stub
      return null;
   }
   @Override
   public Boolean isTransient(Object arg0) {
      // TODO Auto-generated method stub
      return null;
   }
   @Override
   public void onCollectionRecreate(Object arg0, Serializable arg1)
         throws CallbackException {
      // TODO Auto-generated method stub
      
   }
   @Override
   public void onCollectionRemove(Object arg0, Serializable arg1)
         throws CallbackException {
      // TODO Auto-generated method stub
      
   }
   @Override
   public void onCollectionUpdate(Object arg0, Serializable arg1)
         throws CallbackException {
      // TODO Auto-generated method stub
      
   }
   @Override
   public String onPrepareStatement(String arg0) {
      // TODO Auto-generated method stub
      return null;
   }
}



and this is my InsertArticleServlet, where i persist my article and enable my interceptor:
Code:
public class InsertArticleServlet extends HttpServlet {
   
   /**
    *
    */
   private static final long serialVersionUID = -5874664259279264333L;

   /**
    * Constructor of the object.
    */
   public InsertArticleServlet() {
      super();
   }
   
   public void service(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {      
      HttpSession session = request.getSession(false);
      User user = (User) session.getAttribute("user");      
      
      RequestDispatcher rd;   
      
      // Enable interceptor
      AuditLogInterceptor interceptor = new AuditLogInterceptor();
      HibernateUtil.registerInterceptor(interceptor);
      interceptor.setSession(HibernateUtil.getSession());
      interceptor.setUserId(user.getId());
      
      String id = request.getParameter("id");   
      
      // DAO Pattern
      ArticleDAO articleDao = new ArticleDAO();
      
      Article article;
      
      if((id != null) && (id.length() > 0)) {            
         article = articleDao.getArticleByUserAndId(user, Integer.parseInt(id));
         ParameterProcessor processor = new ArticleParameterProcessor(request, article);
         article = (Article) processor.process(Uploader.upload(request));
      } else {
         ParameterProcessor processor = new ArticleParameterProcessor(request, new Article());
         article = (Article) processor.process(Uploader.upload(request));
      }   
      
      if(article != null) {         
         article.setUser(user);
         articleDao.makePersistent(article);
         
         rd = request.getRequestDispatcher("/admin/list.jsp");
      } else {
         rd = request.getRequestDispatcher("/error.jsp");
      }
      
      HibernateUtil.getSession().flush();
      
      HibernateUtil.commitTransaction();
      HibernateUtil.closeSession();

      // Deregister interceptor
      HibernateUtil.registerInterceptor(null);
      
      rd.forward(request, response);
      
   }

}



If that helps, i am also using a session request filter:
Code:
public class HibernateSessionRequestFilter implements Filter {

    private SessionFactory sf;

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {

        try {
           sf.getCurrentSession().beginTransaction();

            // Call the next filter (continue request processing)
            chain.doFilter(request, response);

            // Commit and cleanup
            sf.getCurrentSession().getTransaction().commit();

        } catch (StaleObjectStateException staleEx) {
            throw staleEx;
        } catch (Throwable ex) {
            // Rollback only
            ex.printStackTrace();
            try {
                if (sf.getCurrentSession().getTransaction().isActive()) {
                    sf.getCurrentSession().getTransaction().rollback();
                }
            } catch (Throwable rbEx) {
               rbEx.printStackTrace();
            }

            // Let others handle it... maybe another interceptor for exceptions?
            throw new ServletException(ex);
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
       sf = HibernateUtil.getSessionFactory();
    }

    public void destroy() {}

}



Any idea of why this is not working? do i have to do something else?

Thanks a lot in advance


Top
 Profile  
 
 Post subject:
PostPosted: Sat Apr 04, 2009 6:27 am 
Beginner
Beginner

Joined: Mon May 26, 2008 3:34 am
Posts: 31
Any help here? i tend to think that there is something wrong with the session used in my InsertArticleServlet:
Code:
// Enable interceptor
      AuditLogInterceptor interceptor = new AuditLogInterceptor();
      HibernateUtil.registerInterceptor(interceptor);
      interceptor.setSession(HibernateUtil.getSession());
      interceptor.setUserId(user.getId());


I am still stuck at this, any idea?

Thanks in advance


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 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.