開発メモ

開発用のメモです。

インターセプターの処理を後処理・前処理をわかりやすく

package jp.mirageworld.abstractClass;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public abstract class AbstractCrsInterceptor extends AbstractInterceptor {

    /**
    * @serial
    */
    private static final long serialVersionUID = 4095855367924834178L;

    /**
    * {@link Logger}.
    *
    * @return logger.
    */
    public Logger logger() {
        return LogManager.getLogger(getClass());
    }

    @Override
    public void init() {
        logger().info(getClass().getSimpleName());
        // super.init();
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String ret = Action.INPUT;
        try {
            ret = interceptBefore(ret);
            if (StringUtils.equals(ret, Action.SUCCESS)) {
                ret = invocation.invoke();
            }
            if (StringUtils.equals(ret, Action.SUCCESS)) {
                ret = interceptAfter(ret);
            }
        } catch (Exception e) {
            ret = interceptException(ret, e);
        }

        return ret;
    }

    @Override
    public void destroy() {
        super.destroy();
        logger().info(getClass().getSimpleName());
    }

    protected String interceptAfter(String ret) throws Exception {
        return ret;
    }

    /**
    * {@link ActionInvocation#invoke()} before.
    * @param ret
    * @return
    * @exception
    */
    protected String interceptBefore(String ret) throws Exception {
        return ret;
    }

    /**
    * {@link ActionInvocation#invoke()} before.
    * @param ret
    * @return
    * @exception
    */
    protected String interceptException(String ret, Exception e) throws Exception {
        if (logger().isDebugEnabled()) {
            logger().warn(e.getMessage(), e);
        } else {
            logger().warn(e.getMessage());
        }
        return Action.ERROR;
    }

}
Twitter: @asahina_alice