Coverage Report - org.mule.transport.jms.XaTransactedJmsMessageReceiver
 
Classes in this File Line Coverage Branch Coverage Complexity
XaTransactedJmsMessageReceiver
0%
0/111
0%
0/76
0
XaTransactedJmsMessageReceiver$1
0%
0/16
0%
0/12
0
XaTransactedJmsMessageReceiver$JmsThreadContext
0%
0/1
N/A
0
XaTransactedJmsMessageReceiver$ThreadContextLocal
0%
0/3
N/A
0
 
 1  
 /*
 2  
  * $Id: XaTransactedJmsMessageReceiver.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.MuleMessage;
 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.transaction.Transaction;
 18  
 import org.mule.api.transaction.TransactionCallback;
 19  
 import org.mule.api.transport.Connector;
 20  
 import org.mule.retry.policies.NoRetryPolicyTemplate;
 21  
 import org.mule.transaction.TransactionCoordination;
 22  
 import org.mule.transaction.TransactionTemplate;
 23  
 import org.mule.transaction.XaTransaction;
 24  
 import org.mule.transport.ConnectException;
 25  
 import org.mule.transport.TransactedPollingMessageReceiver;
 26  
 import org.mule.transport.jms.filters.JmsSelectorFilter;
 27  
 import org.mule.transport.jms.redelivery.RedeliveryHandler;
 28  
 import org.mule.util.ClassUtils;
 29  
 import org.mule.util.MapUtils;
 30  
 
 31  
 import java.util.List;
 32  
 
 33  
 import javax.jms.Destination;
 34  
 import javax.jms.JMSException;
 35  
 import javax.jms.Message;
 36  
 import javax.jms.MessageConsumer;
 37  
 import javax.jms.Session;
 38  
 
 39  
 import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
 40  
 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicReference;
 41  
 
 42  0
 public class XaTransactedJmsMessageReceiver extends TransactedPollingMessageReceiver
 43  
 {
 44  
     public static final long DEFAULT_JMS_POLL_FREQUENCY = 100;
 45  0
     public static final TimeUnit DEFAULT_JMS_POLL_TIMEUNIT = TimeUnit.MILLISECONDS;
 46  
     
 47  
     protected final JmsConnector connector;
 48  
     protected boolean reuseConsumer;
 49  
     protected boolean reuseSession;
 50  0
     protected final ThreadContextLocal context = new ThreadContextLocal();
 51  
     protected final long timeout;
 52  0
     private final AtomicReference/*<RedeliveryHandler>*/ redeliveryHandler = new AtomicReference();
 53  
 
 54  
     /**
 55  
      * Holder receiving the session and consumer for this thread.
 56  
      */
 57  0
     protected static class JmsThreadContext
 58  
     {
 59  
         public Session session;
 60  
         public MessageConsumer consumer;
 61  
     }
 62  
 
 63  
     /**
 64  
      * Strongly typed ThreadLocal for ThreadContext.
 65  
      */
 66  0
     protected static class ThreadContextLocal extends ThreadLocal
 67  
     {
 68  
         public JmsThreadContext getContext()
 69  
         {
 70  0
             return (JmsThreadContext)get();
 71  
         }
 72  
 
 73  
         @Override
 74  
         protected Object initialValue()
 75  
         {
 76  0
             return new JmsThreadContext();
 77  
         }
 78  
     }
 79  
 
 80  
     public XaTransactedJmsMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint)
 81  
         throws CreateException
 82  
     {
 83  0
         super(connector, flowConstruct, endpoint);
 84  
         // TODO AP: find appropriate value for polling frequency with the scheduler;
 85  
         // see setFrequency/setTimeUnit & VMMessageReceiver for more
 86  0
         this.setTimeUnit(DEFAULT_JMS_POLL_TIMEUNIT);
 87  0
         this.setFrequency(MapUtils.getLongValue(endpoint.getProperties(), "pollingFrequency", DEFAULT_JMS_POLL_FREQUENCY));
 88  
 
 89  0
         this.connector = (JmsConnector) connector;
 90  0
         this.timeout = endpoint.getTransactionConfig().getTimeout();
 91  
 
 92  
         // If reconnection is configured, default reuse strategy to false
 93  
         // as some jms brokers will not detect lost connections if the
 94  
         // same consumer / session is used
 95  0
         if (retryTemplate != null && !(retryTemplate instanceof NoRetryPolicyTemplate))
 96  
         {
 97  0
             this.reuseConsumer = false;
 98  0
             this.reuseSession = false;
 99  
         }
 100  
 
 101  
         // User may override reuse strategy if necessary. This is available for legacy reasons, 
 102  
         // but this approach is not recommended and should never be set when using XA.
 103  0
         this.reuseConsumer = MapUtils.getBooleanValue(endpoint.getProperties(), "reuseConsumer",
 104  
             this.reuseConsumer);
 105  0
         this.reuseSession = MapUtils.getBooleanValue(endpoint.getProperties(), "reuseSession",
 106  
             this.reuseSession);
 107  
 
 108  
         // Do extra validation, XA Topic & reuse are incompatible. See MULE-2622
 109  0
         boolean topic = this.connector.getTopicResolver().isTopic(getEndpoint());
 110  0
         if (topic && (reuseConsumer || reuseSession))
 111  
         {
 112  0
             logger.warn("Destination " + getEndpoint().getEndpointURI() + " is a topic and XA transaction was " +
 113  
                         "configured. Forcing 'reuseSession' and 'reuseConsumer' to false. Set these " +
 114  
                         "on endpoint to avoid the message.");
 115  0
             reuseConsumer = false;
 116  0
             reuseSession = false;
 117  
         }
 118  
 
 119  
         // Check if the destination is a queue and
 120  
         // if we are in transactional mode.
 121  
         // If true, set receiveMessagesInTransaction to true.
 122  
         // It will start multiple threads, depending on the threading profile.
 123  
 
 124  
         // If we're using topics we don't want to use multiple receivers as we'll get
 125  
         // the same message multiple times
 126  0
         this.setUseMultipleTransactedReceivers(!topic);
 127  0
     }
 128  
 
 129  
     @Override
 130  
     protected void doDispose()
 131  
     {
 132  
         // template method
 133  0
     }
 134  
 
 135  
     @Override
 136  
     protected void doConnect() throws Exception
 137  
     {
 138  0
         if (redeliveryHandler.compareAndSet(null, connector.getRedeliveryHandlerFactory().create()))
 139  
         {
 140  0
             ((RedeliveryHandler) redeliveryHandler.get()).setConnector(this.connector);
 141  
         }
 142  0
     }
 143  
 
 144  
     @Override
 145  
     protected void doDisconnect() throws Exception
 146  
     {
 147  0
         if (connector.isConnected())
 148  
         {
 149  
             // TODO All resources will be close by transaction or by connection close
 150  0
             closeResource(true);
 151  
         }
 152  0
     }
 153  
 
 154  
     /**
 155  
      * The poll method is overriden from the {@link TransactedPollingMessageReceiver}
 156  
      */
 157  
     @Override
 158  
     public void poll() throws Exception
 159  
     {
 160  0
         logger.debug("Polling...");
 161  
         
 162  0
         TransactionTemplate<Void> tt = new TransactionTemplate<Void>(
 163  
                                                 endpoint.getTransactionConfig(),
 164  
                                                 connector.getMuleContext());
 165  0
         TransactionCallback<Void> cb = new TransactionCallback<Void>()
 166  0
         {
 167  
             public Void doInTransaction() throws Exception
 168  
             {
 169  
                 try
 170  
                 {
 171  0
                     List messages = getMessages();
 172  0
                     if (messages != null && messages.size() > 0)
 173  
                     {
 174  0
                         for (Object message : messages)
 175  
                         {
 176  0
                             processMessage(message);
 177  
                         }
 178  
                     }
 179  0
                     return null;
 180  
                 }
 181  0
                 catch (Exception e)
 182  
                 {
 183  
                     // There is not a need to close resources here,
 184  
                     // they will be close by XaTransaction,  
 185  0
                     JmsThreadContext ctx = context.getContext();
 186  0
                     ctx.consumer = null;
 187  0
                     Transaction tx = TransactionCoordination.getInstance().getTransaction();
 188  0
                     if (ctx.session != null && tx instanceof XaTransaction.MuleXaObject)
 189  
                     {
 190  0
                         if (ctx.session instanceof XaTransaction.MuleXaObject)
 191  
                         {
 192  0
                             ((XaTransaction.MuleXaObject) ctx.session).setReuseObject(false);
 193  
                         }
 194  
                         else
 195  
                         {
 196  0
                             logger.warn("Session should be XA, but is of type " + ctx.session.getClass().getName());
 197  
                         }
 198  
                     }
 199  0
                     ctx.session = null;
 200  0
                     throw e;
 201  
                 }
 202  
             }
 203  
         };
 204  
         
 205  0
         tt.execute(cb);
 206  0
     }
 207  
 
 208  
     @Override
 209  
     protected List<MuleMessage> getMessages() throws Exception
 210  
     {
 211  0
         Session session = this.connector.getSessionFromTransaction();
 212  0
         Transaction tx = TransactionCoordination.getInstance().getTransaction();
 213  0
         MessageConsumer consumer = createConsumer();
 214  
 
 215  
         // Retrieve message
 216  0
         Message message = null;
 217  
         try
 218  
         {
 219  0
             message = consumer.receive(timeout);
 220  
         }
 221  0
         catch (JMSException e)
 222  
         {
 223  
             // If we're being disconnected, ignore the exception
 224  0
             if (!this.isConnected())
 225  
             {
 226  
                 // ignore
 227  
             }
 228  
             else
 229  
             {
 230  0
                 throw e;
 231  
             }
 232  0
         }
 233  
         
 234  0
         if (message == null)
 235  
         {
 236  0
             if (tx != null)
 237  
             {
 238  0
                 tx.setRollbackOnly();
 239  
             }
 240  0
             return null;
 241  
         }
 242  0
         message = connector.preProcessMessage(message, session);
 243  
 
 244  
         // Process message
 245  0
         if (logger.isDebugEnabled())
 246  
         {
 247  0
             logger.debug("Message received it is of type: " +
 248  
                     ClassUtils.getSimpleName(message.getClass()));
 249  0
             if (message.getJMSDestination() != null)
 250  
             {
 251  0
                 logger.debug("Message received on " + message.getJMSDestination() + " ("
 252  
                              + message.getJMSDestination().getClass().getName() + ")");
 253  
             }
 254  
             else
 255  
             {
 256  0
                 logger.debug("Message received on unknown destination");
 257  
             }
 258  0
             logger.debug("Message CorrelationId is: " + message.getJMSCorrelationID());
 259  0
             logger.debug("Jms Message Id is: " + message.getJMSMessageID());
 260  
         }
 261  
 
 262  0
         if (message.getJMSRedelivered())
 263  
         {
 264  0
             if (logger.isDebugEnabled())
 265  
             {
 266  0
                 logger.debug("Message with correlationId: " + message.getJMSCorrelationID()
 267  
                              + " is redelivered. handing off to Exception Handler");
 268  
             }
 269  0
             ((RedeliveryHandler) redeliveryHandler.get()).handleRedelivery(message, endpoint, flowConstruct);
 270  
         }
 271  
 
 272  0
         MuleMessage messageToRoute = createMuleMessage(message, endpoint.getEncoding());
 273  0
         routeMessage(messageToRoute);
 274  0
         return null;
 275  
     }
 276  
 
 277  
     @Override
 278  
     protected void processMessage(Object msg) throws Exception
 279  
     {
 280  
         // This method is never called as the
 281  
         // message is processed when received
 282  0
     }
 283  
 
 284  
     /**
 285  
      * Close Sesison and consumer
 286  
      */
 287  
     protected void closeResource(boolean force)
 288  
     {
 289  0
         JmsThreadContext ctx = context.getContext();
 290  0
         if (ctx == null)
 291  
         {
 292  0
             return;
 293  
         }
 294  
         
 295  
         // Close consumer
 296  0
         if (force || !reuseSession || !reuseConsumer)
 297  
         {
 298  0
             connector.closeQuietly(ctx.consumer);
 299  0
             ctx.consumer = null;
 300  
         }
 301  
             
 302  
         // Do not close session if a transaction is in progress
 303  
         // the session will be closed by the transaction
 304  0
         if (force || !reuseSession)
 305  
         {
 306  0
             connector.closeQuietly(ctx.session);
 307  0
             ctx.session = null;
 308  
         }        
 309  0
     }
 310  
 
 311  
     /**
 312  
      * Create a consumer for the jms destination
 313  
      * 
 314  
      * @throws Exception
 315  
      */
 316  
     protected MessageConsumer createConsumer() throws Exception
 317  
     {
 318  0
         logger.debug("Create a consumer for the jms destination");
 319  
         try
 320  
         {
 321  0
             JmsSupport jmsSupport = this.connector.getJmsSupport();
 322  
 
 323  0
             JmsThreadContext ctx = context.getContext();
 324  0
             if (ctx == null)
 325  
             {
 326  0
                 ctx = new JmsThreadContext();
 327  
             }
 328  
             
 329  
             Session session;
 330  0
             Transaction tx = TransactionCoordination.getInstance().getTransaction();
 331  0
             if (this.reuseSession && ctx.session != null)
 332  
             {
 333  0
                 session = ctx.session;
 334  0
                 tx.bindResource(this.connector.getConnection(), session);
 335  
             }
 336  
             else
 337  
             {
 338  0
                 session = this.connector.getSession(endpoint);
 339  0
                 if (session != null && tx != null)
 340  
                 {
 341  0
                     if (session instanceof XaTransaction.MuleXaObject)
 342  
                     {
 343  0
                         ((XaTransaction.MuleXaObject) session).setReuseObject(reuseSession);
 344  
                     }
 345  
                     else
 346  
                     {
 347  0
                         logger.warn("Session should be XA, but is of type " + session.getClass().getName());
 348  
                     }
 349  
                 }
 350  
             }
 351  
             
 352  0
             if (reuseSession)
 353  
             {
 354  0
                 ctx.session = session;
 355  
             }
 356  
             
 357  
             // TODO How can I verify that the consumer is active?
 358  0
             if (this.reuseConsumer && ctx.consumer != null)
 359  
             {
 360  0
                 return ctx.consumer;
 361  
             }
 362  
 
 363  
             // Create destination
 364  0
             final boolean topic = connector.getTopicResolver().isTopic(endpoint);
 365  0
             Destination dest = jmsSupport.createDestination(session, endpoint);
 366  
 
 367  
             // Extract jms selector
 368  0
             String selector = null;
 369  0
             if (endpoint.getFilter() != null && endpoint.getFilter() instanceof JmsSelectorFilter)
 370  
             {
 371  0
                 selector = ((JmsSelectorFilter)endpoint.getFilter()).getExpression();
 372  
             }
 373  0
             else if (endpoint.getProperties() != null)
 374  
             {
 375  
                 // still allow the selector to be set as a property on the endpoint
 376  
                 // to be backward compatible
 377  0
                 selector = (String)endpoint.getProperties().get(JmsConstants.JMS_SELECTOR_PROPERTY);
 378  
             }
 379  0
             String tempDurable = (String)endpoint.getProperties().get("durable");
 380  0
             boolean durable = connector.isDurable();
 381  0
             if (tempDurable != null)
 382  
             {
 383  0
                 durable = Boolean.valueOf(tempDurable);
 384  
             }
 385  
 
 386  
             // Get the durable subscriber name if there is one
 387  0
             String durableName = (String)endpoint.getProperties().get("durableName");
 388  0
             if (durableName == null && durable && topic)
 389  
             {
 390  0
                 durableName = "mule." + connector.getName() + "." + endpoint.getEndpointURI().getAddress();
 391  0
                 logger.debug("Jms Connector for this receiver is durable but no durable name has been specified. Defaulting to: "
 392  
                              + durableName);
 393  
             }
 394  
 
 395  
             // Create consumer
 396  0
             MessageConsumer consumer = jmsSupport.createConsumer(session, dest, selector, connector.isNoLocal(),
 397  
                 durableName, topic, endpoint);
 398  0
             if (reuseConsumer)
 399  
             {
 400  0
                 ctx.consumer = consumer;
 401  
             }
 402  0
             return consumer;
 403  
         }
 404  0
         catch (JMSException e)
 405  
         {
 406  0
             throw new ConnectException(e, this);
 407  
         }
 408  
     }
 409  
 }