View Javadoc

1   /*
2    * $Id: XmppPollingMessageReceiver.java 22396 2011-07-12 21:26:04Z mike.schilling $
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.xmpp;
12  
13  import org.mule.api.MuleException;
14  import org.mule.api.MuleMessage;
15  import org.mule.api.construct.FlowConstruct;
16  import org.mule.api.endpoint.InboundEndpoint;
17  import org.mule.api.lifecycle.CreateException;
18  import org.mule.api.transport.Connector;
19  import org.mule.transport.AbstractPollingMessageReceiver;
20  
21  import org.jivesoftware.smack.packet.Message;
22  
23  public class XmppPollingMessageReceiver extends AbstractPollingMessageReceiver
24  {
25      private final XmppConnector connector;
26      private XmppConversation conversation;
27  
28      public XmppPollingMessageReceiver(Connector conn, FlowConstruct flowConstruct, InboundEndpoint endpoint)
29          throws CreateException
30      {
31          super(conn, flowConstruct, endpoint);
32          connector = (XmppConnector) conn;
33          conversation = connector.getConversationFactory().create(endpoint);
34      }
35  
36      @Override
37      protected void doConnect() throws Exception
38      {
39          conversation.connect();
40      }
41  
42      @Override
43      protected void doDisconnect() throws Exception
44      {
45          conversation.disconnect();
46      }
47  
48      @Override
49      protected void doDispose()
50      {
51          conversation = null;
52      }
53  
54      @Override
55      public void poll() throws Exception
56      {
57          // Wait 10% less than the polling frequency. This approach makes sure that we finish 
58          // in time before the next poll call comes in
59          long frequency = getFrequency();
60          long tenPercent = (long)(frequency * 0.1);
61          long pollTimeout = frequency - tenPercent;
62          
63          Message xmppMessage = conversation.receive(pollTimeout);
64          if (xmppMessage == null)
65          {
66              return;
67          }
68          
69          processMessage(xmppMessage);
70      }
71  
72      @Override
73      protected boolean pollOnPrimaryInstanceOnly()
74      {
75          return true;
76      }
77  
78      protected void processMessage(Message xmppMessage) throws MuleException
79      {
80          MuleMessage muleMessage = createMuleMessage(xmppMessage);        
81          routeMessage(muleMessage);
82      }
83  }