/*
 * $Header: /home/cvs/struts/xdocs/struts1.2/documentation/ja/src/share/org/apache/struts/actions/DispatchAction.java,v 1.4 2005/01/12 07:13:51 hioki Exp $
 * $Revision: 1.4 $
 * $Date: 2005/01/12 07:13:51 $
 *
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * 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.apache.struts.actions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;

/**
 * <p>対応する ActionMapping の parameter
 * プロパティに設定されたされた名前のリクエストパラメータに対応するパブリックメソッドへ処理を割り振る機能を持つ抽象
 * <strong>Action</strong> です。
 * この Action は、アプリケーションの設計を単純化するために、いくつものの類似したアクションを単一の
 * Action クラスに結合したい場合に有用です。 
 * {@primary An abstract <strong>Action</strong> that dispatches to a public
 * method that is named by the request parameter whose name is specified
 * by the <code>parameter</code> property of the corresponding
 * ActionMapping.  This Action is useful for developers who prefer to
 * combine many similar actions into a single Action class, in order to
 * simplify their application design.}</p>
 *
 * <p>このアクションを使用する場合には、以下のようなエントリを
 * <code>struts-config.xml</code> ファイルに記述します:
 * {@primary To configure the use of this action in your
 * <code>struts-config.xml</code> file, create an entry like this:}</p>
 *
 * <code>
 *   &lt;action path="/saveSubscription"
 *           type="org.apache.struts.actions.DispatchAction"
 *           name="subscriptionForm"
 *          scope="request"
 *          input="/subscription.jsp"
 *      parameter="method"/&gt;
 * </code>
 *
 * <p>このエントリでは "method" という名前のリクエストパラメータの値を該当する"実行"メソッド(通常の
 * Action.execute メソッドと同様の引数と返り値を持つメソッド)を選択するために使用します。
 * 例えば以下のような3つのメソッドを同一のアクション内に持つことができます:
 * {@primary which will use the value of the request parameter named "method"
 * to pick the appropriate "execute" method, which must have the same
 * signature (other than method name) of the standard Action.execute
 * method.  For example, you might have the following three methods in the
 * same action:}</p>
 * <ul>
 * <li>public ActionForward delete(ActionMapping mapping, ActionForm form,
 *     HttpServletRequest request, HttpServletResponse response)
 *     throws Exception</li>
 * <li>public ActionForward insert(ActionMapping mapping, ActionForm form,
 *     HttpServletRequest request, HttpServletResponse response)
 *     throws Exception</li>
 * <li>public ActionForward update(ActionMapping mapping, ActionForm form,
 *     HttpServletRequest request, HttpServletResponse response)
 *     throws Exception</li>
 * </ul>
 * <p>また、以下のような URL でこの中の1つのメソッドを呼び出すことができます。
 * {@primary and call one of the methods with a URL like this:}</p>
 * <code>
 *   http://localhost:8080/myapp/saveSubscription.do?method=update
 * </code>
 *
 * <p><strong>注</strong> -
 * 呼び出されるメソッド以外のこのアクションに設定された属性は共有されます。
 * これはひとつの <code>DispatchAction</code>
 * サブクラスに容易にまとめることのできる処理に関してある種の制約となります。
 * {@primary <strong>NOTE</strong> - All of the other mapping characteristics of
 * this action must be shared by the various handlers.  This places some
 * constraints over what types of handlers may reasonably be packaged into
 * the same <code>DispatchAction</code> subclass.}</p>
 *
 * <p><strong>注</strong> - 
 * 該当するリクエストパラメータの値が空だった場合
 * <code>unspecified</code> という名前のメソッドが呼び出されます。
 * デフォルトの状態では例外が発生します。
 * リクエストがキャンセルされた(<code>html:cancel</code> ボタンが押された)場合には、
 * カスタマイズ用途で準備されている <code>cancelled</code> メソッドが代わりに利用されます。
 * また、<code>getMethodName</code> メソッドをオーバーライドすることによって
 * アクションがデフォルトで選択するハンドラを変更することができます。
 * {@primary <p><strong>NOTE</strong> - If the value of the request parameter is empty,
 * a method named <code>unspecified</code> is called. The default action is
 * to throw an exception. If the request was cancelled (a <code>html:cancel</code>
 * button was pressed), the custom handler <code>cancelled</code> will be used instead.
 * You can also override the <code>getMethodName</code> method to override the action's
 * default handler selection.}</p>
 *
 * @version $Revision: 1.4 $ $Date: 2005/01/12 07:13:51 $
 * @translator 日置 聡
 * @editor
 * @update 2005/01/12
 * @status firstdraft
 * @memo ブロックA
 */
