1 20 21 package org.jivesoftware.smack; 22 23 import org.jivesoftware.smack.packet.Message; 24 import org.jivesoftware.smack.util.StringUtils; 25 import org.jivesoftware.smack.filter.*; 26 27 40 public class Chat { 41 42 45 private static String prefix = StringUtils.randomString(5); 46 47 51 private static boolean filteredOnThreadID = true; 52 53 57 private static long id = 0; 58 59 65 private static synchronized String nextID() { 66 return prefix + Long.toString(id++); 67 } 68 69 private XMPPConnection connection; 70 private String threadID; 71 private String participant; 72 private PacketFilter messageFilter; 73 private PacketCollector messageCollector; 74 75 81 public Chat(XMPPConnection connection, String participant) { 82 this(connection, participant, nextID()); 84 if (!filteredOnThreadID) { 86 this.threadID = null; 87 } 88 } 89 90 97 public Chat(XMPPConnection connection, String participant, String threadID) { 98 this.connection = connection; 99 this.participant = participant; 100 this.threadID = threadID; 101 102 if (filteredOnThreadID) { 103 messageFilter = new ThreadFilter(threadID); 105 } 106 else { 107 messageFilter = 109 new OrFilter( 110 new AndFilter( 111 new MessageTypeFilter(Message.Type.CHAT), 112 new FromContainsFilter(participant)), 113 new ThreadFilter(threadID)); 114 } 115 messageCollector = connection.createPacketCollector(messageFilter); 116 } 117 118 124 public static boolean isFilteredOnThreadID() { 125 return filteredOnThreadID; 126 } 127 128 134 public static void setFilteredOnThreadID(boolean value) { 135 filteredOnThreadID = value; 136 } 137 138 145 public String getThreadID() { 146 return threadID; 147 } 148 149 154 public String getParticipant() { 155 return participant; 156 } 157 158 171 public void sendMessage(String text) throws XMPPException { 172 Message message = createMessage(); 173 message.setBody(text); 174 connection.sendPacket(message); 175 } 176 177 185 public Message createMessage() { 186 Message message = new Message(participant, Message.Type.CHAT); 187 message.setThread(threadID); 188 return message; 189 } 190 191 200 public void sendMessage(Message message) throws XMPPException { 201 message.setTo(participant); 204 message.setType(Message.Type.CHAT); 205 message.setThread(threadID); 206 connection.sendPacket(message); 207 } 208 209 220 public Message pollMessage() { 221 return (Message)messageCollector.pollResult(); 222 } 223 224 230 public Message nextMessage() { 231 return (Message)messageCollector.nextResult(); 232 } 233 234 243 public Message nextMessage(long timeout) { 244 return (Message)messageCollector.nextResult(timeout); 245 } 246 247 253 public void addMessageListener(PacketListener listener) { 254 connection.addPacketListener(listener, messageFilter); 255 } 256 257 public void finalize() throws Throwable { 258 super.finalize(); 259 try { 260 if (messageCollector != null) { 261 messageCollector.cancel(); 262 } 263 } 264 catch (Exception e) {} 265 } 266 } | Popular Tags |