All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.discursive.dao.generic.spring.TimestampingInterceptor Maven / Gradle / Ivy

The newest version!
package com.discursive.dao.generic.spring;

import java.util.Date;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.aop.IntroductionInterceptor;

import com.discursive.dao.generic.GenericDao;

public class TimestampingInterceptor implements IntroductionInterceptor {

    private static Logger log = Logger.getLogger( TimestampingInterceptor.class );

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        // TODO: Please tell me what i'm doing wrong, i couldn't call this
        // without getting a ProxyFactoryBean class cast exception
        // FinderExecutor genericDao = (FinderExecutor)
        // factory.getTargetSource().getTarget();

        String methodName = methodInvocation.getMethod().getName();
        Object[] arguments = methodInvocation.getArguments();
        if (methodName.startsWith("makePersistent")) {
            Object object = arguments[0];
            log.debug( "Intercepting call to make persistent for " + object.toString() );
            
            Date now = new Date();
            
            if( PropertyUtils.isReadable( object, "createdAt" ) ) {
                Date createdAtDate = (Date) PropertyUtils.getProperty( object, "createdAt" );
                if( createdAtDate == null ) {
                    log.debug( "Setting the created at timestamp: " + now );
                    PropertyUtils.setProperty(object, "createdAt", now);
                }
            }
            if( PropertyUtils.isWriteable( object, "updatedAt" ) ) {
                log.debug( "Setting the updated at timestamp: " + now );
                PropertyUtils.setProperty(object, "updatedAt", now);                
            }
        }

        return methodInvocation.proceed();
    }

    @SuppressWarnings("unchecked")
	public boolean implementsInterface(Class intf) {
        return intf.isInterface() && GenericDao.class.isAssignableFrom(intf);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy