package org.apache.commons.lang.exception;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 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 acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Turbine" 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",
 *    "Apache Turbine", nor may "Apache" appear in their name, 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.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.PrintStream;

import junit.framework.*;
import junit.textui.TestRunner;
/**
 * Tests the org.apache.commons.lang.exception.NestableDelegate class.
 *
 * @author <a href="mailto:stevencaswell@yahoo.com">Steven Caswell</a>
 */
public class NestableDelegateTestCase extends junit.framework.TestCase
{
    private static final String CONSTRUCTOR_FAILED_MSG = 
    "The Nestable implementation passed to the NestableDelegate(Nestable) constructor must extend java.lang.Throwable";

    /**
     * Construct a new instance of NestableDelegateTestCase with the specified name
     */
    public NestableDelegateTestCase(String name)
    {
        super(name);
    }

    /**
     * Set up instance variables required by this test case.
     */
    public void setUp()
    {
    }
    
    public static Test suite()
    {
        return new TestSuite(NestableDelegateTestCase.class);
    }
    
    /**
     * Tear down instance variables required by this test case.
     */
    public void tearDown()
    {
    }
    
    /**
     * Test the implementation
     */
    public void testNestableDelegateConstructor()
    {
        String msg = null;
        boolean constructorFailed = false;
        try
        {
            NestableDelegate nonThrowableCause = new NestableDelegate(new NonThrowableNestable());
        }
        catch(IllegalArgumentException iae)
        {
            constructorFailed = true;
            msg = iae.getMessage();
        }
        assertTrue("nestable delegate constructor with non-throwable cause failed == true", constructorFailed);
        assertTrue("constructor failed exception msg == " + CONSTRUCTOR_FAILED_MSG,
            msg.equals(CONSTRUCTOR_FAILED_MSG));

        constructorFailed = false;
        try
        {
            NestableDelegate nd1 = new NestableDelegate(new ThrowableNestable());
        }
        catch(IllegalArgumentException iae)
        {
            constructorFailed = true;
        }
        assertTrue("nestable delegate constructor with throwable cause failed == false", !constructorFailed);
    }

    public void testNestableDelegateGetMessage()
    {
        Nestable ne1 = new ThrowableNestable();
        assertTrue("ThrowableNestable ne1 getMessage() == ThrowableNestable exception",
            ne1.getMessage().equals("ThrowableNestable exception"));
        NestableDelegate nd1 = new NestableDelegate(ne1);
        assertTrue("nd1 getMessage() == " + ne1.getCause().getMessage(),
            nd1.getMessage("base").equals("base: " + ne1.getCause().getMessage()));
        
        Nestable ne2 = new ThrowableNestedNestable(new Exception("nested exception 2"));
        NestableDelegate nd2 = new NestableDelegate(ne2);
        assertTrue("nd2 getMessage() == base: " + ne2.getCause().getMessage(),
            nd2.getMessage("base").equals("base: " + ne2.getCause().getMessage()));
    }

    public void testNestableDelegetePrintStackTrace()
    {
        Nestable ne3 = new ThrowableNestedNestable(new Exception("nested exception 3"));
        NestableDelegate nd3 = new NestableDelegate(ne3);

        ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
        PrintStream ps1 = new PrintStream(baos1);
        nd3.printStackTrace(ps1);
        String stack1 = baos1.toString();
        assertTrue("stack trace startsWith == java.lang.Exception: nested exception 3",
            stack1.startsWith("java.lang.Exception: nested exception 3"));
        int start1 = (stack1.length() - 2) - ("rethrown as ThrowableNestedNestable partial stack trace place-holder").length();
        int end1 = stack1.length() - 2;
        assertTrue("stack trace substring(" + start1 + "," + end1 + ") == rethrown as ThrowableNestedNestable partial stack trace place-holder",
            stack1.substring(start1, end1).equals("rethrown as ThrowableNestedNestable partial stack trace place-holder"));

        ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
        PrintStream ps2 = new PrintStream(baos2);
        System.setErr(ps2);
        nd3.printStackTrace();
        String stack2 = baos2.toString();
        assertTrue("stack trace startsWith == java.lang.Exception: nested exception 3",
            stack2.startsWith("java.lang.Exception: nested exception 3"));
        int start2 = (stack2.length() - 2) - ("rethrown as ThrowableNestedNestable partial stack trace place-holder").length();
        int end2 = stack2.length() - 2;
        assertTrue("stack trace substring(" + start2 + "," + end2 + ") == rethrown as ThrowableNestedNestable partial stack trace place-holder",
            stack2.substring(start2, end2).equals("rethrown as ThrowableNestedNestable partial stack trace place-holder"));
    }
    
