/*
 * $Id: RequestUtils.java 560654 2007-07-29 01:54:02Z niallp $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.struts.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.SuppressPropertiesBeanIntrospector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.chain.contexts.ServletActionContext;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
import org.apache.struts.upload.MultipartRequestWrapper;

/**
 * <p>General purpose utility methods related to processing a servlet request
 * in the Struts controller framework.</p>
 *
 * @version $Rev: 560654 $ $Date: 2007-07-28 20:54:02 -0500 (Sat, 28 Jul 2007) $
 */
public final class RequestUtils {

    // ------------------------------------------------------- Static Variables

    /**
     * <p>Commons Logging instance.</p>
     */
    private static final Log LOG = LogFactory.getLog(RequestUtils.class);

    /**
     * Constructor
     */
    private RequestUtils() {
        throw new AssertionError();
    }

    // --------------------------------------------------------- Public Methods

    /**
     * <p>Create and return an absolute URL for the specified context-relative
     * path, based on the server and context information in the specified
     * request.</p>
     *
     * @param request The servlet request we are processing
     * @param path    The context-relative path (must start with '/')
     * @return absolute URL based on context-relative path
     */
    public static URL absoluteURL(final HttpServletRequest request, final String path) {
        try {
            return new URL(serverURL(request), request.getContextPath() + path);
        } catch (final MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>Create (if necessary) and return an <code>ActionForm</code> instance
     * appropriate for this request.  If no <code>ActionForm</code> instance
     * is required, return <code>null</code>.</p>
     *
     * @param request      The servlet request we are processing
     * @param mapping      The action mapping for this request
     * @param moduleConfig The configuration for this module
     * @param servlet      The action servlet
     * @return ActionForm instance associated with this request
     */
    public static ActionForm createActionForm(final HttpServletRequest request,
            final ActionConfig mapping, final ModuleConfig moduleConfig,
            final ActionServlet servlet) {

        // Is there a form bean associated with this mapping?
        String attribute = mapping.getAttribute();
        if (attribute == null) {
            return null;
        }

        // Look up the form bean configuration information to use
        String name = mapping.getName();
        FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
        if (config == null) {
            LOG.warn("No FormBeanConfig found under '" + name + "'");
            return null;
        }

        ActionForm instance =
            lookupActionForm(request, attribute, mapping.getScope());

        // Can we recycle the existing form bean instance (if there is one)?
        if ((instance != null) && config.canReuse(instance)) {
            return instance;
        }

        return createActionForm(config, servlet);
    }

    private static ActionForm lookupActionForm(final HttpServletRequest request,
            final String attribute, final String scope) {
        // Look up any existing form bean instance
        if (LOG.isDebugEnabled()) {
            LOG.debug(" Looking for ActionForm bean instance in scope '"
                + scope + "' under attribute key '" + attribute + "'");
        }

        ActionForm instance = null;
        if ("request".equals(scope)) {
            instance = (ActionForm) request.getAttribute(attribute);
        } else {
            HttpSession session = request.getSession(false);
            if (session != null) {
                instance = (ActionForm) session.getAttribute(attribute);
            }
        }

        return instance;
    }

    /**
     * <p>Create and return an <code>ActionForm</code> instance appropriate to
     * the information in <code>config</code>.</p>
     *
     * <p>Does not perform any checks to see if an existing ActionForm exists
     * which could be reused.</p>
     *
     * @param config  The configuration for the Form bean which is to be
     *                created.
     * @param servlet The action servlet
     * @return ActionForm instance associated with this request
     */
    public static ActionForm createActionForm(final FormBeanConfig config,
            final ActionServlet servlet) {
        ActionForm instance = null;
        if (config != null) {
            // Create and return a new form bean instance
            instance = config.createActionForm();
            if (LOG.isDebugEnabled()) {
                LOG.debug(" Creating new ActionForm instance of type '"
                        + config.getType() + "'");
                LOG.trace(" --> " + instance);
            }
        }
        return instance;
    }

    /**
     * <p>Retrieves the servlet mapping pattern for the specified {@link ActionServlet}.</p>
     * @param servlet ActionServlet
     * @return the servlet mapping
     * @see Globals#SERVLET_KEY
     * @since Struts 1.3.6
     */
    public static String getServletMapping(final ActionServlet servlet) {
        ServletContext servletContext = servlet.getServletConfig().getServletContext();
        return (String)servletContext.getAttribute(Globals.SERVLET_KEY);
    }

    /**
     * <p>Look up and return current user locale, based on the specified
     * parameters.</p>
     *
     * @param request The request used to lookup the Locale
     * @param locale  Name of the session attribute for our user's Locale.  If
     *                this is <code>null</code>, the default locale key is
     *                used for the lookup.
     * @return current user locale
     * @since Struts 1.2
     */
    public static Locale getUserLocale(final HttpServletRequest request, final String locale) {
        String lcl = locale;
        if (lcl == null) {
            lcl = Globals.LOCALE_KEY;
        }

        // Only check session if sessions are enabled
        Locale userLocale = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            userLocale = (Locale) session.getAttribute(lcl);
        }

        if (userLocale == null) {
            // Returns Locale based on Accept-Language header or the server default
            userLocale = request.getLocale();
        }

        return userLocale;
    }

    /**
     * <p>Populate the properties of the specified JavaBean from the specified
     * HTTP request, based on matching each parameter name against the
     * corresponding JavaBeans "property setter" methods in the bean's class.
     * Suitable conversion is done for argument types as described under
     * <code>convert()</code>.</p>
     *
     * @param bean    The JavaBean whose properties are to be set
     * @param sac     ServletActionContext
     */
    public static void populate(final Object bean, final ServletActionContext sac) {
        populate(bean, null, null, sac);
    }

    /**
     * <p>Populate the properties of the specified JavaBean from the specified
     * HTTP request, based on matching each parameter name (plus an optional
     * prefix and/or suffix) against the corresponding JavaBeans "property
     * setter" methods in the bean's class. Suitable conversion is done for
     * argument types as described under <code>setProperties</code>.</p>
     *
     * <p>If you specify a non-null <code>prefix</code> and a non-null
     * <code>suffix</code>, the parameter name must match
     * <strong>both</strong> conditions for its value(s) to be used in
     * populating bean properties. If the request's content type is
     * "multipart/form-data" and the method is "POST", the
     * <code>HttpServletRequest</code> object will be wrapped in a
     * <code>MultipartRequestWrapper</code> object.</p>
     *
     * @param bean    The JavaBean whose properties are to be set
     * @param prefix  The prefix (if any) to be prepend to bean property names
     *                when looking for matching parameters
     * @param suffix  The suffix (if any) to be appended to bean property
     *                names when looking for matching parameters
     * @param sac     ServletActionContext
     */
    public static void populate(final Object bean, final String prefix, final String suffix,
            final ServletActionContext sac) {

        if (bean instanceof ActionForm) {
            ((ActionForm) bean).setMultipartRequestHandler(null);
        }

        // Iterator of parameter names
        Iterable<String> names = Collections.EMPTY_LIST;

        // Map for multipart parameters
        Map<String, Object> multipartParameters = null;

        // Obtain a MultipartRequestHandler
        MultipartRequestHandler multipartHandler = getMultipartHandler(sac);
        if (multipartHandler != null) {
            multipartParameters = getMultipartParameters(multipartHandler, sac.getRequest());
            if (multipartParameters != null) {
                names = multipartParameters.keySet();
            }
        } else {
            names = Collections.list(sac.getRequest().getParameterNames());
        }

        // Build a list of relevant request parameters from this request
        Map<String, Object> properties = getProperties(bean, prefix, suffix, sac.getRequest(),
                names, multipartParameters);

        // Set the corresponding properties of our bean
        try {
            BeanUtilsBean bub = new BeanUtilsBean();
            bub.getPropertyUtils().addBeanIntrospector(
                SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);
            bub.populate(bean, properties);
        } catch (final ReflectiveOperationException e) {
            throw new RuntimeException(e);
        } finally {
            if (bean instanceof ActionForm) {
                ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
            }
        }
    }

    private static Map<String, Object> getMultipartParameters(
            final MultipartRequestHandler multipartHandler, final HttpServletRequest request) {

        //stop here if the maximum length has been exceeded
        Boolean maxLengthExceeded = (Boolean) request.getAttribute(
                MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);

        if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
            return null;
        }

        //retrieve form values and put into properties
        return getAllParametersForMultipartRequest(request, multipartHandler);
    }

