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.endpoint.ImmutableEndpoint;
10  
11  import org.jivesoftware.smack.Chat;
12  import org.jivesoftware.smack.XMPPException;
13  import org.jivesoftware.smack.filter.AndFilter;
14  import org.jivesoftware.smack.filter.FromMatchesFilter;
15  import org.jivesoftware.smack.filter.MessageTypeFilter;
16  import org.jivesoftware.smack.filter.PacketFilter;
17  import org.jivesoftware.smack.packet.Message;
18  
19  /**
20   * {@link XmppConversation} implementation that sends messages via {@link Chat}
21   */
22  public class XmppChatConversation extends AbstractXmppConversation
23  {
24      private Chat chat;
25      
26      public XmppChatConversation(ImmutableEndpoint endpoint)
27      {
28          super(endpoint);
29      }
30  
31      @Override
32      protected void doConnect()
33      {
34          chat = connection.getChatManager().createChat(recipient, null);
35      }
36  
37      @Override
38      protected PacketFilter createPacketFilter()
39      {
40          // The smack API provides Chat.createCollector to create a PacketCollector for a given chat.
41          // We cannot reasonably use this, however because smack uses a ThreadFilter internally
42          // to match the chat's thread ID. While testing with some Jabber clients (Psi, Spark) 
43          // it became obvious that the thread ID is not always preserved. Filtering for a given
44          // thread id would then prevent the PacketCollector to see incoming chat messages.
45          // We create our own PacketFilter here which matches only our chat partner's JID and
46          // the message type, just in case.
47          PacketFilter recipientFilter = new FromMatchesFilter(recipient);
48          PacketFilter messageTypeFilter = new MessageTypeFilter(Message.Type.chat);
49          return new AndFilter(recipientFilter, messageTypeFilter);
50      }
51  
52      @Override
53      protected void doDisconnect()
54      {
55          chat = null;
56      }
57  
58      public void dispatch(Message message) throws XMPPException
59      {
60          message.setType(Message.Type.chat);
61          chat.sendMessage(message);
62      }
63  }