/*
 * ====================================================================== Parts
 * Copyright 2006 University of Leeds, Oxford University, University of the
 * Highlands and Islands. Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 * ======================================================================
 */

package org.bodington.servlet;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Class which allows extra parameters to be added to the request, this is needed
 * when parsing multipart requests.
 * @author buckett
 */
public class UploadRequestWrapper extends HttpServletRequestWrapper
{

    private Map parameters;

    public UploadRequestWrapper(HttpServletRequest request)
    {
        super(request);
        // Copy in all the existing values (orginal is immutable).
        this.parameters = new HashMap(request.getParameterMap());
    }
    
    void addParameter(String name, String value)
    {
        String[] values = getParameterValues(name);
        String[] newValues;
        if (values == null)
        {
             newValues = new String[]{value};
        }
        else
        {
             newValues = new String[values.length +1];
            System.arraycopy(values, 0, newValues, 0, values.length);
            newValues[newValues.length-1] = value;
        }
        parameters.put(name, newValues);
    }

    public Map getParameterMap()
    {
        return Collections.unmodifiableMap(parameters);
    }

    public String[] getParameterValues(String name)
    {
        return (String[]) parameters.get(name);
    }

    public String getParameter(String name)
    {
        String[] params = getParameterValues(name);
        if (params == null) return null;
        return params[0];
    }

    public Enumeration getParameterNames()
    {
        return Collections.enumeration(parameters.keySet());
    }

}