public abstract class DispatchAction extends Action {


    // ----------------------------------------------------- Instance Variables


    /**
     * この DispatchAction クラスの Class インスタンス。
     * {@primary The Class instance of this <code>DispatchAction</code> class.}
     */
    protected Class clazz = this.getClass();


    /**
     * Commons Logging インスタンス。
     * {@primary Commons Logging instance.}
     */
    protected static Log log = LogFactory.getLog(DispatchAction.class);


    /**
     * このパッケージのメッセージリソース。
     * {@primary The message resources for this package.}
     */
    protected static MessageResources messages =
            MessageResources.getMessageResources
            ("org.apache.struts.actions.LocalStrings");


    /**
     * メソッド名をキーとした、このクラス自身の処理を呼ぶための Method オブジェクトのセット。
     * このコレクションは異なるメソッドが呼ばれる際に生成されるため、Method
     * オブジェクトの生成はメソッド名毎に1度だけ行われます。
     * {@primary The set of Method objects we have introspected for this class,
     * keyed by method name.  This collection is populated as different
     * methods are called, so that introspection needs to occur only
     * once per method name.}
     */
    protected HashMap methods = new HashMap();


    /**
     * リフレクションにてメソッドを検索する際に使用される引数の型のセット。
     * このメンバがメソッドの検索の際には常に使用されるため、引数の型の処理は1回ですみます。
     * {@primary The set of argument type classes for the reflected method call.  These
     * are the same for all calls, so calculate them only once.}
     */
    protected Class[] types =
            {
                ActionMapping.class,
                ActionForm.class,
                HttpServletRequest.class,
                HttpServletResponse.class};



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


    /**
     * 指定されたHTTP リクエストを処理し、対応する HTTP
     * レスポンスを返します(または HTTP レスポンスを生成する他の Web
     * コンポーネントに対して転送を行います)。
     * 処理をどこにどうやって転送すべきかが記述された
     * <code>ActionForward</code> インスタンスまたは、レスポンスが既に完了している場合には
     * <code>null</code> を返します。 
     * {@primary Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.}
     *
     * @param mapping このインスタンスを選択する際に使用された ActionMapping
     * {@primary The ActionMapping used to select this instance}
     * @param form このリクエストに対応する ActionForm(もしあれば)
     * {@primary The optional ActionForm bean for this request (if any)}
     * @param request 処理中のHTTPリクエスト
     * {@primary The HTTP request we are processing}
     * @param response 生成中のHTTPレスポンス
     * {@primary The HTTP response we are creating}
     *
     * @exception Exception 例外が発生した場合
     * {@primary if an exception occurs}
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
            throws Exception {
        if (isCancelled(request)) {
            ActionForward af = cancelled(mapping, form, request, response);
            if (af != null) {
                return af;
            }
        }
        // Identify the request parameter containing the method name
        String parameter = mapping.getParameter();
        if (parameter == null) {
            String message =
                    messages.getMessage("dispatch.handler", mapping.getPath());

            log.error(message);

            throw new ServletException(message);
        }

        // Get the method's name. This could be overridden in subclasses.
        String name = getMethodName(mapping, form, request, response, parameter);


	// Prevent recursive calls
	if ("execute".equals(name) || "perform".equals(name)){
		String message =
			messages.getMessage("dispatch.recursive", mapping.getPath());

		log.error(message);
		throw new ServletException(message);
	}


        // Invoke the named method, and return the result
        return dispatchMethod(mapping, form, request, response, name);

    }



    
    /**
     * 指定されたリクエストパラメータの値が設定されていなかった場合に選択されるメソッドです。
     * <code>DispatchAction</code> のサブクラスで ServletException 
     * を投げる以外の振る舞いをさせたい場合にはこのメソッドをオーバライドしてください。
     * {@primary Method which is dispatched to when there is no value for specified
     * request parameter included in the request.  Subclasses of
     * <code>DispatchAction</code> should override this method if they wish
     * to provide default behavior different than throwing a ServletException.}
     */
    protected ActionForward unspecified(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        String message =
                messages.getMessage(
                        "dispatch.parameter",
                        mapping.getPath(),
                        mapping.getParameter());

        log.error(message);

        throw new ServletException(message);
    }

