/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.opensymphony.xwork.interceptor;

import ognl.OgnlOps;

import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.util.OgnlValueStack;

import java.util.Iterator;
import java.util.Map;
import java.util.Arrays;


/**
 *
 *
 * @author $Author: jcarreira $
 * @version $Revision: 1.2 $
 */
public class ParametersInterceptor extends AroundInterceptor {
    public static final String[] EMPTY_STRING_ARRAY = new String[]{""};

    //~ Methods ////////////////////////////////////////////////////////////////

    protected void after(ActionInvocation dispatcher, String result) throws Exception {
    }

    protected void before(ActionInvocation invocation) throws Exception {
        final Map parameters = ActionContext.getContext().getParameters();

        if (log.isDebugEnabled()) {
            log.debug("Setting params " + parameters);
        }

        if (parameters != null) {
            final OgnlValueStack stack = ActionContext.getContext().getValueStack();

            for (Iterator iterator = parameters.entrySet().iterator();
                 iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                if ("".equals(entry.getValue()) || (entry.getValue() instanceof String[]
                        && Arrays.equals(EMPTY_STRING_ARRAY, (String[]) entry.getValue()))) {
                    stack.setValue(entry.getKey().toString(), null);
                }
                else {
                    stack.setValue(entry.getKey().toString(), entry.getValue());
                }
            }
        }
    }
}