    private static Map<String, Object> getProperties(final Object bean,
            final String prefix, final String suffix, final HttpServletRequest request,
            final Iterable<String> names, final Map<String, Object> multipartParameters) {
        Map<String, Object> properties = new HashMap<>();
        for (final String name : names) {
            String stripped = name;
            if (prefix != null) {
                if (!stripped.startsWith(prefix)) {
                    continue;
                }
                stripped = stripped.substring(prefix.length());
            }

            if (suffix != null) {
                if (!stripped.endsWith(suffix)) {
                    continue;
                }
                stripped = stripped.substring(0, stripped.length() - suffix.length());
            }

            Object parameterValue = null;
            if (multipartParameters != null) {
                parameterValue = multipartParameters.get(name);
                parameterValue = rationalizeMultipleFileProperty(bean, name, parameterValue);
            } else {
                parameterValue = request.getParameterValues(name);
            }

            // Populate parameters, except "standard" struts attributes
            // such as 'org.apache.struts.action.CANCEL'
            if (!(stripped.startsWith("org.apache.struts."))) {
                properties.put(stripped, parameterValue);
            }
        }
        return properties;
    }

    /**
     * <p>If the given form bean can accept multiple FormFile objects
     * but the user only uploaded a single, then
     * the property will not match the form bean type.
     * This method performs some simple checks to try to accommodate
     * that situation.</p>
     * @param bean Object
     * @param name String
     * @param parameterValue Object
     * @return Object
     */
    private static Object rationalizeMultipleFileProperty(final Object bean, final String name,
            final Object parameterValue) {
        if (!(parameterValue instanceof FormFile)) {
            return parameterValue;
        }

        FormFile formFileValue = (FormFile) parameterValue;
        try {
            for (PropertyDescriptor pd
                : Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()) {

                Method mt = pd.getWriteMethod();
                if (mt != null && List.class.isAssignableFrom(mt.getParameterTypes()[0])) {
                    ArrayList<FormFile> list = new ArrayList<>(1);
                    list.add(formFileValue);
                    return list;
                }

                if (mt != null && mt.getParameterTypes()[0].isArray()
                        && mt.getParameterTypes()[0].getComponentType().equals(FormFile.class)) {
                    return new FormFile[] {formFileValue};
                }

            }

        } catch (final IntrospectionException e) {
            throw new RuntimeException(e);
        }

        // no changes
        return parameterValue;
    }

