package org.apache.commons.lang.exception;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 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", "Commons", 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 Software Foundation.
 *
 * 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/>.
 */

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a>
 * @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
 * @author <a href="mailto:knielsen@apache.org">Kasper Nielsen</a>
 * @author <a href="mailto:steven@caswell.name">Steven Caswell</a>
 * @author Sean C. Sullivan
 * @translator 日置 聡
 * @status firstdraft
 * @update 2003/08/06
 * @version $Id: NestableDelegate.java,v 1.1.1.1 2004/02/13 10:02:04 hioki Exp $
 */
public class NestableDelegate
	implements java.io.Serializable
{
    /**
     * コンストラクタのエラーメッセージ。
     * {@primary Constructor error message.}
     */
    private transient static final String MUST_BE_THROWABLE =
        "The Nestable implementation passed to the NestableDelegate(Nestable) "
        + "constructor must extend java.lang.Throwable";

    /**
     * ラップしている例外またはエラーへの参照(これは
     * {@link org.apache.commons.lang.exception.Nestable} の実装である必要があります)。
     * {@primary Holds the reference to the exception or error that we're
     * wrapping (which must be a {@link
     * org.apache.commons.lang.exception.Nestable} implementation).}
     */
    private Throwable nestable = null;

    /**
     * 指定された <code>Nestable</code> を管理する <code>NestableDelegate</code>
     * のインスタンスを新たに生成します。
     * {@primary Constructs a new <code>NestableDelegate</code> instance to manage the
     * specified <code>Nestable</code>.}
     *
     * @param nestable the Nestable implementation (<i>must</i> extend
     * {@link java.lang.Throwable})
     */
    NestableDelegate(Nestable nestable) // package
    {
        if (nestable instanceof Throwable)
        {
            this.nestable = (Throwable) nestable;
        }
        else
        {
            throw new IllegalArgumentException(MUST_BE_THROWABLE);
        }
    }

    /**
     * 内部に保持されている <code>Throwable</code> のうち、0 から始まる指定されたインデックスに該当する
     * <code>Throwable</code> のメッセージを返します。 
     * {@primary Returns the error message of the <code>Throwable</code> in the chain
     * of <code>Throwable</code>s at the specified index, numbererd from 0.}
     *
     * @param index 内部に保持されている <code>Throwable</code> のインデックス
     * {@primary the index of the <code>Throwable</code> in the chain of
     * <code>Throwable</code>s}
     * @return エラーメッセージ、インデックスで指定された <code>Throwable</code>
     * にメッセージが設定されていない場合には null
     * {@primary the error message, or null if the <code>Throwable</code> at the
     * specified index in the chain does not contain a message}
     * @throws IndexOutOfBoundsException <code>index</code> の値がマイナスまたは内部の <code>Throwable</code>
     * の数が指定された値よりも少ない場合
     * {@primary if the <code>index</code> argument is
     * negative or not less than the count of <code>Throwable</code>s in the
     * chain}
     */
    String getMessage(int index)
    {
        Throwable t = this.getThrowable(index);
        if(Nestable.class.isInstance(t))
        {
            return ((Nestable) t).getMessage(0);
        }
        else
        {
            return t.getMessage();
        }
    }
    
    /**
     * <code>Nestable</code> とネストされた <code>Throwable</code>
     * に含まれる全てのメッセージを返します。
     * {@primary Returns the full message contained by the <code>Nestable</code>
     * and any nested <code>Throwable</code>s.}
     * @param baseMsg 全てのメッセージを作成する際に使用されるベースメッセージ。
     * 一般的に <code>nestableHelper.getMessage(super.getMessage())</code> を経由して呼ばれます。
     * <code>super</code> は {@link java.lang.Throwable} のインスタンスを意味します。
     *{@primary the base message to use when creating the full
     * message. Should be generally be called via
     * <code>nestableHelper.getMessage(super.getMessage())</code>,
     * where <code>super</code> is an instance of {@link
     * java.lang.Throwable}.}
     * @return この例外とネスとされた全ての <code>Throwable</code>
     * のメッセージを連結したメッセージ
     * {@primary The concatenated message for this and all nested
     * <code>Throwable</code>s}
     */
    String getMessage(String baseMsg) // package
    {
        StringBuffer msg = new StringBuffer();
        if (baseMsg != null)
        {
            msg.append(baseMsg);
        }

        Throwable nestedCause = ExceptionUtils.getCause(this.nestable);
        if (nestedCause != null)
        {
            String causeMsg = nestedCause.getMessage();
            if (causeMsg != null)
            {
                if (baseMsg != null)
                {
                    msg.append(": ");
                }
                msg.append(causeMsg);
            }

        }
        return (msg.length() > 0 ? msg.toString() : null);
    }

    /**
     * この例外と内部にネストされる <code>Throwable</code> のエラーメッセージをStringの配列に格納して返します。
     * メッセージを持たない <code>Throwable</code> のメッセージは null で表現されます。
     * 返される配列の長さは原因の数を示す {@link #getThrowableCount()} の返す値と一致します。
     * {@primary Returns the error message of this and any nested <code>Throwable</code>s
     * in an array of Strings, one element for each message. Any
     * <code>Throwable</code> not containing a message is represented in the
     * array by a null. This has the effect of cause the length of the returned
     * array to be equal to the result of the {@link #getThrowableCount()}
     * operation.}
     *
     * @return エラーメッセージ
     * {@primary the error messages}
     */
    String[] getMessages() // package
    {
        Throwable[] throwables = this.getThrowables();
        String[] msgs = new String[throwables.length];
        for(int i = 0; i < throwables.length; i++)
        {
            msgs[i] = (Nestable.class.isInstance(throwables[i]) ?
                       ((Nestable) throwables[i]).getMessage(0) :
                       throwables[i].getMessage());
        }
        return msgs;
    }

    /**
     * 内部に保持されている <code>Throwable</code> のうち、0 から始まる指定されたインデックスに該当する
     * <code>Throwable</code> を返します。
     * {@primary Returns the <code>Throwable</code> in the chain of
     * <code>Throwable</code>s at the specified index, numbererd from 0.}
     *
     * @param index 内部に保持される <code>Throwable</code> の 0 から始まるインデックス
     * {@primary the index, numbered from 0, of the <code>Throwable</code> in
     * the chain of <code>Throwable</code>s}
     * @return 該当する <code>Throwable</code>
     * {@primary the <code>Throwable</code>}
     * @throws IndexOutOfBoundsException <code>index</code> の値がマイナスまたは内部の <code>Throwable</code>
     * の数が指定された値よりも少ない場合
     * {@primary if the <code>index</code> argument is
     * negative or not less than the count of <code>Throwable</code>s in the
     * chain}
     */
    Throwable getThrowable(int index)
    {
        if(index == 0)
        {
            return this.nestable;
        }
        Throwable[] throwables = this.getThrowables();
        return throwables[index];
    }
    
    /**
     * このクラスに含まれる <code>Nestable</code> の中の
     * <code>Throwable</code> の数を返します。
     * {@primary Returns the number of <code>Throwable</code>s contained in the
     * <code>Nestable</code> contained by this delegate.}
     *
     * @return スロー可能オブジェクト(throwable)の数
     * {@primary the throwable count}
     */
    int getThrowableCount() // package
    {
        return ExceptionUtils.getThrowableCount(this.nestable);
    }
    
    /**
     * このクラス内の <code>Nestable</code> と、内部にネストされた <code>Throwable</code>
     * を <code>Throwable</code> の配列に格納して返します。
     * {@primary Returns this delegate's <code>Nestable</code> and any nested
     * <code>Throwable</code>s in an array of <code>Throwable</code>s, one
     * element for each <code>Throwable</code>.}
     *
     * @return <code>Throwable</code> の配列
     * {@primary the <code>Throwable</code>s}
     */
    Throwable[] getThrowables() // package
    {
        return ExceptionUtils.getThrowables(this.nestable);
    }

    /**
     * このクラスの <code>Nestable</code> の内部にネストされた <code>Throwable</code>
     * から、最初に見つかった指定された型の、検索開始位置より後ろの
     * 0 から始まるインデックスを返します。
     * 該当するものが見つからなかった場合には -1 を返します。
     * {@primary Returns the index, numbered from 0, of the first <code>Throwable</code>
     * that matches the specified type in the chain of <code>Throwable</code>s
     * held in this delegate's <code>Nestable</code> with an index greater than
     * or equal to the specified index, or -1 if the type is not found.}
     *
     * @param type 検索対象となる <code>Class</code>
     * {@primary type <code>Class</code> to be found}
     * @param fromIndex 検索の開始位置となる 0 から始まるインデックス
     * {@primary the index, numbered from 0, of the starting position in
     * the chain to be searched}
     * @return 指定された型が最初に見つかったインデックス、見つからなかった場合には -1
     * {@primary index of the first occurrence of the type in the chain, or -1 if
     * the type is not found}
     * @throws IndexOutOfBoundsException <code>fromIndex</code>の値がマイナスまたは内部の
     * <code>Throwable</code> の数が指定された値よりも少ない場合
     * {@primary if the <code>fromIndex</code> argument
     * is negative or not less than the count of <code>Throwable</code>s in the
     * chain}
     */
    int indexOfThrowable(Class type, int fromIndex) // package
    {
        return ExceptionUtils.indexOfThrowable(this.nestable, type, fromIndex);
    }
    
    /**
     * 標準エラー出力にこの例外のスタックトレースを出力します。
     * {@primary Prints the stack trace of this exception the the standar error
     * stream.} 
     
     */
    public void printStackTrace()
    {
        printStackTrace(System.err);
    }

    /**
     * 指定された stream にこの例外のスタックトレースを出力します。
     * {@primary Prints the stack trace of this exception to the specified
     * stream.}
     *
     * @param out 出力に使用される <code>PrintStream</code>
     * {@primary <code>PrintStream</code> to use for output.}
     * @see #printStackTrace(PrintWriter)
     */
    public void printStackTrace(PrintStream out)
    {
        synchronized (out)
        {
            PrintWriter pw = new PrintWriter(out, false);
            printStackTrace(pw);
            // Flush the PrintWriter before it's GC'ed.
            pw.flush();
        }
    }

    /**
     * 指定された writer にこの例外のスタックトレースを出力します。
     * {@primary Prints the stack trace of this exception to the specified
     * writer.}
     *
     * @param out 出力に使用される <code>PrintWriter</code>
     * {@primary <code>PrintWriter</code> to use for output.}
     */
    public void printStackTrace(PrintWriter out)
    {
        synchronized (out)
        {
            String[] st = getStackFrames(this.nestable);
            Throwable nestedCause = ExceptionUtils.getCause(this.nestable);
            if (nestedCause != null)
            {
                if (nestedCause instanceof Nestable)
                {
                    // Recurse until a non-Nestable is encountered.
                    ((Nestable) nestedCause).printStackTrace(out);
                }
                else
                {
                    String[] nst = getStackFrames(nestedCause);
                    for (int i = 0; i < nst.length; i++)
                    {
                        out.println(nst[i]);
                    }
                }
                out.print("rethrown as ");
            }

            // Output desired frames from stack trace.
            for (int i = 0; i < st.length; i++)
            {
                out.println(st[i]);
            }
        }
    }

    /**
     * 指定された <code>Throwable</code> オブジェクトに関連するスタックトレースを捕まえて
     * スタックフレームのリストに再構成します。
     * {@primary Captures the stack trace associated with the specified
     * <code>Throwable</code> object, decomposing it into a list of
     * stack frames.}
     *
     * @param t 対象となる <code>Throwable</code>
     * {@primary The <code>Throwable</code>.}
     * @return  スタックフレームの内容を表す文字列の配列
     * {@primary An array of strings describing each stack frame.}
     */
    private String[] getStackFrames(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);

        // Avoid infinite loop between decompose() and printStackTrace().
        if (t instanceof Nestable)
        {
            ((Nestable) t).printPartialStackTrace(pw);
        }
        else
        {
            t.printStackTrace(pw);
        }
        return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
    }
}

