View Javadoc

1   /*
2    * $Id: AbstractReceiverResourceWorker.java 20321 2010-11-24 15:21:24Z dfeist $
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  package org.mule.transport;
11  
12  import java.io.OutputStream;
13  import java.util.ArrayList;
14  
15  /**
16   * This is a Message receiver worker used by transports that do not have a way for the underlying transport
17   * to call back to the receiver when a message is available such as Jms. This worker provides a
18   * callback {@link #getNextMessage(Object)} where the receiver can read the next message from the underlying
19   * transport.
20   */
21  public abstract class AbstractReceiverResourceWorker extends AbstractReceiverWorker
22  {
23      protected Object resource;
24  
25      public AbstractReceiverResourceWorker(Object resource, AbstractMessageReceiver receiver)
26      {
27          this(resource, receiver, null);
28      }
29  
30      public AbstractReceiverResourceWorker(Object resource, AbstractMessageReceiver receiver, OutputStream out)
31      {
32          super(new ArrayList<Object>(), receiver, out);
33          this.resource = resource;
34      }
35  
36      @Override
37      public void doRun()
38      {
39          try
40          {
41              Object message;
42              do 
43              {
44                  message = getNextMessage(resource);
45                  messages.add(message);
46                  super.doRun();
47              }
48              while (message != null && hasMoreMessages(message));
49          }
50          catch (Exception e)
51          {
52              receiver.getConnector().getMuleContext().getExceptionListener().handleException(e);
53          }
54      }
55  
56      protected boolean hasMoreMessages(Object message)
57      {
58          return true;
59      }
60      
61      /**
62       * The method used to read the next message from the underlying transport.
63       * @param resource the resource to read from, this may be a socket, a directory or some higher level
64       * representation.
65       * @return the message read from the resource.  This can be raw data such as a byte[].
66       * @throws Exception
67       */
68      protected abstract Object getNextMessage(Object resource) throws Exception;
69  }