    /**
     * <p>Try to locate a multipart request handler for this request. First,
     * look for a mapping-specific handler stored for us under an attribute.
     * If one is not present, use the global multipart handler, if there is
     * one.</p>
     *
     * @param sac ServletActionContext
     * @return the multipart handler to use, or null if none is found.
     */
    private static MultipartRequestHandler getMultipartHandler(
            final ServletActionContext sac) {

        String contentType = sac.getRequest().getContentType();
        String method = sac.getRequest().getMethod();
        if ((contentType == null)
                || (!contentType.startsWith("multipart/form-data"))
                || (!"POST".equalsIgnoreCase(method))) {
            return null;
        }

        String multipartClass =
            (String) sac.getRequest().getAttribute(Globals.MULTIPART_KEY);
        sac.getRequest().removeAttribute(Globals.MULTIPART_KEY);

        // Try to initialize the mapping specific request handler
        MultipartRequestHandler multipartHandler =
                getMultipartHandlerInstance(multipartClass);

        if (multipartHandler == null) {
            ModuleConfig moduleConfig =
                    ModuleUtils.getInstance().getModuleConfig(sac.getRequest());

            multipartClass = moduleConfig.getControllerConfig().getMultipartClass();

            // Try to initialize the global request handler
            multipartHandler = getMultipartHandlerInstance(multipartClass);
        }

        if (multipartHandler != null) {
            // Set servlet and mapping info
            multipartHandler.setServlet(sac.getActionServlet());
            multipartHandler.setMapping(
                    (ActionMapping) sac.getRequest().getAttribute(Globals.MAPPING_KEY));

            // Initialize multipart request class handler
            multipartHandler.handleRequest(sac.getRequest());
        }

        return multipartHandler;
    }