    public static void main(String args[])
    {
        TestRunner.run(suite());
    }
}

class ThrowableNestable extends Throwable implements Nestable
{
    
    /**
     * Returns the error message of this and any nested
     * <code>Throwable</code>.
     *
     * @return The error message.
     */
    public String getMessage()
    {
        return "ThrowableNestable exception";
    }
    
    /**
     * Returns the reference to the exception or error that caused the
     * exception implementing the <code>Nestable</code> to be thrown.
     */
    public Throwable getCause()
    {
        return new Exception("ThrowableNestable cause");
    }
    
    /**
     * Prints the stack trace of this exception to the specified print
     * writer.  Includes inforamation from the exception--if
     * any--which caused this exception.
     *
     * @param out <code>PrintWriter</code> to use for output.
     */
    public void printStackTrace(PrintWriter out)
    {
    }
    
    /**
     * Prints the stack trace for this exception only--root cause not
     * included--using the provided writer.  Used by {@link
     * org.apache.commons.lang.exception.NestableDelegate} to write
     * individual stack traces to a buffer.  The implementation of
     * this method should call
     * <code>super.printStackTrace(out);</code> in most cases.
     *
     * @param out The writer to use.
     */
    public void printPartialStackTrace(PrintWriter out)
    {
    }
    
}

class ThrowableNestedNestable extends Throwable implements Nestable
{
    private Throwable cause = null;
    
    public ThrowableNestedNestable(Throwable cause)
    {
        this.cause = cause;
    }
    /**
     * Returns the error message of this and any nested
     * <code>Throwable</code>.
     *
     * @return The error message.
     */
    public String getMessage()
    {
        return "ThrowableNestedNestable exception (" + cause.getMessage() + ")";
    }
    
    /**
     * Returns the reference to the exception or error that caused the
     * exception implementing the <code>Nestable</code> to be thrown.
     */
    public Throwable getCause()
    {
        return cause;
    }
    
    /**
     * Prints the stack trace of this exception to the specified print
     * writer.  Includes inforamation from the exception--if
     * any--which caused this exception.
     *
     * @param out <code>PrintWriter</code> to use for output.
     */
    public void printStackTrace(PrintWriter out)
    {
        out.println("ThrowableNestedNestable stack trace place-holder");
    }
    
    /**
     * Prints the stack trace for this exception only--root cause not
     * included--using the provided writer.  Used by {@link
     * org.apache.commons.lang.exception.NestableDelegate} to write
     * individual stack traces to a buffer.  The implementation of
     * this method should call
     * <code>super.printStackTrace(out);</code> in most cases.
     *
     * @param out The writer to use.
     */
    public void printPartialStackTrace(PrintWriter out)
    {
        out.println("ThrowableNestedNestable partial stack trace place-holder");
    }
    
}

class NonThrowableNestable implements Nestable
{
    /**
     * Returns the error message of this and any nested
     * <code>Throwable</code>.
     *
     * @return The error message.
     */
    public String getMessage()
    {
        return "non-throwable";
    }
    
    /**
     * Returns the reference to the exception or error that caused the
     * exception implementing the <code>Nestable</code> to be thrown.
     */
    public Throwable getCause()
    {
        return null;
    }
    
    /**
     * Prints the stack trace of this exception to the specified print
     * writer.  Includes inforamation from the exception--if
     * any--which caused this exception.
     *
     * @param out <code>PrintWriter</code> to use for output.
     */
    public void printStackTrace(PrintWriter out)
    {
    }
    
    /**
     * Prints the stack trace for this exception only--root cause not
     * included--using the provided writer.  Used by {@link
     * org.apache.commons.lang.exception.NestableDelegate} to write
     * individual stack traces to a buffer.  The implementation of
     * this method should call
     * <code>super.printStackTrace(out);</code> in most cases.
     *
     * @param out The writer to use.
     */
    public void printPartialStackTrace(PrintWriter out)
    {
    }
    
}