/*
 *  ====================================================================
 *
 *  The Apache Software License, Version 1.1
 *
 *  Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 *  reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in
 *  the documentation and/or other materials provided with the
 *  distribution.
 *
 *  3. The end-user documentation included with the redistribution, if
 *  any, must include the following acknowlegement:
 *  "This product includes software developed by the
 *  Apache Software Foundation (http://www.apache.org/)."
 *  Alternately, this acknowlegement may appear in the software itself,
 *  if and wherever such third-party acknowlegements normally appear.
 *
 *  4. The names "The Jakarta Project", "Struts", and "Apache Software
 *  Foundation" must not be used to endorse or promote products derived
 *  from this software without prior written permission. For written
 *  permission, please contact apache@apache.org.
 *
 *  5. Products derived from this software may not be called "Apache"
 *  nor may "Apache" appear in their names without prior written
 *  permission of the Apache Group.
 *
 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 *  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 *  SUCH DAMAGE.
 *  ====================================================================
 *
 *  This software consists of voluntary contributions made by many
 *  individuals on behalf of the Apache Software Foundation.  For more
 *  information on the Apache Software Foundation, please see
 *  <http://www.apache.org/>.
 *
 */
package org.apache.struts.actions;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Locale;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

/**
 * An abstract <strong>Action</strong> that looks up the key for a given
 * message, and passes that key to an alternate perform.
 * This is useful when there are multiple submit buttons on a form with
 * localized labels.
 * This Action can look up the key for the button's label, and then pass
 * that key down to the subclass.
 * The subclass must override the getKeys method to provide the keys
 * used by the controls in its application
 * The subclass must also override the perform(...,key) method to
 * provide the usual perform functionality.
 * The buttons on the HTML form must use the same property name.
 * To tell LookupAction which property name is being used, specify the
 * property name as the parameter property in the ActionMapping, as such:
 * <p>
 *   &lt;action path="/test"
 *           type="org.example.MyAction"
 *           name="MyForm"
 *          scope="request"
 *          input="/test.jsp"
 *      parameter="action"/&gt;
 * </pre>
 * <p>
 *  And your JSP would have the following format for submit buttons:</p> <pre>
 *   &lt;html:form action="/test"&gt;
 *    &lt;html:submit property="action"&gt;
 *      &lt;bean:message key="button.add"/&gt;
 *    &lt;/html:submit&gt;
 *    &lt;html:submit property="action"&gt;
 *      &lt;bean:message key="button.delete"/&gt;
 *    &lt;/html:submit&gt;
 *  &lt;/html:form&gt;
 *  </pre>
 *  <p>
 *  Your subclass must implement both getKeys and perform. An example of such
 *  implementations are:</p> <pre>
 *  protected String[] getKeys(ActionMapping mapping,
 *          ActionForm form
 *          HttpServletRequest request) {
 *      return new String[] {"button.add", "button.delete" };
 *  }
 *
 *  protected ActionForward perform(String key,
 *          ActionMapping mapping,
 *          ActionForm form,
 *          HttpServletRequest request,
 *          HttpServletResponse response)
 *          throws IOException, ServletException {
 *      // do something based on the value of 'key'
 *      return mapping.findForward("success");
 *  }
 * </pre> <p>
 *
 *  The <code>perform</code> method would receive either "button.add",
 *  "button.delete", or <code>null</code> as the <code>key</code> parameter.</p>
 *  <p>
 *
 *  <strong>Notes</strong> - If duplicate values exist for the keys returned by
 *  getKeys, the last one found will be used. If no corresponding key
 *  is found then <code>null</code> is returned.</p>
 *  It is recommended that null=false be set in the web.xml in case a needed
 *  error message is not provided for one of the supported locales. This will
 *  at least present a placeholder message instead of a blank message.
 *
 *@author     Erik Hatcher
 *@author     Ted Husted
 *@created    November 24, 2001
 */

public abstract class LookupAction extends Action {

    /**
     * The message resources for this package.
     */
    protected static MessageResources messages =
     MessageResources.getMessageResources
    ("org.apache.struts.actions.LocalStrings");


// -------------------------------------------------------- Public Methods


    /**
     * Return the locale for the given request. If no session is set,
     * or if the session has no locale set, the default locale
     * is returned.
     * @author  François Rey (FREY - francois.rey@capco.com)
     * @author  Eric Bariaux (EBRX - eric.bariaux@capco.com)
     */
    protected Locale getLocale(HttpServletRequest request) {
        Locale result = null;
        HttpSession session = request.getSession();
        if (session!=null) {
            result = (Locale) session.getAttribute(Action.LOCALE_KEY);
            if (result == null) result = Locale.getDefault();
        } else {
            result = Locale.getDefault();
        }
        return result;
    }


    /**
     * The set of message keys that a control on the HTML form might use.
     * The messages for these keys are retrieved and mapped back to the
     * original key.
     * @param  mapping  ActionMapping for this action
     * @param  form     ActionForm associated with this action (if any)
     * @param  request  The HTTP request we are processing
     * @return          Set of ApplicationResources keys
     */
    protected abstract String[] getKeys(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request);

    // return new String[] {"button.add", "button.delete" };


    /**
     * Provide usual perform functionality here, using "key"
     * as the indication of what activty user requested on
     * the HTML form.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @param form The optional ActionForm bean
     * @return ActionForward or null on normal operation, or Bad Request
     * error if parameters are missing.
     * @exception IOException       if an input/output error occurs
     * @exception ServletException  if a servlet exception occurs.
     */
    protected abstract ActionForward perform(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response,
            String key)
             throws IOException, ServletException;


    /**
     * Retrieves the message key for a given parameter in the
     * request, and passes that key to perform(...,key) for
     * handling.
     * The result of perform(...,key) is returned.
     * Requires that getKeys() and perform(...,key) be made
     * concrete by subclass.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @param form The optional ActionForm bean
     * @return ActionForward or null on normal operation, or Bad Request
     * error if parameters are missing.
     * @exception IOException       if an input/output error occurs
     * @exception ServletException  if a servlet exception occurs.
     */
    public ActionForward perform(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
             throws IOException, ServletException {

        Locale locale = getLocale(request);

        // Error message bucket
        String message = null;

        // Obtain parameter property to specify the request parameter
        String parameter = mapping.getParameter();
        if (parameter == null) {
            message = messages.getMessage(locale,"dispatch.handler",
                mapping.getPath());
        }

        // Obtain text to match based on parameter property
        String name = request.getParameter(parameter);
        if ((message==null) && (name == null)) {
            message = messages.getMessage(locale,"dispatch.parameter",
                mapping.getPath(), parameter);
        }

        // Retrieve the key lookup map
        String[] keys = getKeys(mapping, form, request);
        if ((message==null) && (keys==null))  {
            message = messages.getMessage(locale,"dispatch.keys",
               mapping.getPath());
        }

        // Process the key lookup map
        String key = null;
        if (message==null) {

            // Build the key lookup map; if duplicates, last key wins
            MessageResources resources = servlet.getResources();
            Map lookupMap = new HashMap();
            for (int i = 0; i < keys.length; i++) {
                String text = resources.getMessage(locale,keys[i]);
                lookupMap.put(text, keys[i]);
            }

            // Lookup the key for the label in user's locale
            key = (String) lookupMap.get(name);
            if (key==null) {
               message = messages.getMessage(locale,"dispatch.key",
                mapping.getPath());
            }
        }

        // Fail if required settings are missing
        if (message!=null) {
            servlet.log(message);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                               message);
            return (null);
        }

        // Call subclass perform to handle rest
        return (perform(mapping, form, request, response, key));

    }
}