    private static MultipartRequestHandler getMultipartHandlerInstance(
            final String multipartClass) {
        if (multipartClass != null) {
            try {
                return ResponseUtils.applicationInstance(multipartClass);
            } catch (final ReflectiveOperationException roe) {
                LOG.error(roe.getMessage());
                LOG.error(roe.getClass().getName() + " when instantiating "
                        + "MultipartRequestHandler \"" + multipartClass + "\", "
                        + "defaulting to global multipart class, exception: "
                        + roe.getMessage());
            }
        }
        return null;
    }

    /**
     * <p>Create a <code>Map</code> containing all of the parameters supplied
     * for a multipart request, keyed by parameter name. In addition to text
     * and file elements from the multipart body, query string parameters are
     * included as well.</p>
     *
     * @param request          The (wrapped) HTTP request whose parameters are
     *                         to be added to the map.
     * @param multipartHandler The multipart handler used to parse the
     *                         request.
     * @return the map containing all parameters for this multipart request.
     */
    private static Map<String, Object> getAllParametersForMultipartRequest(
            final HttpServletRequest request, final MultipartRequestHandler multipartHandler) {
        Map<String, Object> parameters = new HashMap<>();
        Map<String, Object> elements = multipartHandler.getAllElements();
        parameters.putAll(elements);

        if (request instanceof MultipartRequestWrapper) {
            HttpServletRequest req =
                (HttpServletRequest) ((MultipartRequestWrapper) request).getRequest();
            parameters.putAll(req.getParameterMap());
        } else {
            LOG.debug("Gathering multipart parameters for unwrapped request");
        }

        return parameters;
    }

    /**
     * <p>Compute the printable representation of a URL, leaving off the
     * scheme/host/port part if no host is specified. This will typically be
     * the case for URLs that were originally created from relative or
     * context-relative URIs.</p>
     *
     * @param url URL to render in a printable representation
     * @return printable representation of a URL
     */
    public static String printableURL(final URL url) {
        if (url.getHost() != null) {
            return url.toString();
        }

        String file = url.getFile();
        String ref = url.getRef();
        if (ref == null) {
            return file;
        }

        StringBuilder sb = new StringBuilder(file);

        sb.append('#');
        sb.append(ref);

        return sb.toString();
    }

    /**
     * <p>Return the context-relative URL that corresponds to the specified
     * {@link ActionConfig}, relative to the module associated with the
     * current modules's {@link ModuleConfig}.</p>
     *
     * @param request The servlet request we are processing
     * @param action  ActionConfig to be evaluated
     * @param pattern URL pattern used to map the controller servlet
     * @return context-relative URL relative to the module
     * @since Struts 1.1
     */
    public static String actionURL(final HttpServletRequest request,
            final ActionConfig action, final String pattern) {
        StringBuilder sb = new StringBuilder();

        if (pattern.endsWith("/*")) {
            sb.append(pattern.substring(0, pattern.length() - 2));
            sb.append(action.getPath());
        } else if (pattern.startsWith("*.")) {
            ModuleConfig appConfig = ModuleUtils.getInstance().getModuleConfig(request);
            sb.append(appConfig.getPrefix());
            sb.append(action.getPath());
            sb.append(pattern.substring(1));
        } else {
            throw new IllegalArgumentException(pattern);
        }

        return sb.toString();
    }

