001/*
002 *  Copyright 2010, 2013, 2014 Chris Pheby
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.jadira.jms.mdp;
017
018import javax.jms.Message;
019import javax.jms.MessageListener;
020
021import org.jadira.jms.exception.FatalJmsException;
022import org.springframework.beans.factory.InitializingBean;
023import org.springframework.jms.core.JmsTemplate;
024
025/**
026 * Provides a base implementation for a Message Driven POJO. The key benefit of extending this class is that a standard error handling pattern is 'baked in'. This class should be configured by setting
027 * the appropriate JmsTemplate for handling Fatal JMS failures.
028 */
029public abstract class AbstractMessageDriven implements MessageListener, InitializingBean {
030
031    private JmsTemplate fatalJmsExceptionHandler;
032
033    public JmsTemplate getFatalJmsExceptionHandler() {
034        return fatalJmsExceptionHandler;
035    }
036
037    public void setFatalJmsExceptionHandler(JmsTemplate fatalJmsExceptionHandler) {
038        this.fatalJmsExceptionHandler = fatalJmsExceptionHandler;
039    }
040
041    @Override
042    public void onMessage(final Message message) {
043
044        if (fatalJmsExceptionHandler == null) {
045            doOnMessage(message);
046        } else {
047            try {
048                doOnMessage(message);
049            } catch (final FatalJmsException e) {
050                fatalJmsExceptionHandler.send(new FatalJmsExceptionMessageCreator(message, e));
051            }
052        }
053    }
054
055    /**
056     * Implements message handling functionality
057     * @param message Message to be read
058     * @throws FatalJmsException Exception thrown to indicate a processing failure that cannot be recovered from
059     */
060    protected abstract void doOnMessage(Message message) throws FatalJmsException;
061}