View Javadoc

1   /*
2    * $Id: PollingReceiverWorker.java 20351 2010-11-25 18:01:47Z svacas $
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;
12  
13  import org.mule.RequestContext;
14  import org.mule.api.MuleException;
15  
16  import javax.resource.spi.work.Work;
17  
18  public class PollingReceiverWorker implements Work
19  {
20      protected final AbstractPollingMessageReceiver receiver;
21      protected volatile boolean running = false;
22  
23      public PollingReceiverWorker(AbstractPollingMessageReceiver pollingMessageReceiver)
24      {
25          super();
26          receiver = pollingMessageReceiver;
27      }
28  
29      public AbstractPollingMessageReceiver getReceiver()
30      {
31          return receiver;
32      }
33      
34      public boolean isRunning()
35      {
36          return running;
37      }
38  
39      // the run() method will exit after each poll() since it will be invoked again
40      // by the scheduler
41      public void run()
42      {
43          // Make sure we start with a clean slate.
44          RequestContext.clear();
45          if (receiver.isStarted())
46          {
47              running = true;
48              try
49              {
50                  poll();
51              }
52              catch (InterruptedException e)
53              {
54                 // stop polling
55                  try
56                  {
57                      receiver.stop();
58                  }
59                  catch (MuleException e1)
60                  {
61                      receiver.getConnector().getMuleContext().getExceptionListener().handleException(e1);
62                  }
63              }
64              catch (Exception e)
65              {
66                  receiver.getConnector().getMuleContext().getExceptionListener().handleException(e);
67              }
68              finally
69              {
70                  running = false;
71              }
72          }
73      }
74  
75      protected void poll() throws Exception
76      {
77          // make sure we are connected, wait if necessary
78          receiver.connected.whenTrue(null);
79          receiver.poll();
80      }
81  
82      public void release()
83      {
84          // nop
85      }
86  
87  }