mercredi 7 octobre 2009

Struts2 interceptor to remove empty parameters

Everything is in the title (or maybe I should say in the code). This simple interceptor removes empty parameters from the request so that, in the actions, the objects and objects properties will be kept at null in case of empty parameters. Put this interceptor before the "params" provided one.

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

/**
 */
public class RemoveEmptyParametersInterceptor implements Interceptor {

    /**
     */
    public RemoveEmptyParametersInterceptor() {
        super();
    }

    /**
     * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
     */
    public void destroy() {
        // Nothing to do.
    }

    /**
     * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
     */
    public void init() {
        // Nothing to do.
    }

    /**
     * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
     */
    public String intercept(final ActionInvocation invocation) throws Exception {
        final String result;

        final ActionContext actionContext = invocation.getInvocationContext();
        final Map parameters = actionContext.getParameters();

        if (parameters == null) {
            // Nothing to do.
        } else {
            final Collection parametersToRemove =
                new ArrayList();

            for (final Map.Entry entry : parameters.entrySet()) {
                final Object object = entry.getValue();
                if (object instanceof String) {
                    final String value = (String) object;

                    if (StringUtils.isEmpty(value)) {
                        parametersToRemove.add(entry.getKey());
                    }
                } else if (object instanceof String[]) {
                    final String[] values = (String[]) object;

                    final Object[] objects =
                        ArrayUtils.removeElement(values, "");

                    if (objects.length == 0) {
                        parametersToRemove.add(entry.getKey());
                    }
                } else {
                    throw new IllegalArgumentException();
                }
            }

            for (final String parameterToRemove : parametersToRemove) {
                parameters.remove(parameterToRemove);
            }
        }

        result = invocation.invoke();

        return result;
    }
}

Aucun commentaire: