View Javadoc

1   /*
2    * $Id: JmsMessageReceiver.java 20501 2010-12-08 00:52:19Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.jms;
12  
13  import org.mule.api.MuleException;
14  import org.mule.api.construct.FlowConstruct;
15  import org.mule.api.endpoint.InboundEndpoint;
16  import org.mule.api.lifecycle.CreateException;
17  import org.mule.api.lifecycle.LifecycleException;
18  import org.mule.api.transaction.Transaction;
19  import org.mule.api.transaction.TransactionException;
20  import org.mule.api.transport.Connector;
21  import org.mule.transport.AbstractMessageReceiver;
22  import org.mule.transport.AbstractReceiverWorker;
23  import org.mule.transport.ConnectException;
24  import org.mule.transport.jms.filters.JmsSelectorFilter;
25  import org.mule.transport.jms.redelivery.RedeliveryHandler;
26  import org.mule.util.ClassUtils;
27  
28  import java.util.ArrayList;
29  import java.util.List;
30  
31  import javax.jms.Destination;
32  import javax.jms.JMSException;
33  import javax.jms.Message;
34  import javax.jms.MessageConsumer;
35  import javax.jms.MessageListener;
36  import javax.jms.Session;
37  import javax.jms.Topic;
38  
39  /**
40   * Registers a single JmsMessage listener but uses a thread pool to process incoming
41   * messages.
42   * @deprecated use {@link org.mule.transport.jms.MultiConsumerJmsMessageReceiver} (set by default).
43   */
44  @Deprecated
45  public class JmsMessageReceiver extends AbstractMessageReceiver implements MessageListener
46  {
47  
48      protected JmsConnector connector;
49      protected RedeliveryHandler redeliveryHandler;
50      protected MessageConsumer consumer;
51      protected Session session;
52      protected boolean startOnConnect = false;
53  
54      public JmsMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint)
55              throws CreateException
56      {
57          super(connector, flowConstruct, endpoint);
58          this.connector = (JmsConnector) connector;
59  
60          try
61          {
62              redeliveryHandler = this.connector.getRedeliveryHandlerFactory().create();
63              redeliveryHandler.setConnector(this.connector);
64          }
65          catch (Exception e)
66          {
67              throw new CreateException(e, this);
68          }
69      }
70  
71      protected void doConnect() throws Exception
72      {
73          createConsumer();
74          if (startOnConnect)
75          {
76              doStart();
77          }
78      }
79  
80      protected void doDisconnect() throws Exception
81      {
82          closeConsumer();
83      }
84  
85      public void onMessage(Message message)
86      {
87          try
88          {
89              getWorkManager().scheduleWork(new JmsWorker(message, this));
90          }
91          catch (Exception e)
92          {
93              getConnector().getMuleContext().getExceptionListener().handleException(e);
94          }
95      }
96  
97      protected  class JmsWorker extends AbstractReceiverWorker
98      {
99          public JmsWorker(Message message, AbstractMessageReceiver receiver)
100         {
101             super(new ArrayList(1), receiver);
102             messages.add(message);
103         }
104 
105         public JmsWorker(List messages, AbstractMessageReceiver receiver)
106         {
107             super(messages, receiver);
108         }
109 
110         @Override
111         protected Object preProcessMessage(Object message) throws Exception
112         {
113             Message m = (Message) message;
114 
115             if (logger.isDebugEnabled())
116             {
117                 logger.debug("Message received it is of type: " +
118                         ClassUtils.getSimpleName(message.getClass()));
119                 if (m.getJMSDestination() != null)
120                 {
121                     logger.debug("Message received on " + m.getJMSDestination() + " ("
122                             + m.getJMSDestination().getClass().getName() + ")");
123                 }
124                 else
125                 {
126                     logger.debug("Message received on unknown destination");
127                 }
128                 logger.debug("Message CorrelationId is: " + m.getJMSCorrelationID());
129                 logger.debug("Jms Message Id is: " + m.getJMSMessageID());
130             }
131 
132             if (m.getJMSRedelivered() && redeliveryHandler != null)
133             {
134                 if (logger.isDebugEnabled())
135                 {
136                     logger.debug("Message with correlationId: " + m.getJMSCorrelationID()
137                             + " has redelivered flag set, handing off to Exception Handler");
138                 }
139                 redeliveryHandler.handleRedelivery(m, receiver.getEndpoint(), receiver.getFlowConstruct());
140             }
141             return m;
142 
143         }
144 
145         protected void bindTransaction(Transaction tx) throws TransactionException
146         {
147             if(tx instanceof JmsTransaction)
148             {
149                 tx.bindResource(connector.getConnection(), session);
150             }
151             else if(tx instanceof JmsClientAcknowledgeTransaction)
152             {
153                 //We should still bind the session to the transaction, but we also need the message itself
154                 //since that is the object that gets Acknowledged
155                 tx.bindResource(connector.getConnection(), session);
156                 ((JmsClientAcknowledgeTransaction)tx).setMessage((Message)messages.get(0));
157             }
158         }
159     }
160 
161     protected void doStart() throws MuleException
162     {
163         try
164         {
165             // We ned to register the listener when start is called in order to only
166             // start receiving messages after
167             // start/
168             // If the consumer is null it means that the connection strategy is being
169             // run in a separate thread
170             // And hasn't managed to connect yet.
171             if (consumer == null)
172             {
173                 startOnConnect = true;
174             }
175             else
176             {
177                 startOnConnect = false;
178                 consumer.setMessageListener(this);
179             }
180         }
181         catch (JMSException e)
182         {
183             throw new LifecycleException(e, this);
184         }
185     }
186 
187     protected void doStop() throws MuleException
188     {
189         try
190         {
191             if (consumer != null)
192             {
193                 consumer.setMessageListener(null);
194             }
195         }
196         catch (JMSException e)
197         {
198             throw new LifecycleException(e, this);
199         }
200     }
201 
202     protected void doDispose()
203     {
204         // template method
205     }
206 
207     protected void closeConsumer()
208     {
209         connector.closeQuietly(consumer);
210         consumer = null;
211         connector.closeQuietly(session);
212         session = null;
213     }
214 
215     /**
216      * Create a consumer for the jms destination
217      *
218      * @throws Exception
219      */
220     protected void createConsumer() throws Exception
221     {
222         try
223         {
224             JmsSupport jmsSupport = this.connector.getJmsSupport();
225             // Create session if none exists
226             if (session == null)
227             {
228                 session = this.connector.getSession(endpoint);
229             }
230 
231             boolean topic = connector.getTopicResolver().isTopic(endpoint);
232 
233             // Create destination
234             Destination dest = jmsSupport.createDestination(session, endpoint);
235 
236             // Extract jms selector
237             String selector = null;
238             if (endpoint.getFilter() != null && endpoint.getFilter() instanceof JmsSelectorFilter)
239             {
240                 selector = ((JmsSelectorFilter) endpoint.getFilter()).getExpression();
241             }
242             else if (endpoint.getProperties() != null)
243             {
244                 // still allow the selector to be set as a property on the endpoint
245                 // to be backward compatable
246                 selector = (String) endpoint.getProperties().get(JmsConstants.JMS_SELECTOR_PROPERTY);
247             }
248             String tempDurable = (String) endpoint.getProperties().get(JmsConstants.DURABLE_PROPERTY);
249             boolean durable = connector.isDurable();
250             if (tempDurable != null)
251             {
252                 durable = Boolean.valueOf(tempDurable).booleanValue();
253             }
254 
255             // Get the durable subscriber name if there is one
256             String durableName = (String) endpoint.getProperties().get(JmsConstants.DURABLE_NAME_PROPERTY);
257             if (durableName == null && durable && dest instanceof Topic)
258             {
259                 durableName = "mule." + connector.getName() + "." + endpoint.getEndpointURI().getAddress();
260                 logger.debug("Jms Connector for this receiver is durable but no durable name has been specified. Defaulting to: "
261                         + durableName);
262             }
263 
264             // Create consumer
265             consumer = jmsSupport.createConsumer(session, dest, selector, connector.isNoLocal(), durableName,
266                     topic, endpoint);
267         }
268         catch (JMSException e)
269         {
270             throw new ConnectException(e, this);
271         }
272     }
273 
274 }