    /**
     * <p>Return the context-relative URL that corresponds to the specified
     * <code>ForwardConfig</code>. The URL is calculated based on the
     * properties of the {@link ForwardConfig} instance as follows:</p>
     *
     * <ul>
     *
     *
     * <li>If the <code>contextRelative</code> property is set, it is assumed
     * that the <code>path</code> property contains a path that is already
     * context-relative:
     *
     * <ul>
     *
     * <li>If the <code>path</code> property value starts with a slash, it is
     * returned unmodified.</li> <li>If the <code>path</code> property value
     * does not start with a slash, a slash is prepended.</li>
     *
     * </ul></li>
     *
     * <li>Acquire the <code>forwardPattern</code> property from the
     * <code>ControllerConfig</code> for the application module used to
     * process this request. If no pattern was configured, default to a
     * pattern of <code>$M$P</code>, which is compatible with the hard-coded
     * mapping behavior in Struts 1.0.</li>
     *
     * <li>Process the acquired <code>forwardPattern</code>, performing the
     * following substitutions:
     *
     * <ul>
     *
     * <li><strong>$M</strong> - Replaced by the module prefix for the
     * application module processing this request.</li>
     *
     * <li><strong>$P</strong> - Replaced by the <code>path</code> property of
     * the specified {@link ForwardConfig}, prepended with a slash if it does
     * not start with one.</li>
     *
     * <li><strong>$$</strong> - Replaced by a single dollar sign
     * character.</li>
     *
     * <li><strong>$x</strong> (where "x" is any charater not listed above) -
     * Silently omit these two characters from the result value.  (This has
     * the side effect of causing all other $+letter combinations to be
     * reserved.)</li>
     *
     * </ul></li>
     *
     * </ul>
     *
     * @param request The servlet request we are processing
     * @param forward ForwardConfig to be evaluated
     * @return context-relative URL
     * @since Struts 1.1
     */
    public static String forwardURL(final HttpServletRequest request, final ForwardConfig forward) {
        return forwardURL(request, forward, null);
    }

    /**
     * <p>Return the context-relative URL that corresponds to the specified
     * <code>ForwardConfig</code>. The URL is calculated based on the
     * properties of the {@link ForwardConfig} instance as follows:</p>
     *
     * <ul>
     *
     * <li>If the <code>contextRelative</code> property is set, it is assumed
     * that the <code>path</code> property contains a path that is already
     * context-relative: <ul>
     *
     * <li>If the <code>path</code> property value starts with a slash, it is
     * returned unmodified.</li> <li>If the <code>path</code> property value
     * does not start with a slash, a slash is prepended.</li>
     *
     * </ul></li>
     *
     * <li>Acquire the <code>forwardPattern</code> property from the
     * <code>ControllerConfig</code> for the application module used to
     * process this request. If no pattern was configured, default to a
     * pattern of <code>$M$P</code>, which is compatible with the hard-coded
     * mapping behavior in Struts 1.0.</li>
     *
     * <li>Process the acquired <code>forwardPattern</code>, performing the
     * following substitutions: <ul> <li><strong>$M</strong> - Replaced by the
     * module prefix for the application module processing this request.</li>
     *
     * <li><strong>$P</strong> - Replaced by the <code>path</code> property of
     * the specified {@link ForwardConfig}, prepended with a slash if it does
     * not start with one.</li>
     *
     * <li><strong>$$</strong> - Replaced by a single dollar sign
     * character.</li>
     *
     * <li><strong>$x</strong> (where "x" is any charater not listed above) -
     * Silently omit these two characters from the result value.  (This has
     * the side effect of causing all other $+letter combinations to be
     * reserved.)</li>
     *
     * </ul></li></ul>
     *
     * @param request      The servlet request we are processing
     * @param forward      ForwardConfig to be evaluated
     * @param moduleConfig Base forward on this module config.
     * @return context-relative URL
     * @since Struts 1.2
     */
    public static String forwardURL(final HttpServletRequest request,
            final ForwardConfig forward, final ModuleConfig moduleConfig) {
        //load the current moduleConfig, if null
        ModuleConfig mc = moduleConfig;
        if (mc == null) {
            mc = ModuleUtils.getInstance().getModuleConfig(request);
        }
        String path = forward.getPath();

        //load default prefix
        String prefix = mc.getPrefix();

        //override prefix if supplied by forward
        if (forward.getModule() != null) {
            prefix = forward.getModule();

            if ("/".equals(prefix)) {
                prefix = "";
            }
        }

        StringBuilder sb = new StringBuilder();

        // Calculate a context relative path for this ForwardConfig
        String forwardPattern =
                mc.getControllerConfig().getForwardPattern();

        if (forwardPattern == null) {
            // Performance optimization for previous default behavior
            sb.append(prefix);

            // smoothly insert a '/' if needed
            if (!path.startsWith("/")) {
                sb.append("/");
            }

            sb.append(path);
        } else {
            boolean dollar = false;

            for (int i = 0; i < forwardPattern.length(); i++) {
                char ch = forwardPattern.charAt(i);

                if (dollar) {
                    switch (ch) {
                        case 'M':
                            sb.append(prefix);
                            break;

                        case 'P':
                            // add '/' if needed
                            if (!path.startsWith("/")) {
                                sb.append("/");
                            }
                            sb.append(path);
                            break;

                        case '$':
                            sb.append('$');
                            break;

                        default:
                            break;
                    }

                    dollar = false;
                    continue;
                } else if (ch == '$') {
                    dollar = true;
                } else {
                    sb.append(ch);
                }
            }
        }

        return sb.toString();
    }

