1 /***
2 *
3 * Copyright 2004 Protique Ltd
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 **/
18 package org.codehaus.activemq.util;
19
20 import javax.jms.ExceptionListener;
21 import javax.jms.JMSException;
22 import javax.jms.Message;
23 import javax.jms.MessageListener;
24
25 /***
26 * A helper base class which makes writing message listeners easier without
27 * having to worry about handling the JMSException on the onMessage() method.
28 * By default the JMS ExceptionListener will be used to handle any JMS exceptions
29 * or if none is configured then a runtime exception will be generated.
30 *
31 * @author James Strachan
32 * @version $Revision: 1.2 $
33 */
34 public abstract class MessageListenerSupport implements MessageListener {
35 private ExceptionListener exceptionListener;
36
37 public void onMessage(Message message) {
38 try {
39 processMessage(message);
40 }
41 catch (JMSException e) {
42 onJMSException(e, message);
43 }
44 catch (Exception e) {
45
46 JMSException jmsEx = JMSExceptionHelper.newJMSException(e.getMessage(), e);
47 onJMSException(jmsEx, message);
48 }
49 }
50
51 public ExceptionListener getExceptionListener() {
52 return exceptionListener;
53 }
54
55 public void setExceptionListener(ExceptionListener exceptionListener) {
56 this.exceptionListener = exceptionListener;
57 }
58
59 /***
60 * This method processes the incoming message possibly throwing a JMSException
61 * if the message could not be processed correctly.
62 *
63 * @param messsage
64 * @throws Exception
65 */
66 protected abstract void processMessage(Message messsage) throws Exception;
67
68 /***
69 * Process the JMS exception either by calling an exception listener
70 * which can contian custom logic or by throwing a runtime exception
71 *
72 * @param e
73 * @param message
74 */
75 protected void onJMSException(JMSException e, Message message) {
76 if (exceptionListener != null) {
77 exceptionListener.onException(e);
78 }
79 else {
80 throw new RuntimeException("Failed to process message: " + message + " Reason: " + e, e);
81 }
82 }
83
84 }