/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * 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.activemq.util;

import org.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;

/**
 * A helper class for ensuring that a number of tasks occur, whether they
 * throw exceptions or not and saving the first exception so that we can
 * throw it properly.
 * This class is particularly useful for shutting things down, where we
 * want to try close all resources, whether they fail or not.
 *
 * @version $Revision: 1.1.1.1 $
 */
public class ExceptionTemplate {
    private Throwable firstException;

    public ExceptionTemplate() {
    }

    public void run(Callback task) {
        try {
            task.execute();
        }
        catch (Throwable t) {
            if (firstException == null) {
                firstException = t;
            }
        }
    }

    /**
     * Returns the first exception thrown during the execution of this
     * template or returns null if there has been no exception thrown yet.
     *
     * @return the first caught exception or null if none has occured yet
     */
    public Throwable getFirstException() {
        return firstException;
    }

    /**
     * Throws the first exception caught during the execution of this template
     * as a JMS exception or do nothing if we have not caught and exception
     *
     * @throws JMSException
     */
    public void throwJMSException() throws JMSException {
        if (firstException != null) {
            if (firstException instanceof JMSException) {
                  throw (JMSException) firstException;
            }
            else if (firstException instanceof Exception) {
                throw JMSExceptionHelper.newJMSException(firstException.getMessage(), (Exception) firstException);
            }
            else {
                // lets wrap the Throwable in an Exception
                throw JMSExceptionHelper.newJMSException(firstException.getMessage(), new Exception(firstException));
            }
        }
    }
}
