/** 
 * 
 * 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 javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * A helper base class which makes writing message listeners easier without
 * having to worry about handling the JMSException on the onMessage() method.
 * By default the JMS ExceptionListener will be used to handle any JMS exceptions
 * or if none is configured then a runtime exception will be generated.
 *
 * @author James Strachan
 * @version $Revision: 1.1.1.1 $
 */
public abstract class MessageListenerSupport implements MessageListener {
    private ExceptionListener exceptionListener;

    public void onMessage(Message message) {
        try {
            processMessage(message);
        }
        catch (JMSException e) {
            onJMSException(e, message);
        }
        catch (Exception e) {
            // lets wrap the exception
            JMSException jmsEx = JMSExceptionHelper.newJMSException(e.getMessage(), e);
            onJMSException(jmsEx, message);
        }
    }

    public ExceptionListener getExceptionListener() {
        return exceptionListener;
    }

    public void setExceptionListener(ExceptionListener exceptionListener) {
        this.exceptionListener = exceptionListener;
    }

    /**
     * This method processes the incoming message possibly throwing a JMSException
     * if the message could not be processed correctly.
     *
     * @param messsage
     * @throws Exception
     */
    protected abstract void processMessage(Message messsage) throws Exception;

    /**
     * Process the JMS exception either by calling an exception listener
     * which can contian custom logic or by throwing a runtime exception
     *
     * @param e
     * @param message
     */
    protected void onJMSException(JMSException e, Message message) {
        if (exceptionListener != null) {
            exceptionListener.onException(e);
        }
        else {
            throw new RuntimeException("Failed to process message: " + message + " Reason: " + e, e);
        }
    }

}