    /**
     * <p>Return the URL representing the current request. This is equivalent
     * to <code>HttpServletRequest.getRequestURL</code> in Servlet 2.3.</p>
     *
     * @param request The servlet request we are processing
     * @return URL representing the current request
     */
    public static URL requestURL(final HttpServletRequest request) {
        StringBuilder url = requestToServerUriStringBuilder(request);
        try {
            return new URL(url.toString());
        } catch (final MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>Return the URL representing the scheme, server, and port number of
     * the current request. Server-relative URLs can be created by simply
     * appending the server-relative path (starting with '/') to this.</p>
     *
     * @param request The servlet request we are processing
     * @return URL representing the scheme, server, and port number of the
     *         current request
     */
    public static URL serverURL(final HttpServletRequest request) {
        StringBuilder url = requestToServerStringBuilder(request);
        try {
            return new URL(url.toString());
        } catch (final MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>Return the string representing the scheme, server, and port number
     * of the current request. Server-relative URLs can be created by simply
     * appending the server-relative path (starting with '/') to this.</p>
     *
     * @param request The servlet request we are processing
     * @return URL representing the scheme, server, and port number of the
     *         current request
     * @since Struts 1.2.0
     */
    public static StringBuilder requestToServerUriStringBuilder(final HttpServletRequest request) {
        StringBuilder serverUri =
            createServerUriStringBuilder(request.getScheme(),
                request.getServerName(), request.getServerPort(),
                request.getRequestURI());

        return serverUri;
    }

    /**
     * <p>Return <code>StringBuilder</code> representing the scheme, server,
     * and port number of the current request. Server-relative URLs can be
     * created by simply appending the server-relative path (starting with
     * '/') to this.</p>
     *
     * @param request The servlet request we are processing
     * @return URL representing the scheme, server, and port number of the
     *         current request
     * @since Struts 1.2.0
     */
    public static StringBuilder requestToServerStringBuilder(final HttpServletRequest request) {
        return createServerStringBuilder(request.getScheme(),
            request.getServerName(), request.getServerPort());
    }

    /**
     * <p>Return <code>StringBuilder</code> representing the scheme, server,
     * and port number of the current request.</p>
     *
     * @param scheme The scheme name to use
     * @param server The server name to use
     * @param port   The port value to use
     * @return StringBuilder in the form scheme: server: port
     * @since Struts 1.2.0
     */
    public static StringBuilder createServerStringBuilder(final String scheme,
            final String server, final int port) {
        StringBuilder url = new StringBuilder();
        int p = port;
        if (p < 0) {
            // Work around java.net.URL bug
            p = 80;
        }

        url.append(scheme);
        url.append("://");
        url.append(server);

        if (("http".equals(scheme) && (p != 80))
            || ("https".equals(scheme) && (p != 443))) {
            url.append(':');
            url.append(p);
        }

        return url;
    }

    /**
     * <p>Return <code>StringBuilder</code> representing the scheme, server,
     * and port number of the current request.</p>
     *
     * @param scheme The scheme name to use
     * @param server The server name to use
     * @param port   The port value to use
     * @param uri    The uri value to use
     * @return StringBuilder in the form scheme: server: port
     * @since Struts 1.2.0
     */
    public static StringBuilder createServerUriStringBuilder(final String scheme,
            final String server, final int port, final String uri) {
        StringBuilder serverUri = createServerStringBuilder(scheme, server, port);

        serverUri.append(uri);

        return serverUri;
    }

    /**
     * <p>Returns the true path of the destination action if the specified forward
     * is an action-aliased URL. This method version forms the URL based on
     * the current request; selecting the current module if the forward does not
     * explicitly contain a module path.</p>
     *
     * @param forward the forward config
     * @param request the current request
     * @param servlet the servlet handling the current request
     * @return the context-relative URL of the action if the forward has an action identifier;
     * otherwise <code>null</code>.
     * @since Struts 1.3.6
     */
    public static String actionIdURL(final ForwardConfig forward, final HttpServletRequest request,
            final ActionServlet servlet) {
        ModuleConfig moduleConfig = null;
        if (forward.getModule() != null) {
            String prefix = forward.getModule();
            moduleConfig = ModuleUtils.getInstance().getModuleConfig(
                    prefix, servlet.getServletContext());
        } else {
            moduleConfig = ModuleUtils.getInstance().getModuleConfig(request);
        }
        return actionIdURL(forward.getPath(), moduleConfig, servlet);
    }

    /**
     * <p>Returns the true path of the destination action if the specified forward
     * is an action-aliased URL. This method version forms the URL based on
     * the specified module.
     *
     * @param originalPath the action-aliased path
     * @param moduleConfig the module config for this request
     * @param servlet the servlet handling the current request
     * @return the context-relative URL of the action if the path has an action identifier;
     * otherwise <code>null</code>.
     * @since Struts 1.3.6
     */
    public static String actionIdURL(final String originalPath,
            final ModuleConfig moduleConfig, final ActionServlet servlet) {
        if (originalPath.startsWith("http") || originalPath.startsWith("/")) {
            return null;
        }

        // Split the forward path into the resource and query string;
        // it is possible a forward (or redirect) has added parameters.
        String actionId = null;
        String qs = null;
        int qpos = originalPath.indexOf('?');
        if (qpos == -1) {
            actionId = originalPath;
        } else {
            actionId = originalPath.substring(0, qpos);
            qs = originalPath.substring(qpos);
        }

        // Find the action of the given actionId
        ActionConfig actionConfig = moduleConfig.findActionConfigId(actionId);
        if (actionConfig == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No actionId found for " + actionId);
            }
            return null;
        }

        String path = actionConfig.getPath();
        String mapping = getServletMapping(servlet);
        StringBuilder actionIdPath = new StringBuilder();

        // Form the path based on the servlet mapping pattern
        if (mapping.startsWith("*")) {
            actionIdPath.append(path);
            actionIdPath.append(mapping.substring(1));
        } else if (mapping.startsWith("/")) {
            // implied ends with a *
            mapping = mapping.substring(0, mapping.length() - 1);
            if (mapping.endsWith("/") && path.startsWith("/")) {
                actionIdPath.append(mapping);
                actionIdPath.append(path.substring(1));
            } else {
                actionIdPath.append(mapping);
                actionIdPath.append(path);
            }
        } else {
            LOG.warn("Unknown servlet mapping pattern");
            actionIdPath.append(path);
        }

        // Lastly add any query parameters (the ? is part of the query string)
        if (qs != null) {
            actionIdPath.append(qs);
        }

        // Return the path
        if (LOG.isDebugEnabled()) {
            LOG.debug(originalPath + " unaliased to " + actionIdPath.toString());
        }
        return actionIdPath.toString();
    }
}
