Here is the source of the HibernateAuditInterceptor
Code:
package com.usp.portal.portlets.usermgmt.models.audit;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Logger;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.Type;
import com.usp.portal.portlets.usermgmt.models.AbstractPersistentObject;
import com.usp.portal.portlets.usermgmt.models.Auditable;
/**
* The HibernateInterceptor is used to create the necessary entries
* for changes on Entities in the Audit Log Table of the database.
* <p>
* A AuditLoggerInterceptor is instanciated per HibernateSession.
* Every object is passed trough this interceptor individually.
* </p>
*/
public class HibernateAuditInterceptor extends EmptyInterceptor {
/**
* The logger to be used for this class.
*/
private static final Logger log = Logger.getLogger(HibernateAuditInterceptor.class);
/**
* A Set containing references to the inserted Entities. Will be used
* to create the Log Entries after flush.
*/
private Set<Auditable> insertedEntities = new HashSet<Auditable>();
/**
* A Set containing references to the updated Entities. Will be used
* to create the Log Entries after flush.
*/
private Set<Auditable> updatedEntities = new HashSet<Auditable>();
/**
* A Set containing references to the deleted Entities. Will be used
* to create the Log Entries after flush.
*/
private Set<Auditable> deletedEntities = new HashSet<Auditable>();
/**
* The session factory to use when doing auditlogging.
*/
private SessionFactory sessionFactory = null;
/**
* This method takes care about auditing for updated records.
*
* @see org.hibernate.Interceptor#onFlushDirty(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
public boolean onFlushDirty(Object entity, Serializable id, Object[] state,
Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
if (entity instanceof Auditable) {
updatedEntities.add((Auditable)entity);
}
return false;
}
/**
* This method takes care about auditing for inserted records.
*
* @see org.hibernate.Interceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) throws CallbackException {
boolean changed = false;
if (entity instanceof Auditable) {
insertedEntities.add((Auditable)entity);
}
Date now = new Date();
if (entity instanceof AbstractPersistentObject) {
String userPid = getUserName();
for (int x=0; x< propertyNames.length; x++) {
if ("createDate".equals(propertyNames[x])
&& state[x] == null) {
state[x] = now;
changed = true;
} else if ("createUser".equals(propertyNames[x])
&& state[x] == null) {
state[x] = userPid;
changed = true;
} else if ("modifyDate".equals(propertyNames[x])) {
state[x] = now;
changed = true;
} else if ("modifyUser".equals(propertyNames[x])) {
state[x] = userPid;
changed = true;
}
}
}
return changed;
}
/**
* This method takes care about auditing for deleted records.
*
* @see org.hibernate.Interceptor#onDelete(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
public void onDelete(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) throws CallbackException {
if (entity instanceof Auditable) {
deletedEntities.add((Auditable)entity);
}
}
/**
* Creates all the Auditlog entries for the inserted, updated and
* deleted entities and stores them on the database.
*
* @see org.hibernate.Interceptor#postFlush(java.util.Iterator)
*/
public void postFlush(Iterator arg0) throws CallbackException {
Session tempSession = null;
try {
if (sessionFactory != null) {
tempSession = sessionFactory.openSession();
}
String userName = getUserName();
// create the log entries for the new records
Iterator it = insertedEntities.iterator();
while (it.hasNext()) {
Auditable auditable = (Auditable)it.next();
AuditLogHelper.insert(auditable, userName, tempSession);
}
insertedEntities.clear();
// create the log entries for the updated records
it = updatedEntities.iterator();
while (it.hasNext()) {
Auditable auditable = (Auditable)it.next();
AuditLogHelper.update(auditable, userName, tempSession);
}
updatedEntities.clear();
// create the log entries for the new records
it = deletedEntities.iterator();
while (it.hasNext()) {
Auditable auditable = (Auditable)it.next();
AuditLogHelper.delete(auditable, userName, tempSession);
}
deletedEntities.clear();
if (tempSession != null) {
tempSession.flush();
}
} catch(Exception ex) {
log.error("Error while postFlusing", ex);
} finally {
if (tempSession != null) {
tempSession.close();
}
}
}
/**
* @return Returns the userPID.
*/
public String getUserName() {
String retVal = null;
// get the user from the Operating system:
String osUser = System.getProperty("user.name");
if (osUser != null && osUser.length() > 0) {
retVal= osUser;
}
return retVal;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
}