    /**
     * キャンセルボタンを押した場合のリクエストの際に選択されるメソッドです。
     * <code>DispatchAction</code> のサブクラスで null 
     * を返す以外の振る舞いをさせたい場合にはこのメソッドをオーバライドしてください。
     * {@primary Method which is dispatched to when the request is a cancel button submit.
     * Subclasses of <code>DispatchAction</code> should override this method if
     * they wish to provide default behavior different than returning null.}
     * @since Struts 1.2.0
     */
    protected ActionForward cancelled(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
            throws Exception {

        return null;
    }

    // ----------------------------------------------------- Protected Methods


    /**
     * 指定されたメソッドに処理を割り振ります。
     * {@primary Dispatch to the specified method.}
     * @since Struts 1.1
     */
    protected ActionForward dispatchMethod(ActionMapping mapping,
                                           ActionForm form,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           String name) throws Exception {

        // Make sure we have a valid method name to call.
        // This may be null if the user hacks the query string.
        if (name == null) {
            return this.unspecified(mapping, form, request, response);
        }

        // Identify the method object to be dispatched to
        Method method = null;
        try {
            method = getMethod(name);

        } catch(NoSuchMethodException e) {
            String message =
                    messages.getMessage("dispatch.method", mapping.getPath(), name);
            log.error(message, e);
            throw e;
        }

        ActionForward forward = null;
        try {
            Object args[] = {mapping, form, request, response};
            forward = (ActionForward) method.invoke(this, args);

        } catch(ClassCastException e) {
            String message =
                    messages.getMessage("dispatch.return", mapping.getPath(), name);
            log.error(message, e);
            throw e;

        } catch(IllegalAccessException e) {
            String message =
                    messages.getMessage("dispatch.error", mapping.getPath(), name);
            log.error(message, e);
            throw e;

        } catch(InvocationTargetException e) {
            // Rethrow the target exception if possible so that the
            // exception handling machinery can deal with it
            Throwable t = e.getTargetException();
            if (t instanceof Exception) {
                throw ((Exception) t);
            } else {
                String message =
                        messages.getMessage("dispatch.error", mapping.getPath(), name);
                log.error(message, e);
                throw new ServletException(t);
            }
        }

        // Return the returned ActionForward instance
        return (forward);
    }


    /**
     * 指定された名前を持つ、<code>execute</code>
     * メソッドと同じ引数、返り値をもつこのクラス内のメソッドを取得します。
     * {@primary Introspect the current class to identify a method of the specified
     * name that accepts the same parameter types as the <code>execute</code>
     * method does.}
     *
     * @param name このクラス内のメソッド名
     * {@primary Name of the method to be introspected}
     *
     * @exception NoSuchMethodException 指定されたメソッドが存在しない場合
     * {@primary if no such method can be found}
     */
    protected Method getMethod(String name)
            throws NoSuchMethodException {

        synchronized(methods) {
            Method method = (Method) methods.get(name);
            if (method == null) {
                method = clazz.getMethod(name, types);
                methods.put(name, method);
            }
            return (method);
        }

    }

    /**
     * 与えられたパラメータを用いて、メソッド名を返します。
     * {@primary Returns the method name, given a parameter's value.}
     *
     * @param mapping このインスタンスを選択する際に使用された ActionMapping
     * {@primary The ActionMapping used to select this instance}
     * @param form このリクエストに対応する ActionForm(もしあれば)
     * {@primary The optional ActionForm bean for this request (if any)}
     * @param request 処理中のHTTPリクエスト
     * {@primary The HTTP request we are processing}
     * @param response 生成中のHTTPレスポンス
     * {@primary The HTTP response we are creating}
     * @param parameter <code>ActionMapping</code> 内のパラメーターの名前
     * {@primary The <code>ActionMapping</code> parameter's name}
     *
     * @return メソッド名
     * {@primary The method's name.}
     * @since Struts 1.2.0
     */
    protected String getMethodName(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   String parameter)
            throws Exception {

        // Identify the method name to be dispatched to.
        // dispatchMethod() will call unspecified() if name is null
        return request.getParameter(parameter);
    }

}
