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