Apache Cayenne > Index > Cayenne Examples > WebWork Interceptor

WebWork's interceptor system provdies an excellent way to interject Cayenne into the framework. This interceptor automatically registers a DataContext with session if it does not currently exist, and binds it to the thread. Additionally, it automatically commits any changes at the end of the transaction and catches errors for centralized handling.

The auto-commit represents a point for several actions - you can modify this to simply detect uncommitted objects and log a warning to the developer, you can let your application rely on this to do all commits (as suggested in this example), or simply remove the entire around method and handle commit/rollback explicitly in your application.

CayenneInterceptor.java
package org.cadencetools.webwork;

import org.apache.log4j.Logger;
import org.objectstyle.cayenne.CayenneRuntimeException;
import org.objectstyle.cayenne.access.DataContext;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.AroundInterceptor;

public class CayenneInterceptor extends AroundInterceptor {

    private static Logger LOGGER = Logger.getLogger(CayenneInterceptor.class);
    
    private static String SESSION_CAYENNE = "cayenneThreadContext";
    
    protected void after(ActionInvocation arg0, String arg1) throws Exception {
        
        DataContext dataContext = (DataContext) 
                ServletActionContext.getRequest().getSession().getAttribute(
                CayenneInterceptor.SESSION_CAYENNE);

        // Auto-commit
        if (dataContext != null && dataContext.hasChanges()) {
            
            try {
                dataContext.commitChanges();
            } catch (CayenneRuntimeException commitException) {
                LOGGER.error(commitException.getMessage(), commitException);
                
                try {
                    dataContext.rollbackChanges();
                } catch (CayenneRuntimeException rollbackException) {
                    LOGGER.fatal(rollbackException.getMessage(), rollbackException);
                }

                // This should be ACTUALLY handled, after logging
                // and cleaning up.
            }
            
        }
    }

    protected void before(ActionInvocation arg0) throws Exception {
        
        DataContext dataContext = (DataContext) 
                ServletActionContext.getRequest().getSession()
                .getAttribute(CayenneInterceptor.SESSION_CAYENNE);

        if (dataContext == null) {
            dataContext = DataContext.createDataContext();
        }

        ServletActionContext.getRequest().getSession()
                .setAttribute(CayenneInterceptor.SESSION_CAYENNE, dataContext);

        DataContext.bindThreadDataContext(dataContext);
        
    }

}