View Javadoc

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