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