From ae6065d7cc43b1eed57657774166979bbd13b2b4 Mon Sep 17 00:00:00 2001 From: Alex Wenckus Date: Wed, 22 Nov 2006 22:55:37 +0000 Subject: [PATCH] Created new chat manager which handles the creation of Chats. git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@6213 b35dd754-fafc-0310-a699-88a17e54d16e --- build/projects/Smack.iml | 2 +- build/projects/Smack.ipr | 147 +- source/org/jivesoftware/smack/Chat.java | 177 +-- .../org/jivesoftware/smack/ChatListener.java | 25 + .../org/jivesoftware/smack/ChatManager.java | 188 +++ .../jivesoftware/smack/XMPPConnection.java | 58 +- .../jivesoftware/smack/filter/AndFilter.java | 50 +- .../smack/filter/ThreadFilter.java | 7 +- .../jivesoftware/smack/packet/Message.java | 59 +- .../collections/AbstractEmptyIterator.java | 89 ++ .../util/collections/AbstractHashedMap.java | 1338 +++++++++++++++++ .../util/collections/AbstractKeyValue.java | 80 + .../util/collections/AbstractMapEntry.java | 89 ++ .../collections/AbstractReferenceMap.java | 1025 +++++++++++++ .../util/collections/DefaultMapEntry.java | 65 + .../smack/util/collections/EmptyIterator.java | 58 + .../util/collections/EmptyMapIterator.java | 42 + .../smack/util/collections/IterableMap.java | 61 + .../smack/util/collections/KeyValue.java | 46 + .../smack/util/collections/MapIterator.java | 109 ++ .../smack/util/collections/ReferenceMap.java | 161 ++ .../util/collections/ResettableIterator.java | 38 + test/org/jivesoftware/smack/ChatTest.java | 153 +- test/org/jivesoftware/smack/FloodTest.java | 22 +- test/org/jivesoftware/smack/MessageTest.java | 25 +- .../smack/filter/AndFilterTest.java | 2 +- test/org/jivesoftware/smackx/FormTest.java | 30 +- .../smackx/MessageEventManagerTest.java | 20 +- .../smackx/MultipleRecipientManagerTest.java | 20 +- .../smackx/OfflineMessageManagerTest.java | 14 +- .../smackx/ServiceDiscoveryManagerTest.java | 4 - .../jivesoftware/smackx/XHTMLManagerTest.java | 117 +- .../smackx/muc/MultiUserChatTest.java | 41 +- .../smackx/packet/MessageEventTest.java | 12 +- .../smackx/packet/RosterExchangeTest.java | 131 +- .../smackx/packet/XHTMLExtensionTest.java | 173 +-- 36 files changed, 3964 insertions(+), 714 deletions(-) create mode 100644 source/org/jivesoftware/smack/ChatListener.java create mode 100644 source/org/jivesoftware/smack/ChatManager.java create mode 100644 source/org/jivesoftware/smack/util/collections/AbstractEmptyIterator.java create mode 100644 source/org/jivesoftware/smack/util/collections/AbstractHashedMap.java create mode 100644 source/org/jivesoftware/smack/util/collections/AbstractKeyValue.java create mode 100644 source/org/jivesoftware/smack/util/collections/AbstractMapEntry.java create mode 100644 source/org/jivesoftware/smack/util/collections/AbstractReferenceMap.java create mode 100644 source/org/jivesoftware/smack/util/collections/DefaultMapEntry.java create mode 100644 source/org/jivesoftware/smack/util/collections/EmptyIterator.java create mode 100644 source/org/jivesoftware/smack/util/collections/EmptyMapIterator.java create mode 100644 source/org/jivesoftware/smack/util/collections/IterableMap.java create mode 100644 source/org/jivesoftware/smack/util/collections/KeyValue.java create mode 100644 source/org/jivesoftware/smack/util/collections/MapIterator.java create mode 100644 source/org/jivesoftware/smack/util/collections/ReferenceMap.java create mode 100644 source/org/jivesoftware/smack/util/collections/ResettableIterator.java diff --git a/build/projects/Smack.iml b/build/projects/Smack.iml index 73ac27096..7496ded77 100644 --- a/build/projects/Smack.iml +++ b/build/projects/Smack.iml @@ -1,7 +1,7 @@ - + diff --git a/build/projects/Smack.ipr b/build/projects/Smack.ipr index b168f4e95..95aadef4c 100644 --- a/build/projects/Smack.ipr +++ b/build/projects/Smack.ipr @@ -12,6 +12,13 @@ + + + + + + + + @@ -61,6 +84,48 @@ + + + @@ -92,116 +158,141 @@ + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + @@ -224,6 +324,7 @@ diff --git a/source/org/jivesoftware/smack/Chat.java b/source/org/jivesoftware/smack/Chat.java index b82c91e30..478ec3cec 100644 --- a/source/org/jivesoftware/smack/Chat.java +++ b/source/org/jivesoftware/smack/Chat.java @@ -20,15 +20,12 @@ package org.jivesoftware.smack; -import org.jivesoftware.smack.filter.PacketFilter; -import org.jivesoftware.smack.filter.ThreadFilter; import org.jivesoftware.smack.packet.Message; -import org.jivesoftware.smack.util.StringUtils; import java.lang.ref.WeakReference; -import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; /** * A chat is a series of messages sent between two users. Each chat has a unique @@ -37,73 +34,28 @@ import java.util.Set; * don't send thread IDs at all. Therefore, if a message without a thread ID * arrives it is routed to the most recently created Chat with the message * sender. - * - * @see XMPPConnection#createChat(String) + * * @author Matt Tucker */ public class Chat { - /** - * A prefix helps to make sure that ID's are unique across mutliple instances. - */ - private static String prefix = StringUtils.randomString(5); - - /** - * Keeps track of the current increment, which is appended to the prefix to - * forum a unique ID. - */ - private static long id = 0; - - /** - * Returns the next unique id. Each id made up of a short alphanumeric - * prefix along with a unique numeric value. - * - * @return the next id. - */ - private static synchronized String nextID() { - return prefix + Long.toString(id++); - } - - private XMPPConnection connection; + private ChatManager chatManager; private String threadID; private String participant; - private PacketFilter messageFilter; - private PacketCollector messageCollector; private final Set> listeners = - new HashSet>(); - - /** - * Creates a new chat with the specified user. - * - * @param connection the connection the chat will use. - * @param participant the user to chat with. - */ - public Chat(XMPPConnection connection, String participant) { - // Automatically assign the next chat ID. - this(connection, participant, nextID()); - } + new CopyOnWriteArraySet>(); /** * Creates a new chat with the specified user and thread ID. * - * @param connection the connection the chat will use. + * @param chatManager the chatManager the chat will use. * @param participant the user to chat with. * @param threadID the thread ID to use. */ - public Chat(XMPPConnection connection, String participant, String threadID) { - this.connection = connection; + Chat(ChatManager chatManager, String participant, String threadID) { + this.chatManager = chatManager; this.participant = participant; this.threadID = threadID; - - // Register with the map of chats so that messages with no thread ID - // set will be delivered to this Chat. - connection.chats.put(StringUtils.parseBareAddress(participant), - new WeakReference(this)); - - // Filter the messages whose thread equals Chat's id - messageFilter = new ThreadFilter(threadID); - - messageCollector = connection.createPacketCollector(messageFilter); } /** @@ -140,30 +92,15 @@ public class Chat { * @throws XMPPException if sending the message fails. */ public void sendMessage(String text) throws XMPPException { - Message message = createMessage(); - message.setBody(text); - connection.sendPacket(message); - } - - /** - * Creates a new Message to the chat participant. The message returned - * will have its thread property set with this chat ID. - * - * @return a new message addressed to the chat participant and - * using the correct thread value. - * @see #sendMessage(Message) - */ - public Message createMessage() { - Message message = new Message(participant, Message.Type.CHAT); + Message message = new Message(participant, Message.Type.chat); message.setThread(threadID); - return message; + message.setBody(text); + chatManager.sendMessage(this, message); } /** * Sends a message to the other chat participant. The thread ID, recipient, - * and message type of the message will automatically set to those of this chat - * in case the Message was not created using the {@link #createMessage() createMessage} - * method. + * and message type of the message will automatically set to those of this chat. * * @param message the message to send. * @throws XMPPException if an error occurs sending the message. @@ -172,47 +109,9 @@ public class Chat { // Force the recipient, message type, and thread ID since the user elected // to send the message through this chat object. message.setTo(participant); - message.setType(Message.Type.CHAT); + message.setType(Message.Type.chat); message.setThread(threadID); - connection.sendPacket(message); - } - - /** - * Polls for and returns the next message, or null if there isn't - * a message immediately available. This method provides significantly different - * functionalty than the {@link #nextMessage()} method since it's non-blocking. - * In other words, the method call will always return immediately, whereas the - * nextMessage method will return only when a message is available (or after - * a specific timeout). - * - * @return the next message if one is immediately available and - * null otherwise. - */ - public Message pollMessage() { - return (Message)messageCollector.pollResult(); - } - - /** - * Returns the next available message in the chat. The method call will block - * (not return) until a message is available. - * - * @return the next message. - */ - public Message nextMessage() { - return (Message)messageCollector.nextResult(); - } - - /** - * Returns the next available message in the chat. The method call will block - * (not return) until a packet is available or the timeout has elapased. - * If the timeout elapses without a result, null will be returned. - * - * @param timeout the maximum amount of time to wait for the next message. - * @return the next message, or null if the timeout elapses without a - * message becoming available. - */ - public Message nextMessage(long timeout) { - return (Message)messageCollector.nextResult(timeout); + chatManager.sendMessage(this, message); } /** @@ -222,12 +121,21 @@ public class Chat { * @param listener a packet listener. */ public void addMessageListener(PacketListener listener) { - connection.addPacketListener(listener, messageFilter); - // Keep track of the listener so that we can manually deliver extra - // messages to it later if needed. - synchronized (listeners) { - listeners.add(new WeakReference(listener)); + if(listener == null) { + return; } + listeners.add(new WeakReference(listener)); + } + + /** + * Creates a {@link org.jivesoftware.smack.PacketCollector} which will accumulate the Messages + * for this chat. Always cancel PacketCollectors when finished with them as they will accumulate + * messages indefinitely. + * + * @return the PacketCollector which returns Messages for this chat. + */ + public PacketCollector createCollector() { + return chatManager.createPacketCollector(this); } /** @@ -244,31 +152,16 @@ public class Chat { // probably never had one. message.setThread(threadID); - messageCollector.processPacket(message); - synchronized (listeners) { - for (Iterator> i=listeners.iterator(); i.hasNext(); ) { - WeakReference listenerRef = i.next(); - PacketListener listener; - if ((listener = listenerRef.get()) != null) { - listener.processPacket(message); - } - // If the reference was cleared, remove it from the set. - else { - i.remove(); - } + for (Iterator> i = listeners.iterator(); i.hasNext();) { + WeakReference listenerRef = i.next(); + PacketListener listener; + if ((listener = listenerRef.get()) != null) { + listener.processPacket(message); } - } - } - - public void finalize() throws Throwable { - super.finalize(); - try { - if (messageCollector != null) { - messageCollector.cancel(); + // If the reference was cleared, remove it from the set. + else { + i.remove(); } } - catch (Exception e) { - // Ignore. - } } } \ No newline at end of file diff --git a/source/org/jivesoftware/smack/ChatListener.java b/source/org/jivesoftware/smack/ChatListener.java new file mode 100644 index 000000000..9e055b4bd --- /dev/null +++ b/source/org/jivesoftware/smack/ChatListener.java @@ -0,0 +1,25 @@ +/** + * $RCSfile: $ + * $Revision: $ + * $Date: $ + * + * Copyright (C) 2006 Jive Software. All rights reserved. + * This software is the proprietary information of Jive Software. Use is subject to license terms. + */ +package org.jivesoftware.smack; + +/** + * A listener for chat related events. + * + * @author Alexander Wenckus + */ +public interface ChatListener { + + /** + * Event fired when a new chat is created. + * + * @param chat the chat that was created. + * @param createdLocally true if the chat was created by the local user and false if it wasn't. + */ + void chatCreated(Chat chat, boolean createdLocally); +} diff --git a/source/org/jivesoftware/smack/ChatManager.java b/source/org/jivesoftware/smack/ChatManager.java new file mode 100644 index 000000000..6052216d7 --- /dev/null +++ b/source/org/jivesoftware/smack/ChatManager.java @@ -0,0 +1,188 @@ +/** + * $RCSfile: $ + * $Revision: $ + * $Date: $ + * + * Copyright (C) 2006 Jive Software. All rights reserved. + * This software is the proprietary information of Jive Software. Use is subject to license terms. + */ +package org.jivesoftware.smack; + +import org.jivesoftware.smack.util.StringUtils; +import org.jivesoftware.smack.util.collections.ReferenceMap; +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smack.packet.Packet; +import org.jivesoftware.smack.filter.*; + +import java.util.*; +import java.util.concurrent.CopyOnWriteArraySet; + +/** + * The chat manager keeps track of references to all current chats. It will not hold any references + * in memory on its own so it is neccesary to keep a reference to the chat object itself. To be + * made aware of new chats, register a listener by calling {@link #addChatListener(ChatListener)}. + * + * @author Alexander Wenckus + */ +public class ChatManager { + /** + * Returns the next unique id. Each id made up of a short alphanumeric + * prefix along with a unique numeric value. + * + * @return the next id. + */ + private static synchronized String nextID() { + return prefix + Long.toString(id++); + } + + /** + * A prefix helps to make sure that ID's are unique across mutliple instances. + */ + private static String prefix = StringUtils.randomString(5); + + /** + * Keeps track of the current increment, which is appended to the prefix to + * forum a unique ID. + */ + private static long id = 0; + + /** + * Maps thread ID to chat. + */ + private Map threadChats = new ReferenceMap(ReferenceMap.HARD, + ReferenceMap.WEAK); + + /** + * Maps jids to chats + */ + private Map jidChats = new ReferenceMap(ReferenceMap.HARD, + ReferenceMap.WEAK); + + private Set chatListeners = new CopyOnWriteArraySet(); + + private XMPPConnection connection; + + ChatManager(XMPPConnection connection) { + this.connection = connection; + + PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class), + new PacketFilter() { + + public boolean accept(Packet packet) { + if (!(packet instanceof Message)) { + return false; + } + Message.Type messageType = ((Message) packet).getType(); + return messageType != Message.Type.groupchat && + messageType != Message.Type.headline; + } + }); + // Add a listener for all message packets so that we can deliver errant + // messages to the best Chat instance available. + connection.addPacketListener(new PacketListener() { + public void processPacket(Packet packet) { + Message message = (Message) packet; + Chat chat; + if (message.getThread() == null) { + chat = getUserChat(StringUtils.parseBareAddress(message.getFrom())); + } + else { + chat = getThreadChat(message.getThread()); + } + + if(chat == null) { + chat = createChat(message); + } + deliverMessage(chat, message); + } + }, filter); + } + + /** + * Creates a new chat and returns it. + * + * @param userJID the user this chat is with. + * @param listener the listener which will listen for new messages from this chat. + * @return the created chat. + */ + public Chat createChat(String userJID, PacketListener listener) { + String threadID = nextID(); + + Chat chat = createChat(userJID, threadID, true); + chat.addMessageListener(listener); + + return chat; + } + + private Chat createChat(String userJID, String threadID, boolean createdLocally) { + Chat chat = new Chat(this, userJID, threadID); + threadChats.put(threadID, chat); + jidChats.put(userJID, chat); + + for(ChatListener listener : chatListeners) { + listener.chatCreated(chat, createdLocally); + } + + return chat; + } + + private Chat createChat(Message message) { + String threadID = message.getThread(); + String userJID = message.getFrom(); + + return createChat(userJID, threadID, false); + } + + private Chat getUserChat(String userJID) { + return jidChats.get(userJID); + } + + private Chat getThreadChat(String thread) { + return threadChats.get(thread); + } + + /** + * Register a new listener with the ChatManager to recieve events related to chats. + * + * @param listener the listener. + */ + public void addChatListener(ChatListener listener) { + chatListeners.add(listener); + } + + /** + * Removes a listener, it will no longer be notified of new events related to chats. + * + * @param listener the listener that is being removed + */ + public void removeChatListener(ChatListener listener) { + chatListeners.remove(listener); + } + + /** + * Returns an unmodifiable collection of all chat listeners currently registered with this + * manager. + * + * @return an unmodifiable collection of all chat listeners currently registered with this + * manager. + */ + public Collection getChatListeners() { + return Collections.unmodifiableCollection(chatListeners); + } + + private void deliverMessage(Chat chat, Message message) { + // Here we will run any interceptors + chat.deliver(message); + } + + void sendMessage(Chat chat, Message message) { + // Here we will run any interceptors + connection.sendPacket(message); + } + + PacketCollector createPacketCollector(Chat chat) { + return connection.createPacketCollector(new AndFilter(new ThreadFilter(chat.getThreadID()), + new FromContainsFilter(chat.getParticipant()))); + } + +} diff --git a/source/org/jivesoftware/smack/XMPPConnection.java b/source/org/jivesoftware/smack/XMPPConnection.java index 9d77d9cf1..cebee8b97 100644 --- a/source/org/jivesoftware/smack/XMPPConnection.java +++ b/source/org/jivesoftware/smack/XMPPConnection.java @@ -22,8 +22,6 @@ package org.jivesoftware.smack; import org.jivesoftware.smack.debugger.SmackDebugger; import org.jivesoftware.smack.filter.PacketFilter; -import org.jivesoftware.smack.filter.PacketTypeFilter; -import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.XMPPError; @@ -34,15 +32,12 @@ import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import java.io.*; -import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.Socket; import java.net.UnknownHostException; import java.util.Collection; -import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; /** @@ -147,14 +142,6 @@ public class XMPPConnection { Writer writer; Reader reader; - /** - * A map between JIDs and the most recently created Chat object with that JID. - * Reference to the Chat is stored via a WeakReference so that the map - * does not interfere with garbage collection. The map of chats must be stored - * with each connection. - */ - Map> chats = new ConcurrentHashMap>(); - /** * Collection of available stream compression methods offered by the server. */ @@ -167,6 +154,7 @@ public class XMPPConnection { * Holds the initial configuration used while creating the connection. */ private ConnectionConfiguration configuration; + private ChatManager chatManager; /** * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be @@ -564,18 +552,16 @@ public class XMPPConnection { } /** - * Creates a new chat with the specified participant. The participant should - * be a valid XMPP user such as jdoe@jivesoftware.com or - * jdoe@jivesoftware.com/work. + * Returns a chat manager instance for this connection. The ChatManager manages all incoming and + * outgoing chats on the current connection. * - * @param participant the person to start the conversation with. - * @return a new Chat object. + * @return a chat manager instance for this connection. */ - public Chat createChat(String participant) { - if (!isConnected()) { - throw new IllegalStateException("Not connected to server."); + public synchronized ChatManager getChatManager() { + if(this.chatManager == null) { + this.chatManager = new ChatManager(this); } - return new Chat(this, participant); + return this.chatManager; } /** @@ -934,34 +920,6 @@ public class XMPPConnection { for (ConnectionCreationListener listener : connectionEstablishedListeners) { listener.connectionCreated(this); } - - // Add a listener for all message packets so that we can deliver errant - // messages to the best Chat instance available. - addPacketListener(new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - // Ignore any messages with a thread ID, as they will likely - // already be associated with a Chat. This will miss messages - // with new thread ID values, but we can only assume that a - // listener is registered to deal with this case. - if (message.getThread() == null && - message.getType() != Message.Type.GROUP_CHAT && - message.getType() != Message.Type.HEADLINE) { - WeakReference chatRef = - chats.get(StringUtils.parseBareAddress(message.getFrom())); - if (chatRef != null) { - // Do some extra clean-up if the reference was cleared. - Chat chat = chatRef.get(); - if (chat == null) { - chats.remove(message.getFrom()); - } - else { - chat.deliver(message); - } - } - } - } - }, new PacketTypeFilter(Message.class)); } else { packetReader.notifyReconnection(); diff --git a/source/org/jivesoftware/smack/filter/AndFilter.java b/source/org/jivesoftware/smack/filter/AndFilter.java index 2ca4a1c2b..9a3fc6bc0 100644 --- a/source/org/jivesoftware/smack/filter/AndFilter.java +++ b/source/org/jivesoftware/smack/filter/AndFilter.java @@ -22,6 +22,9 @@ package org.jivesoftware.smack.filter; import org.jivesoftware.smack.packet.Packet; +import java.util.List; +import java.util.ArrayList; + /** * Implements the logical AND operation over two or more packet filters. * In other words, packets pass this filter if they pass all of the filters. @@ -30,39 +33,34 @@ import org.jivesoftware.smack.packet.Packet; */ public class AndFilter implements PacketFilter { - /** - * The current number of elements in the filter. - */ - private int size; - /** * The list of filters. */ - private PacketFilter [] filters; + private List filters = new ArrayList(); /** * Creates an empty AND filter. Filters should be added using the * {@link #addFilter(PacketFilter)} method. */ public AndFilter() { - size = 0; - filters = new PacketFilter[3]; + } /** - * Creates an AND filter using the two specified filters. + * Creates an AND filter using the specified filters. * - * @param filter1 the first packet filter. - * @param filter2 the second packet filter. + * @param filters the filters to add. */ - public AndFilter(PacketFilter filter1, PacketFilter filter2) { - if (filter1 == null || filter2 == null) { - throw new IllegalArgumentException("Parameters cannot be null."); + public AndFilter(PacketFilter... filters) { + if (filters == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + for(PacketFilter filter : filters) { + if(filter == null) { + throw new IllegalArgumentException("Parameter cannot be null."); + } + this.filters.add(filter); } - size = 2; - filters = new PacketFilter[2]; - filters[0] = filter1; - filters[1] = filter2; } /** @@ -75,22 +73,12 @@ public class AndFilter implements PacketFilter { if (filter == null) { throw new IllegalArgumentException("Parameter cannot be null."); } - // If there is no more room left in the filters array, expand it. - if (size == filters.length) { - PacketFilter [] newFilters = new PacketFilter[filters.length+2]; - for (int i=0; i"); @@ -190,7 +191,7 @@ public class Message extends Packet { buf.append("").append(thread).append(""); } // Append the error subpacket if the message type is an error. - if (type == Type.ERROR) { + if (type == Type.error) { XMPPError error = getError(); if (error != null) { buf.append(error.toXML()); @@ -205,69 +206,41 @@ public class Message extends Packet { /** * Represents the type of a message. */ - public static class Type { + public enum Type { /** * (Default) a normal text message used in email like interface. */ - public static final Type NORMAL = new Type("normal"); + normal, /** * Typically short text message used in line-by-line chat interfaces. */ - public static final Type CHAT = new Type("chat"); + chat, /** * Chat message sent to a groupchat server for group chats. */ - public static final Type GROUP_CHAT = new Type("groupchat"); + groupchat, /** * Text message to be displayed in scrolling marquee displays. */ - public static final Type HEADLINE = new Type("headline"); + headline, /** * indicates a messaging error. */ - public static final Type ERROR = new Type("error"); + error; - /** - * Converts a String value into its Type representation. - * - * @param type the String value. - * @return the Type corresponding to the String. - */ - public static Type fromString(String type) { - if (type == null) { - return NORMAL; + public static Type fromString(String name) { + try { + return Type.valueOf(name); } - type = type.toLowerCase(); - if (CHAT.toString().equals(type)) { - return CHAT; - } - else if (GROUP_CHAT.toString().equals(type)) { - return GROUP_CHAT; - } - else if (HEADLINE.toString().equals(type)) { - return HEADLINE; - } - else if (ERROR.toString().equals(type)) { - return ERROR; - } - else { - return NORMAL; + catch (Exception e) { + return normal; } } - private String value; - - private Type(String value) { - this.value = value; - } - - public String toString() { - return value; - } } } \ No newline at end of file diff --git a/source/org/jivesoftware/smack/util/collections/AbstractEmptyIterator.java b/source/org/jivesoftware/smack/util/collections/AbstractEmptyIterator.java new file mode 100644 index 000000000..c2ec15678 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/AbstractEmptyIterator.java @@ -0,0 +1,89 @@ +// GenericsNote: Converted. +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.NoSuchElementException; + +/** + * Provides an implementation of an empty iterator. + * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ + * @since Commons Collections 3.1 + */ +abstract class AbstractEmptyIterator { + + /** + * Constructor. + */ + protected AbstractEmptyIterator() { + super(); + } + + public boolean hasNext() { + return false; + } + + public E next() { + throw new NoSuchElementException("Iterator contains no elements"); + } + + public boolean hasPrevious() { + return false; + } + + public E previous() { + throw new NoSuchElementException("Iterator contains no elements"); + } + + public int nextIndex() { + return 0; + } + + public int previousIndex() { + return -1; + } + + public void add(E obj) { + throw new UnsupportedOperationException("add() not supported for empty Iterator"); + } + + public void set(E obj) { + throw new IllegalStateException("Iterator contains no elements"); + } + + public void remove() { + throw new IllegalStateException("Iterator contains no elements"); + } + + public E getKey() { + throw new IllegalStateException("Iterator contains no elements"); + } + + public E getValue() { + throw new IllegalStateException("Iterator contains no elements"); + } + + public E setValue(E value) { + throw new IllegalStateException("Iterator contains no elements"); + } + + public void reset() { + // do nothing + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/AbstractHashedMap.java b/source/org/jivesoftware/smack/util/collections/AbstractHashedMap.java new file mode 100644 index 000000000..85740f3fc --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/AbstractHashedMap.java @@ -0,0 +1,1338 @@ +// GenericsNote: Converted -- However, null keys will now be represented in the internal structures, a big change. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.*; + +/** + * An abstract implementation of a hash-based map which provides numerous points for + * subclasses to override. + *

+ * This class implements all the features necessary for a subclass hash-based map. + * Key-value entries are stored in instances of the HashEntry class, + * which can be overridden and replaced. The iterators can similarly be replaced, + * without the need to replace the KeySet, EntrySet and Values view classes. + *

+ * Overridable methods are provided to change the default hashing behaviour, and + * to change how entries are added to and removed from the map. Hopefully, all you + * need for unusual subclasses is here. + *

+ * NOTE: From Commons Collections 3.1 this class extends AbstractMap. + * This is to provide backwards compatibility for ReferenceMap between v3.0 and v3.1. + * This extends clause will be removed in v4.0. + * + * @author java util HashMap + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @since Commons Collections 3.0 + */ +public class AbstractHashedMap extends AbstractMap implements IterableMap { + + protected static final String NO_NEXT_ENTRY = "No next() entry in the iteration"; + protected static final String NO_PREVIOUS_ENTRY = "No previous() entry in the iteration"; + protected static final String REMOVE_INVALID = "remove() can only be called once after next()"; + protected static final String GETKEY_INVALID = "getKey() can only be called after next() and before remove()"; + protected static final String GETVALUE_INVALID = "getValue() can only be called after next() and before remove()"; + protected static final String SETVALUE_INVALID = "setValue() can only be called after next() and before remove()"; + + /** + * The default capacity to use + */ + protected static final int DEFAULT_CAPACITY = 16; + /** + * The default threshold to use + */ + protected static final int DEFAULT_THRESHOLD = 12; + /** + * The default load factor to use + */ + protected static final float DEFAULT_LOAD_FACTOR = 0.75f; + /** + * The maximum capacity allowed + */ + protected static final int MAXIMUM_CAPACITY = 1 << 30; + /** + * An object for masking null + */ + protected static final Object NULL = new Object(); + + /** + * Load factor, normally 0.75 + */ + protected transient float loadFactor; + /** + * The size of the map + */ + protected transient int size; + /** + * Map entries + */ + protected transient HashEntry[] data; + /** + * Size at which to rehash + */ + protected transient int threshold; + /** + * Modification count for iterators + */ + protected transient int modCount; + /** + * Entry set + */ + protected transient EntrySet entrySet; + /** + * Key set + */ + protected transient KeySet keySet; + /** + * Values + */ + protected transient Values values; + + /** + * Constructor only used in deserialization, do not use otherwise. + */ + protected AbstractHashedMap() { + super(); + } + + /** + * Constructor which performs no validation on the passed in parameters. + * + * @param initialCapacity the initial capacity, must be a power of two + * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f + * @param threshold the threshold, must be sensible + */ + protected AbstractHashedMap(int initialCapacity, float loadFactor, int threshold) { + super(); + this.loadFactor = loadFactor; + this.data = new HashEntry[initialCapacity]; + this.threshold = threshold; + init(); + } + + /** + * Constructs a new, empty map with the specified initial capacity and + * default load factor. + * + * @param initialCapacity the initial capacity + * @throws IllegalArgumentException if the initial capacity is less than one + */ + protected AbstractHashedMap(int initialCapacity) { + this(initialCapacity, DEFAULT_LOAD_FACTOR); + } + + /** + * Constructs a new, empty map with the specified initial capacity and + * load factor. + * + * @param initialCapacity the initial capacity + * @param loadFactor the load factor + * @throws IllegalArgumentException if the initial capacity is less than one + * @throws IllegalArgumentException if the load factor is less than or equal to zero + */ + protected AbstractHashedMap(int initialCapacity, float loadFactor) { + super(); + if (initialCapacity < 1) { + throw new IllegalArgumentException("Initial capacity must be greater than 0"); + } + if (loadFactor <= 0.0f || Float.isNaN(loadFactor)) { + throw new IllegalArgumentException("Load factor must be greater than 0"); + } + this.loadFactor = loadFactor; + this.threshold = calculateThreshold(initialCapacity, loadFactor); + initialCapacity = calculateNewCapacity(initialCapacity); + this.data = new HashEntry[initialCapacity]; + init(); + } + + /** + * Constructor copying elements from another map. + * + * @param map the map to copy + * @throws NullPointerException if the map is null + */ + protected AbstractHashedMap(Map map) { + this(Math.max(2 * map.size(), DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR); + putAll(map); + } + + /** + * Initialise subclasses during construction, cloning or deserialization. + */ + protected void init() { + } + + //----------------------------------------------------------------------- + /** + * Gets the value mapped to the key specified. + * + * @param key the key + * @return the mapped value, null if no match + */ + public V get(Object key) { + int hashCode = hash((key == null) ? NULL : key); + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + while (entry != null) { + if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { + return entry.getValue(); + } + entry = entry.next; + } + return null; + } + + /** + * Gets the size of the map. + * + * @return the size + */ + public int size() { + return size; + } + + /** + * Checks whether the map is currently empty. + * + * @return true if the map is currently size zero + */ + public boolean isEmpty() { + return (size == 0); + } + + //----------------------------------------------------------------------- + /** + * Checks whether the map contains the specified key. + * + * @param key the key to search for + * @return true if the map contains the key + */ + public boolean containsKey(Object key) { + int hashCode = hash((key == null) ? NULL : key); + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + while (entry != null) { + if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { + return true; + } + entry = entry.next; + } + return false; + } + + /** + * Checks whether the map contains the specified value. + * + * @param value the value to search for + * @return true if the map contains the value + */ + public boolean containsValue(Object value) { + if (value == null) { + for (int i = 0, isize = data.length; i < isize; i++) { + HashEntry entry = data[i]; + while (entry != null) { + if (entry.getValue() == null) { + return true; + } + entry = entry.next; + } + } + } else { + for (int i = 0, isize = data.length; i < isize; i++) { + HashEntry entry = data[i]; + while (entry != null) { + if (isEqualValue(value, entry.getValue())) { + return true; + } + entry = entry.next; + } + } + } + return false; + } + + //----------------------------------------------------------------------- + /** + * Puts a key-value mapping into this map. + * + * @param key the key to add + * @param value the value to add + * @return the value previously mapped to this key, null if none + */ + public V put(K key, V value) { + int hashCode = hash((key == null) ? NULL : key); + int index = hashIndex(hashCode, data.length); + HashEntry entry = data[index]; + while (entry != null) { + if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { + V oldValue = entry.getValue(); + updateEntry(entry, value); + return oldValue; + } + entry = entry.next; + } + addMapping(index, hashCode, key, value); + return null; + } + + /** + * Puts all the values from the specified map into this map. + *

+ * This implementation iterates around the specified map and + * uses {@link #put(Object, Object)}. + * + * @param map the map to add + * @throws NullPointerException if the map is null + */ + public void putAll(Map map) { + int mapSize = map.size(); + if (mapSize == 0) { + return; + } + int newSize = (int) ((size + mapSize) / loadFactor + 1); + ensureCapacity(calculateNewCapacity(newSize)); + // Have to cast here because of compiler inference problems. + for (Iterator it = map.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + put(entry.getKey(), entry.getValue()); + } + } + + /** + * Removes the specified mapping from this map. + * + * @param key the mapping to remove + * @return the value mapped to the removed key, null if key not in map + */ + public V remove(Object key) { + int hashCode = hash((key == null) ? NULL : key); + int index = hashIndex(hashCode, data.length); + HashEntry entry = data[index]; + HashEntry previous = null; + while (entry != null) { + if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { + V oldValue = entry.getValue(); + removeMapping(entry, index, previous); + return oldValue; + } + previous = entry; + entry = entry.next; + } + return null; + } + + /** + * Clears the map, resetting the size to zero and nullifying references + * to avoid garbage collection issues. + */ + public void clear() { + modCount++; + HashEntry[] data = this.data; + for (int i = data.length - 1; i >= 0; i--) { + data[i] = null; + } + size = 0; + } + + /** + * Gets the hash code for the key specified. + * This implementation uses the additional hashing routine from JDK1.4. + * Subclasses can override this to return alternate hash codes. + * + * @param key the key to get a hash code for + * @return the hash code + */ + protected int hash(Object key) { + // same as JDK 1.4 + int h = key.hashCode(); + h += ~(h << 9); + h ^= (h >>> 14); + h += (h << 4); + h ^= (h >>> 10); + return h; + } + + /** + * Compares two keys, in internal converted form, to see if they are equal. + * This implementation uses the equals method. + * Subclasses can override this to match differently. + * + * @param key1 the first key to compare passed in from outside + * @param key2 the second key extracted from the entry via entry.key + * @return true if equal + */ + protected boolean isEqualKey(Object key1, Object key2) { + return (key1 == key2 || ((key1 != null) && key1.equals(key2))); + } + + /** + * Compares two values, in external form, to see if they are equal. + * This implementation uses the equals method and assumes neither value is null. + * Subclasses can override this to match differently. + * + * @param value1 the first value to compare passed in from outside + * @param value2 the second value extracted from the entry via getValue() + * @return true if equal + */ + protected boolean isEqualValue(Object value1, Object value2) { + return (value1 == value2 || value1.equals(value2)); + } + + /** + * Gets the index into the data storage for the hashCode specified. + * This implementation uses the least significant bits of the hashCode. + * Subclasses can override this to return alternate bucketing. + * + * @param hashCode the hash code to use + * @param dataSize the size of the data to pick a bucket from + * @return the bucket index + */ + protected int hashIndex(int hashCode, int dataSize) { + return hashCode & (dataSize - 1); + } + + //----------------------------------------------------------------------- + /** + * Gets the entry mapped to the key specified. + *

+ * This method exists for subclasses that may need to perform a multi-step + * process accessing the entry. The public methods in this class don't use this + * method to gain a small performance boost. + * + * @param key the key + * @return the entry, null if no match + */ + protected HashEntry getEntry(Object key) { + int hashCode = hash((key == null) ? NULL : key); + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + while (entry != null) { + if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) { + return entry; + } + entry = entry.next; + } + return null; + } + + //----------------------------------------------------------------------- + /** + * Updates an existing key-value mapping to change the value. + *

+ * This implementation calls setValue() on the entry. + * Subclasses could override to handle changes to the map. + * + * @param entry the entry to update + * @param newValue the new value to store + */ + protected void updateEntry(HashEntry entry, V newValue) { + entry.setValue(newValue); + } + + /** + * Reuses an existing key-value mapping, storing completely new data. + *

+ * This implementation sets all the data fields on the entry. + * Subclasses could populate additional entry fields. + * + * @param entry the entry to update, not null + * @param hashIndex the index in the data array + * @param hashCode the hash code of the key to add + * @param key the key to add + * @param value the value to add + */ + protected void reuseEntry(HashEntry entry, int hashIndex, int hashCode, K key, V value) { + entry.next = data[hashIndex]; + entry.hashCode = hashCode; + entry.key = key; + entry.value = value; + } + + //----------------------------------------------------------------------- + /** + * Adds a new key-value mapping into this map. + *

+ * This implementation calls createEntry(), addEntry() + * and checkCapacity(). + * It also handles changes to modCount and size. + * Subclasses could override to fully control adds to the map. + * + * @param hashIndex the index into the data array to store at + * @param hashCode the hash code of the key to add + * @param key the key to add + * @param value the value to add + */ + protected void addMapping(int hashIndex, int hashCode, K key, V value) { + modCount++; + HashEntry entry = createEntry(data[hashIndex], hashCode, key, value); + addEntry(entry, hashIndex); + size++; + checkCapacity(); + } + + /** + * Creates an entry to store the key-value data. + *

+ * This implementation creates a new HashEntry instance. + * Subclasses can override this to return a different storage class, + * or implement caching. + * + * @param next the next entry in sequence + * @param hashCode the hash code to use + * @param key the key to store + * @param value the value to store + * @return the newly created entry + */ + protected HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new HashEntry(next, hashCode, key, value); + } + + /** + * Adds an entry into this map. + *

+ * This implementation adds the entry to the data storage table. + * Subclasses could override to handle changes to the map. + * + * @param entry the entry to add + * @param hashIndex the index into the data array to store at + */ + protected void addEntry(HashEntry entry, int hashIndex) { + data[hashIndex] = entry; + } + + //----------------------------------------------------------------------- + /** + * Removes a mapping from the map. + *

+ * This implementation calls removeEntry() and destroyEntry(). + * It also handles changes to modCount and size. + * Subclasses could override to fully control removals from the map. + * + * @param entry the entry to remove + * @param hashIndex the index into the data structure + * @param previous the previous entry in the chain + */ + protected void removeMapping(HashEntry entry, int hashIndex, HashEntry previous) { + modCount++; + removeEntry(entry, hashIndex, previous); + size--; + destroyEntry(entry); + } + + /** + * Removes an entry from the chain stored in a particular index. + *

+ * This implementation removes the entry from the data storage table. + * The size is not updated. + * Subclasses could override to handle changes to the map. + * + * @param entry the entry to remove + * @param hashIndex the index into the data structure + * @param previous the previous entry in the chain + */ + protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { + if (previous == null) { + data[hashIndex] = entry.next; + } else { + previous.next = entry.next; + } + } + + /** + * Kills an entry ready for the garbage collector. + *

+ * This implementation prepares the HashEntry for garbage collection. + * Subclasses can override this to implement caching (override clear as well). + * + * @param entry the entry to destroy + */ + protected void destroyEntry(HashEntry entry) { + entry.next = null; + entry.key = null; + entry.value = null; + } + + //----------------------------------------------------------------------- + /** + * Checks the capacity of the map and enlarges it if necessary. + *

+ * This implementation uses the threshold to check if the map needs enlarging + */ + protected void checkCapacity() { + if (size >= threshold) { + int newCapacity = data.length * 2; + if (newCapacity <= MAXIMUM_CAPACITY) { + ensureCapacity(newCapacity); + } + } + } + + /** + * Changes the size of the data structure to the capacity proposed. + * + * @param newCapacity the new capacity of the array (a power of two, less or equal to max) + */ + protected void ensureCapacity(int newCapacity) { + int oldCapacity = data.length; + if (newCapacity <= oldCapacity) { + return; + } + if (size == 0) { + threshold = calculateThreshold(newCapacity, loadFactor); + data = new HashEntry[newCapacity]; + } else { + HashEntry oldEntries[] = data; + HashEntry newEntries[] = new HashEntry[newCapacity]; + + modCount++; + for (int i = oldCapacity - 1; i >= 0; i--) { + HashEntry entry = oldEntries[i]; + if (entry != null) { + oldEntries[i] = null; // gc + do { + HashEntry next = entry.next; + int index = hashIndex(entry.hashCode, newCapacity); + entry.next = newEntries[index]; + newEntries[index] = entry; + entry = next; + } while (entry != null); + } + } + threshold = calculateThreshold(newCapacity, loadFactor); + data = newEntries; + } + } + + /** + * Calculates the new capacity of the map. + * This implementation normalizes the capacity to a power of two. + * + * @param proposedCapacity the proposed capacity + * @return the normalized new capacity + */ + protected int calculateNewCapacity(int proposedCapacity) { + int newCapacity = 1; + if (proposedCapacity > MAXIMUM_CAPACITY) { + newCapacity = MAXIMUM_CAPACITY; + } else { + while (newCapacity < proposedCapacity) { + newCapacity <<= 1; // multiply by two + } + if (newCapacity > MAXIMUM_CAPACITY) { + newCapacity = MAXIMUM_CAPACITY; + } + } + return newCapacity; + } + + /** + * Calculates the new threshold of the map, where it will be resized. + * This implementation uses the load factor. + * + * @param newCapacity the new capacity + * @param factor the load factor + * @return the new resize threshold + */ + protected int calculateThreshold(int newCapacity, float factor) { + return (int) (newCapacity * factor); + } + + //----------------------------------------------------------------------- + /** + * Gets the next field from a HashEntry. + * Used in subclasses that have no visibility of the field. + * + * @param entry the entry to query, must not be null + * @return the next field of the entry + * @throws NullPointerException if the entry is null + * @since Commons Collections 3.1 + */ + protected HashEntry entryNext(HashEntry entry) { + return entry.next; + } + + /** + * Gets the hashCode field from a HashEntry. + * Used in subclasses that have no visibility of the field. + * + * @param entry the entry to query, must not be null + * @return the hashCode field of the entry + * @throws NullPointerException if the entry is null + * @since Commons Collections 3.1 + */ + protected int entryHashCode(HashEntry entry) { + return entry.hashCode; + } + + /** + * Gets the key field from a HashEntry. + * Used in subclasses that have no visibility of the field. + * + * @param entry the entry to query, must not be null + * @return the key field of the entry + * @throws NullPointerException if the entry is null + * @since Commons Collections 3.1 + */ + protected K entryKey(HashEntry entry) { + return entry.key; + } + + /** + * Gets the value field from a HashEntry. + * Used in subclasses that have no visibility of the field. + * + * @param entry the entry to query, must not be null + * @return the value field of the entry + * @throws NullPointerException if the entry is null + * @since Commons Collections 3.1 + */ + protected V entryValue(HashEntry entry) { + return entry.value; + } + + //----------------------------------------------------------------------- + /** + * Gets an iterator over the map. + * Changes made to the iterator affect this map. + *

+ * A MapIterator returns the keys in the map. It also provides convenient + * methods to get the key and value, and set the value. + * It avoids the need to create an entrySet/keySet/values object. + * It also avoids creating the Map.Entry object. + * + * @return the map iterator + */ + public MapIterator mapIterator() { + if (size == 0) { + return EmptyMapIterator.INSTANCE; + } + return new HashMapIterator(this); + } + + /** + * MapIterator implementation. + */ + protected static class HashMapIterator extends HashIterator implements MapIterator { + + protected HashMapIterator(AbstractHashedMap parent) { + super(parent); + } + + public K next() { + return super.nextEntry().getKey(); + } + + public K getKey() { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); + } + return current.getKey(); + } + + public V getValue() { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); + } + return current.getValue(); + } + + public V setValue(V value) { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); + } + return current.setValue(value); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the entrySet view of the map. + * Changes made to the view affect this map. + * To simply iterate through the entries, use {@link #mapIterator()}. + * + * @return the entrySet view + */ + public Set> entrySet() { + if (entrySet == null) { + entrySet = new EntrySet(this); + } + return entrySet; + } + + /** + * Creates an entry set iterator. + * Subclasses can override this to return iterators with different properties. + * + * @return the entrySet iterator + */ + protected Iterator> createEntrySetIterator() { + if (size() == 0) { + return EmptyIterator.INSTANCE; + } + return new EntrySetIterator(this); + } + + /** + * EntrySet implementation. + */ + protected static class EntrySet extends AbstractSet> { + /** + * The parent map + */ + protected final AbstractHashedMap parent; + + protected EntrySet(AbstractHashedMap parent) { + super(); + this.parent = parent; + } + + public int size() { + return parent.size(); + } + + public void clear() { + parent.clear(); + } + + public boolean contains(Map.Entry entry) { + Map.Entry e = entry; + Entry match = parent.getEntry(e.getKey()); + return (match != null && match.equals(e)); + } + + public boolean remove(Object obj) { + if (obj instanceof Map.Entry == false) { + return false; + } + if (contains(obj) == false) { + return false; + } + Map.Entry entry = (Map.Entry) obj; + K key = entry.getKey(); + parent.remove(key); + return true; + } + + public Iterator> iterator() { + return parent.createEntrySetIterator(); + } + } + + /** + * EntrySet iterator. + */ + protected static class EntrySetIterator extends HashIterator implements Iterator> { + + protected EntrySetIterator(AbstractHashedMap parent) { + super(parent); + } + + public HashEntry next() { + return super.nextEntry(); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the keySet view of the map. + * Changes made to the view affect this map. + * To simply iterate through the keys, use {@link #mapIterator()}. + * + * @return the keySet view + */ + public Set keySet() { + if (keySet == null) { + keySet = new KeySet(this); + } + return keySet; + } + + /** + * Creates a key set iterator. + * Subclasses can override this to return iterators with different properties. + * + * @return the keySet iterator + */ + protected Iterator createKeySetIterator() { + if (size() == 0) { + return EmptyIterator.INSTANCE; + } + return new KeySetIterator(this); + } + + /** + * KeySet implementation. + */ + protected static class KeySet extends AbstractSet { + /** + * The parent map + */ + protected final AbstractHashedMap parent; + + protected KeySet(AbstractHashedMap parent) { + super(); + this.parent = parent; + } + + public int size() { + return parent.size(); + } + + public void clear() { + parent.clear(); + } + + public boolean contains(Object key) { + return parent.containsKey(key); + } + + public boolean remove(Object key) { + boolean result = parent.containsKey(key); + parent.remove(key); + return result; + } + + public Iterator iterator() { + return parent.createKeySetIterator(); + } + } + + /** + * KeySet iterator. + */ + protected static class KeySetIterator extends HashIterator implements Iterator { + + protected KeySetIterator(AbstractHashedMap parent) { + super(parent); + } + + public K next() { + return super.nextEntry().getKey(); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the values view of the map. + * Changes made to the view affect this map. + * To simply iterate through the values, use {@link #mapIterator()}. + * + * @return the values view + */ + public Collection values() { + if (values == null) { + values = new Values(this); + } + return values; + } + + /** + * Creates a values iterator. + * Subclasses can override this to return iterators with different properties. + * + * @return the values iterator + */ + protected Iterator createValuesIterator() { + if (size() == 0) { + return EmptyIterator.INSTANCE; + } + return new ValuesIterator(this); + } + + /** + * Values implementation. + */ + protected static class Values extends AbstractCollection { + /** + * The parent map + */ + protected final AbstractHashedMap parent; + + protected Values(AbstractHashedMap parent) { + super(); + this.parent = parent; + } + + public int size() { + return parent.size(); + } + + public void clear() { + parent.clear(); + } + + public boolean contains(Object value) { + return parent.containsValue(value); + } + + public Iterator iterator() { + return parent.createValuesIterator(); + } + } + + /** + * Values iterator. + */ + protected static class ValuesIterator extends HashIterator implements Iterator { + + protected ValuesIterator(AbstractHashedMap parent) { + super(parent); + } + + public V next() { + return super.nextEntry().getValue(); + } + } + + //----------------------------------------------------------------------- + /** + * HashEntry used to store the data. + *

+ * If you subclass AbstractHashedMap but not HashEntry + * then you will not be able to access the protected fields. + * The entryXxx() methods on AbstractHashedMap exist + * to provide the necessary access. + */ + protected static class HashEntry implements Map.Entry, KeyValue { + /** + * The next entry in the hash chain + */ + protected HashEntry next; + /** + * The hash code of the key + */ + protected int hashCode; + /** + * The key + */ + private K key; + /** + * The value + */ + private V value; + + protected HashEntry(HashEntry next, int hashCode, K key, V value) { + super(); + this.next = next; + this.hashCode = hashCode; + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public void setKey(K key) { + this.key = key; + } + + public V getValue() { + return value; + } + + public V setValue(V value) { + V old = this.value; + this.value = value; + return old; + } + + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Map.Entry == false) { + return false; + } + Map.Entry other = (Map.Entry) obj; + return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); + } + + public int hashCode() { + return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); + } + + public String toString() { + return new StringBuffer().append(getKey()).append('=').append(getValue()).toString(); + } + } + + /** + * Base Iterator + */ + protected static abstract class HashIterator { + + /** + * The parent map + */ + protected final AbstractHashedMap parent; + /** + * The current index into the array of buckets + */ + protected int hashIndex; + /** + * The last returned entry + */ + protected HashEntry last; + /** + * The next entry + */ + protected HashEntry next; + /** + * The modification count expected + */ + protected int expectedModCount; + + protected HashIterator(AbstractHashedMap parent) { + super(); + this.parent = parent; + HashEntry[] data = parent.data; + int i = data.length; + HashEntry next = null; + while (i > 0 && next == null) { + next = data[--i]; + } + this.next = next; + this.hashIndex = i; + this.expectedModCount = parent.modCount; + } + + public boolean hasNext() { + return (next != null); + } + + protected HashEntry nextEntry() { + if (parent.modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + HashEntry newCurrent = next; + if (newCurrent == null) { + throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); + } + HashEntry[] data = parent.data; + int i = hashIndex; + HashEntry n = newCurrent.next; + while (n == null && i > 0) { + n = data[--i]; + } + next = n; + hashIndex = i; + last = newCurrent; + return newCurrent; + } + + protected HashEntry currentEntry() { + return last; + } + + public void remove() { + if (last == null) { + throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); + } + if (parent.modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + parent.remove(last.getKey()); + last = null; + expectedModCount = parent.modCount; + } + + public String toString() { + if (last != null) { + return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; + } else { + return "Iterator[]"; + } + } + } + + //----------------------------------------------------------------------- + /** + * Writes the map data to the stream. This method must be overridden if a + * subclass must be setup before put() is used. + *

+ * Serialization is not one of the JDK's nicest topics. Normal serialization will + * initialise the superclass before the subclass. Sometimes however, this isn't + * what you want, as in this case the put() method on read can be + * affected by subclass state. + *

+ * The solution adopted here is to serialize the state data of this class in + * this protected method. This method must be called by the + * writeObject() of the first serializable subclass. + *

+ * Subclasses may override if they have a specific field that must be present + * on read before this implementation will work. Generally, the read determines + * what must be serialized here, if anything. + * + * @param out the output stream + */ + protected void doWriteObject(ObjectOutputStream out) throws IOException { + out.writeFloat(loadFactor); + out.writeInt(data.length); + out.writeInt(size); + for (MapIterator it = mapIterator(); it.hasNext();) { + out.writeObject(it.next()); + out.writeObject(it.getValue()); + } + } + + /** + * Reads the map data from the stream. This method must be overridden if a + * subclass must be setup before put() is used. + *

+ * Serialization is not one of the JDK's nicest topics. Normal serialization will + * initialise the superclass before the subclass. Sometimes however, this isn't + * what you want, as in this case the put() method on read can be + * affected by subclass state. + *

+ * The solution adopted here is to deserialize the state data of this class in + * this protected method. This method must be called by the + * readObject() of the first serializable subclass. + *

+ * Subclasses may override if the subclass has a specific field that must be present + * before put() or calculateThreshold() will work correctly. + * + * @param in the input stream + */ + protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + loadFactor = in.readFloat(); + int capacity = in.readInt(); + int size = in.readInt(); + init(); + data = new HashEntry[capacity]; + for (int i = 0; i < size; i++) { + K key = (K) in.readObject(); + V value = (V) in.readObject(); + put(key, value); + } + threshold = calculateThreshold(data.length, loadFactor); + } + + //----------------------------------------------------------------------- + /** + * Clones the map without cloning the keys or values. + *

+ * To implement clone(), a subclass must implement the + * Cloneable interface and make this method public. + * + * @return a shallow clone + */ + protected Object clone() { + try { + AbstractHashedMap cloned = (AbstractHashedMap) super.clone(); + cloned.data = new HashEntry[data.length]; + cloned.entrySet = null; + cloned.keySet = null; + cloned.values = null; + cloned.modCount = 0; + cloned.size = 0; + cloned.init(); + cloned.putAll(this); + return cloned; + + } catch (CloneNotSupportedException ex) { + return null; // should never happen + } + } + + /** + * Compares this map with another. + * + * @param obj the object to compare to + * @return true if equal + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Map == false) { + return false; + } + Map map = (Map) obj; + if (map.size() != size()) { + return false; + } + MapIterator it = mapIterator(); + try { + while (it.hasNext()) { + Object key = it.next(); + Object value = it.getValue(); + if (value == null) { + if (map.get(key) != null || map.containsKey(key) == false) { + return false; + } + } else { + if (value.equals(map.get(key)) == false) { + return false; + } + } + } + } catch (ClassCastException ignored) { + return false; + } catch (NullPointerException ignored) { + return false; + } + return true; + } + + /** + * Gets the standard Map hashCode. + * + * @return the hash code defined in the Map interface + */ + public int hashCode() { + int total = 0; + Iterator it = createEntrySetIterator(); + while (it.hasNext()) { + total += it.next().hashCode(); + } + return total; + } + + /** + * Gets the map as a String. + * + * @return a string version of the map + */ + public String toString() { + if (size() == 0) { + return "{}"; + } + StringBuffer buf = new StringBuffer(32 * size()); + buf.append('{'); + + MapIterator it = mapIterator(); + boolean hasNext = it.hasNext(); + while (hasNext) { + Object key = it.next(); + Object value = it.getValue(); + buf.append(key == this ? "(this Map)" : key).append('=').append(value == this ? "(this Map)" : value); + + hasNext = it.hasNext(); + if (hasNext) { + buf.append(',').append(' '); + } + } + + buf.append('}'); + return buf.toString(); + } +} diff --git a/source/org/jivesoftware/smack/util/collections/AbstractKeyValue.java b/source/org/jivesoftware/smack/util/collections/AbstractKeyValue.java new file mode 100644 index 000000000..d06452af6 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/AbstractKeyValue.java @@ -0,0 +1,80 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + + +/** + * Abstract pair class to assist with creating KeyValue and MapEntry implementations. + * + * @author James Strachan + * @author Michael A. Smith + * @author Neil O'Toole + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @since Commons Collections 3.0 + */ +public abstract class AbstractKeyValue implements KeyValue { + + /** + * The key + */ + protected K key; + /** + * The value + */ + protected V value; + + /** + * Constructs a new pair with the specified key and given value. + * + * @param key the key for the entry, may be null + * @param value the value for the entry, may be null + */ + protected AbstractKeyValue(K key, V value) { + super(); + this.key = key; + this.value = value; + } + + /** + * Gets the key from the pair. + * + * @return the key + */ + public K getKey() { + return key; + } + + /** + * Gets the value from the pair. + * + * @return the value + */ + public V getValue() { + return value; + } + + /** + * Gets a debugging String view of the pair. + * + * @return a String view of the entry + */ + public String toString() { + return new StringBuffer().append(getKey()).append('=').append(getValue()).toString(); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/AbstractMapEntry.java b/source/org/jivesoftware/smack/util/collections/AbstractMapEntry.java new file mode 100644 index 000000000..2feb30846 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/AbstractMapEntry.java @@ -0,0 +1,89 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.Map; + +/** + * Abstract Pair class to assist with creating correct Map Entry implementations. + * + * @author James Strachan + * @author Michael A. Smith + * @author Neil O'Toole + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @since Commons Collections 3.0 + */ +public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { + + /** + * Constructs a new entry with the given key and given value. + * + * @param key the key for the entry, may be null + * @param value the value for the entry, may be null + */ + protected AbstractMapEntry(K key, V value) { + super(key, value); + } + + // Map.Entry interface + //------------------------------------------------------------------------- + /** + * Sets the value stored in this Map Entry. + *

+ * This Map Entry is not connected to a Map, so only the local data is changed. + * + * @param value the new value + * @return the previous value + */ + public V setValue(V value) { + V answer = this.value; + this.value = value; + return answer; + } + + /** + * Compares this Map Entry with another Map Entry. + *

+ * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)} + * + * @param obj the object to compare to + * @return true if equal key and value + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Map.Entry == false) { + return false; + } + Map.Entry other = (Map.Entry) obj; + return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); + } + + /** + * Gets a hashCode compatible with the equals method. + *

+ * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()} + * + * @return a suitable hash code + */ + public int hashCode() { + return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/AbstractReferenceMap.java b/source/org/jivesoftware/smack/util/collections/AbstractReferenceMap.java new file mode 100644 index 000000000..b57f17d7d --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/AbstractReferenceMap.java @@ -0,0 +1,1025 @@ +// Converted, with some major refactors required. Not as memory-efficient as before, could use additional refactoring. +// Perhaps use four different types of HashEntry classes for max efficiency: +// normal HashEntry for HARD,HARD +// HardRefEntry for HARD,(SOFT|WEAK) +// RefHardEntry for (SOFT|WEAK),HARD +// RefRefEntry for (SOFT|WEAK),(SOFT|WEAK) +/* + * Copyright 2002-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; +import java.util.*; + +/** + * An abstract implementation of a hash-based map that allows the entries to + * be removed by the garbage collector. + *

+ * This class implements all the features necessary for a subclass reference + * hash-based map. Key-value entries are stored in instances of the + * ReferenceEntry class which can be overridden and replaced. + * The iterators can similarly be replaced, without the need to replace the KeySet, + * EntrySet and Values view classes. + *

+ * Overridable methods are provided to change the default hashing behaviour, and + * to change how entries are added to and removed from the map. Hopefully, all you + * need for unusual subclasses is here. + *

+ * When you construct an AbstractReferenceMap, you can specify what + * kind of references are used to store the map's keys and values. + * If non-hard references are used, then the garbage collector can remove + * mappings if a key or value becomes unreachable, or if the JVM's memory is + * running low. For information on how the different reference types behave, + * see {@link Reference}. + *

+ * Different types of references can be specified for keys and values. + * The keys can be configured to be weak but the values hard, + * in which case this class will behave like a + * + * WeakHashMap. However, you can also specify hard keys and + * weak values, or any other combination. The default constructor uses + * hard keys and soft values, providing a memory-sensitive cache. + *

+ * This {@link Map} implementation does not allow null elements. + * Attempting to add a null key or value to the map will raise a + * NullPointerException. + *

+ * All the available iterators can be reset back to the start by casting to + * ResettableIterator and calling reset(). + *

+ * This implementation is not synchronized. + * You can use {@link java.util.Collections#synchronizedMap} to + * provide synchronized access to a ReferenceMap. + * + * @author Paul Jack + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @see java.lang.ref.Reference + * @since Commons Collections 3.1 (extracted from ReferenceMap in 3.0) + */ +public abstract class AbstractReferenceMap extends AbstractHashedMap { + + /** + * Constant indicating that hard references should be used + */ + public static final int HARD = 0; + + /** + * Constant indicating that soft references should be used + */ + public static final int SOFT = 1; + + /** + * Constant indicating that weak references should be used + */ + public static final int WEAK = 2; + + /** + * The reference type for keys. Must be HARD, SOFT, WEAK. + * + * @serial + */ + protected int keyType; + + /** + * The reference type for values. Must be HARD, SOFT, WEAK. + * + * @serial + */ + protected int valueType; + + /** + * Should the value be automatically purged when the associated key has been collected? + */ + protected boolean purgeValues; + + /** + * ReferenceQueue used to eliminate stale mappings. + * See purge. + */ + private transient ReferenceQueue queue; + + //----------------------------------------------------------------------- + /** + * Constructor used during deserialization. + */ + protected AbstractReferenceMap() { + super(); + } + + /** + * Constructs a new empty map with the specified reference types, + * load factor and initial capacity. + * + * @param keyType the type of reference to use for keys; + * must be {@link #SOFT} or {@link #WEAK} + * @param valueType the type of reference to use for values; + * must be {@link #SOFT} or {@link #WEAK} + * @param capacity the initial capacity for the map + * @param loadFactor the load factor for the map + * @param purgeValues should the value be automatically purged when the + * key is garbage collected + */ + protected AbstractReferenceMap(int keyType, int valueType, int capacity, float loadFactor, boolean purgeValues) { + super(capacity, loadFactor); + verify("keyType", keyType); + verify("valueType", valueType); + this.keyType = keyType; + this.valueType = valueType; + this.purgeValues = purgeValues; + } + + /** + * Initialise this subclass during construction, cloning or deserialization. + */ + protected void init() { + queue = new ReferenceQueue(); + } + + //----------------------------------------------------------------------- + /** + * Checks the type int is a valid value. + * + * @param name the name for error messages + * @param type the type value to check + * @throws IllegalArgumentException if the value if invalid + */ + private static void verify(String name, int type) { + if ((type < HARD) || (type > WEAK)) { + throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the size of the map. + * + * @return the size + */ + public int size() { + purgeBeforeRead(); + return super.size(); + } + + /** + * Checks whether the map is currently empty. + * + * @return true if the map is currently size zero + */ + public boolean isEmpty() { + purgeBeforeRead(); + return super.isEmpty(); + } + + /** + * Checks whether the map contains the specified key. + * + * @param key the key to search for + * @return true if the map contains the key + */ + public boolean containsKey(Object key) { + purgeBeforeRead(); + Entry entry = getEntry(key); + if (entry == null) { + return false; + } + return (entry.getValue() != null); + } + + /** + * Checks whether the map contains the specified value. + * + * @param value the value to search for + * @return true if the map contains the value + */ + public boolean containsValue(Object value) { + purgeBeforeRead(); + if (value == null) { + return false; + } + return super.containsValue(value); + } + + /** + * Gets the value mapped to the key specified. + * + * @param key the key + * @return the mapped value, null if no match + */ + public V get(Object key) { + purgeBeforeRead(); + Entry entry = getEntry(key); + if (entry == null) { + return null; + } + return entry.getValue(); + } + + + /** + * Puts a key-value mapping into this map. + * Neither the key nor the value may be null. + * + * @param key the key to add, must not be null + * @param value the value to add, must not be null + * @return the value previously mapped to this key, null if none + * @throws NullPointerException if either the key or value is null + */ + public V put(K key, V value) { + if (key == null) { + throw new NullPointerException("null keys not allowed"); + } + if (value == null) { + throw new NullPointerException("null values not allowed"); + } + + purgeBeforeWrite(); + return super.put(key, value); + } + + /** + * Removes the specified mapping from this map. + * + * @param key the mapping to remove + * @return the value mapped to the removed key, null if key not in map + */ + public V remove(Object key) { + if (key == null) { + return null; + } + purgeBeforeWrite(); + return super.remove(key); + } + + /** + * Clears this map. + */ + public void clear() { + super.clear(); + while (queue.poll() != null) { + } // drain the queue + } + + //----------------------------------------------------------------------- + /** + * Gets a MapIterator over the reference map. + * The iterator only returns valid key/value pairs. + * + * @return a map iterator + */ + public MapIterator mapIterator() { + return new ReferenceMapIterator(this); + } + + /** + * Returns a set view of this map's entries. + * An iterator returned entry is valid until next() is called again. + * The setValue() method on the toArray entries has no effect. + * + * @return a set view of this map's entries + */ + public Set> entrySet() { + if (entrySet == null) { + entrySet = new ReferenceEntrySet(this); + } + return entrySet; + } + + /** + * Returns a set view of this map's keys. + * + * @return a set view of this map's keys + */ + public Set keySet() { + if (keySet == null) { + keySet = new ReferenceKeySet(this); + } + return keySet; + } + + /** + * Returns a collection view of this map's values. + * + * @return a set view of this map's values + */ + public Collection values() { + if (values == null) { + values = new ReferenceValues(this); + } + return values; + } + + //----------------------------------------------------------------------- + /** + * Purges stale mappings from this map before read operations. + *

+ * This implementation calls {@link #purge()} to maintain a consistent state. + */ + protected void purgeBeforeRead() { + purge(); + } + + /** + * Purges stale mappings from this map before write operations. + *

+ * This implementation calls {@link #purge()} to maintain a consistent state. + */ + protected void purgeBeforeWrite() { + purge(); + } + + /** + * Purges stale mappings from this map. + *

+ * Note that this method is not synchronized! Special + * care must be taken if, for instance, you want stale + * mappings to be removed on a periodic basis by some + * background thread. + */ + protected void purge() { + Reference ref = queue.poll(); + while (ref != null) { + purge(ref); + ref = queue.poll(); + } + } + + /** + * Purges the specified reference. + * + * @param ref the reference to purge + */ + protected void purge(Reference ref) { + // The hashCode of the reference is the hashCode of the + // mapping key, even if the reference refers to the + // mapping value... + int hash = ref.hashCode(); + int index = hashIndex(hash, data.length); + HashEntry previous = null; + HashEntry entry = data[index]; + while (entry != null) { + if (((ReferenceEntry) entry).purge(ref)) { + if (previous == null) { + data[index] = entry.next; + } else { + previous.next = entry.next; + } + this.size--; + return; + } + previous = entry; + entry = entry.next; + } + + } + + //----------------------------------------------------------------------- + /** + * Gets the entry mapped to the key specified. + * + * @param key the key + * @return the entry, null if no match + */ + protected HashEntry getEntry(Object key) { + if (key == null) { + return null; + } else { + return super.getEntry(key); + } + } + + /** + * Gets the hash code for a MapEntry. + * Subclasses can override this, for example to use the identityHashCode. + * + * @param key the key to get a hash code for, may be null + * @param value the value to get a hash code for, may be null + * @return the hash code, as per the MapEntry specification + */ + protected int hashEntry(Object key, Object value) { + return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); + } + + /** + * Compares two keys, in internal converted form, to see if they are equal. + *

+ * This implementation converts the key from the entry to a real reference + * before comparison. + * + * @param key1 the first key to compare passed in from outside + * @param key2 the second key extracted from the entry via entry.key + * @return true if equal + */ + protected boolean isEqualKey(Object key1, Object key2) { + //if ((key1 == null) && (key2 != null) || (key1 != null) || (key2 == null)) { + // return false; + //} + // GenericsNote: Conversion from reference handled by getKey() which replaced all .key references + //key2 = (keyType > HARD ? ((Reference) key2).get() : key2); + return (key1 == key2 || key1.equals(key2)); + } + + /** + * Creates a ReferenceEntry instead of a HashEntry. + * + * @param next the next entry in sequence + * @param hashCode the hash code to use + * @param key the key to store + * @param value the value to store + * @return the newly created entry + */ + public HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new ReferenceEntry(this, (ReferenceEntry) next, hashCode, key, value); + } + + /** + * Creates an entry set iterator. + * + * @return the entrySet iterator + */ + protected Iterator> createEntrySetIterator() { + return new ReferenceEntrySetIterator(this); + } + + /** + * Creates an key set iterator. + * + * @return the keySet iterator + */ + protected Iterator createKeySetIterator() { + return new ReferenceKeySetIterator(this); + } + + /** + * Creates an values iterator. + * + * @return the values iterator + */ + protected Iterator createValuesIterator() { + return new ReferenceValuesIterator(this); + } + + //----------------------------------------------------------------------- + /** + * EntrySet implementation. + */ + static class ReferenceEntrySet extends EntrySet { + + protected ReferenceEntrySet(AbstractHashedMap parent) { + super(parent); + } + + public Object[] toArray() { + return toArray(new Object[0]); + } + + public T[] toArray(T[] arr) { + // special implementation to handle disappearing entries + ArrayList> list = new ArrayList>(); + Iterator> iterator = iterator(); + while (iterator.hasNext()) { + Map.Entry e = iterator.next(); + list.add(new DefaultMapEntry(e.getKey(), e.getValue())); + } + return list.toArray(arr); + } + } + + //----------------------------------------------------------------------- + /** + * KeySet implementation. + */ + static class ReferenceKeySet extends KeySet { + + protected ReferenceKeySet(AbstractHashedMap parent) { + super(parent); + } + + public Object[] toArray() { + return toArray(new Object[0]); + } + + public T[] toArray(T[] arr) { + // special implementation to handle disappearing keys + List list = new ArrayList(parent.size()); + for (Iterator it = iterator(); it.hasNext();) { + list.add(it.next()); + } + return list.toArray(arr); + } + } + + //----------------------------------------------------------------------- + /** + * Values implementation. + */ + static class ReferenceValues extends Values { + + protected ReferenceValues(AbstractHashedMap parent) { + super(parent); + } + + public Object[] toArray() { + return toArray(new Object[0]); + } + + public T[] toArray(T[] arr) { + // special implementation to handle disappearing values + List list = new ArrayList(parent.size()); + for (Iterator it = iterator(); it.hasNext();) { + list.add(it.next()); + } + return list.toArray(arr); + } + } + + //----------------------------------------------------------------------- + /** + * A MapEntry implementation for the map. + *

+ * If getKey() or getValue() returns null, it means + * the mapping is stale and should be removed. + * + * @since Commons Collections 3.1 + */ + protected static class ReferenceEntry extends HashEntry { + /** + * The parent map + */ + protected final AbstractReferenceMap parent; + + protected Reference refKey; + protected Reference refValue; + + /** + * Creates a new entry object for the ReferenceMap. + * + * @param parent the parent map + * @param next the next entry in the hash bucket + * @param hashCode the hash code of the key + * @param key the key + * @param value the value + */ + public ReferenceEntry(AbstractReferenceMap parent, ReferenceEntry next, int hashCode, K key, V value) { + super(next, hashCode, null, null); + this.parent = parent; + if (parent.keyType != HARD) { + refKey = toReference(parent.keyType, key, hashCode); + } else { + this.setKey(key); + } + if (parent.valueType != HARD) { + refValue = toReference(parent.valueType, value, hashCode); // the key hashCode is passed in deliberately + } else { + this.setValue(value); + } + } + + /** + * Gets the key from the entry. + * This method dereferences weak and soft keys and thus may return null. + * + * @return the key, which may be null if it was garbage collected + */ + public K getKey() { + return (parent.keyType > HARD) ? refKey.get() : super.getKey(); + } + + /** + * Gets the value from the entry. + * This method dereferences weak and soft value and thus may return null. + * + * @return the value, which may be null if it was garbage collected + */ + public V getValue() { + return (parent.valueType > HARD) ? refValue.get() : super.getValue(); + } + + /** + * Sets the value of the entry. + * + * @param obj the object to store + * @return the previous value + */ + public V setValue(V obj) { + V old = getValue(); + if (parent.valueType > HARD) { + refValue.clear(); + refValue = toReference(parent.valueType, obj, hashCode); + } else { + super.setValue(obj); + } + return old; + } + + /** + * Compares this map entry to another. + *

+ * This implementation uses isEqualKey and + * isEqualValue on the main map for comparison. + * + * @param obj the other map entry to compare to + * @return true if equal, false if not + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Map.Entry == false) { + return false; + } + + Map.Entry entry = (Map.Entry) obj; + Object entryKey = entry.getKey(); // convert to hard reference + Object entryValue = entry.getValue(); // convert to hard reference + if ((entryKey == null) || (entryValue == null)) { + return false; + } + // compare using map methods, aiding identity subclass + // note that key is direct access and value is via method + return parent.isEqualKey(entryKey, getKey()) && parent.isEqualValue(entryValue, getValue()); + } + + /** + * Gets the hashcode of the entry using temporary hard references. + *

+ * This implementation uses hashEntry on the main map. + * + * @return the hashcode of the entry + */ + public int hashCode() { + return parent.hashEntry(getKey(), getValue()); + } + + /** + * Constructs a reference of the given type to the given referent. + * The reference is registered with the queue for later purging. + * + * @param type HARD, SOFT or WEAK + * @param referent the object to refer to + * @param hash the hash code of the key of the mapping; + * this number might be different from referent.hashCode() if + * the referent represents a value and not a key + */ + protected Reference toReference(int type, T referent, int hash) { + switch (type) { + case SOFT: + return new SoftRef(hash, referent, parent.queue); + case WEAK: + return new WeakRef(hash, referent, parent.queue); + default: + throw new Error("Attempt to create hard reference in ReferenceMap!"); + } + } + + /** + * Purges the specified reference + * + * @param ref the reference to purge + * @return true or false + */ + boolean purge(Reference ref) { + boolean r = (parent.keyType > HARD) && (refKey == ref); + r = r || ((parent.valueType > HARD) && (refValue == ref)); + if (r) { + if (parent.keyType > HARD) { + refKey.clear(); + } + if (parent.valueType > HARD) { + refValue.clear(); + } else if (parent.purgeValues) { + setValue(null); + } + } + return r; + } + + /** + * Gets the next entry in the bucket. + * + * @return the next entry in the bucket + */ + protected ReferenceEntry next() { + return (ReferenceEntry) next; + } + } + + //----------------------------------------------------------------------- + /** + * The EntrySet iterator. + */ + static class ReferenceIteratorBase { + /** + * The parent map + */ + final AbstractReferenceMap parent; + + // These fields keep track of where we are in the table. + int index; + ReferenceEntry entry; + ReferenceEntry previous; + + // These Object fields provide hard references to the + // current and next entry; this assures that if hasNext() + // returns true, next() will actually return a valid element. + K nextKey; + V nextValue; + K currentKey; + V currentValue; + + int expectedModCount; + + public ReferenceIteratorBase(AbstractReferenceMap parent) { + super(); + this.parent = parent; + index = (parent.size() != 0 ? parent.data.length : 0); + // have to do this here! size() invocation above + // may have altered the modCount. + expectedModCount = parent.modCount; + } + + public boolean hasNext() { + checkMod(); + while (nextNull()) { + ReferenceEntry e = entry; + int i = index; + while ((e == null) && (i > 0)) { + i--; + e = (ReferenceEntry) parent.data[i]; + } + entry = e; + index = i; + if (e == null) { + currentKey = null; + currentValue = null; + return false; + } + nextKey = e.getKey(); + nextValue = e.getValue(); + if (nextNull()) { + entry = entry.next(); + } + } + return true; + } + + private void checkMod() { + if (parent.modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + private boolean nextNull() { + return (nextKey == null) || (nextValue == null); + } + + protected ReferenceEntry nextEntry() { + checkMod(); + if (nextNull() && !hasNext()) { + throw new NoSuchElementException(); + } + previous = entry; + entry = entry.next(); + currentKey = nextKey; + currentValue = nextValue; + nextKey = null; + nextValue = null; + return previous; + } + + protected ReferenceEntry currentEntry() { + checkMod(); + return previous; + } + + public ReferenceEntry superNext() { + return nextEntry(); + } + + public void remove() { + checkMod(); + if (previous == null) { + throw new IllegalStateException(); + } + parent.remove(currentKey); + previous = null; + currentKey = null; + currentValue = null; + expectedModCount = parent.modCount; + } + } + + /** + * The EntrySet iterator. + */ + static class ReferenceEntrySetIterator extends ReferenceIteratorBase implements Iterator> { + + public ReferenceEntrySetIterator(AbstractReferenceMap abstractReferenceMap) { + super(abstractReferenceMap); + } + + public ReferenceEntry next() { + return superNext(); + } + + } + + /** + * The keySet iterator. + */ + static class ReferenceKeySetIterator extends ReferenceIteratorBase implements Iterator { + + ReferenceKeySetIterator(AbstractReferenceMap parent) { + super(parent); + } + + public K next() { + return nextEntry().getKey(); + } + } + + /** + * The values iterator. + */ + static class ReferenceValuesIterator extends ReferenceIteratorBase implements Iterator { + + ReferenceValuesIterator(AbstractReferenceMap parent) { + super(parent); + } + + public V next() { + return nextEntry().getValue(); + } + } + + /** + * The MapIterator implementation. + */ + static class ReferenceMapIterator extends ReferenceIteratorBase implements MapIterator { + + protected ReferenceMapIterator(AbstractReferenceMap parent) { + super(parent); + } + + public K next() { + return nextEntry().getKey(); + } + + public K getKey() { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); + } + return current.getKey(); + } + + public V getValue() { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); + } + return current.getValue(); + } + + public V setValue(V value) { + HashEntry current = currentEntry(); + if (current == null) { + throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); + } + return current.setValue(value); + } + } + + //----------------------------------------------------------------------- + // These two classes store the hashCode of the key of + // of the mapping, so that after they're dequeued a quick + // lookup of the bucket in the table can occur. + + /** + * A soft reference holder. + */ + static class SoftRef extends SoftReference { + /** + * the hashCode of the key (even if the reference points to a value) + */ + private int hash; + + public SoftRef(int hash, T r, ReferenceQueue q) { + super(r, q); + this.hash = hash; + } + + public int hashCode() { + return hash; + } + } + + /** + * A weak reference holder. + */ + static class WeakRef extends WeakReference { + /** + * the hashCode of the key (even if the reference points to a value) + */ + private int hash; + + public WeakRef(int hash, T r, ReferenceQueue q) { + super(r, q); + this.hash = hash; + } + + public int hashCode() { + return hash; + } + } + + //----------------------------------------------------------------------- + /** + * Replaces the superclass method to store the state of this class. + *

+ * Serialization is not one of the JDK's nicest topics. Normal serialization will + * initialise the superclass before the subclass. Sometimes however, this isn't + * what you want, as in this case the put() method on read can be + * affected by subclass state. + *

+ * The solution adopted here is to serialize the state data of this class in + * this protected method. This method must be called by the + * writeObject() of the first serializable subclass. + *

+ * Subclasses may override if they have a specific field that must be present + * on read before this implementation will work. Generally, the read determines + * what must be serialized here, if anything. + * + * @param out the output stream + */ + protected void doWriteObject(ObjectOutputStream out) throws IOException { + out.writeInt(keyType); + out.writeInt(valueType); + out.writeBoolean(purgeValues); + out.writeFloat(loadFactor); + out.writeInt(data.length); + for (MapIterator it = mapIterator(); it.hasNext();) { + out.writeObject(it.next()); + out.writeObject(it.getValue()); + } + out.writeObject(null); // null terminate map + // do not call super.doWriteObject() as code there doesn't work for reference map + } + + /** + * Replaces the superclassm method to read the state of this class. + *

+ * Serialization is not one of the JDK's nicest topics. Normal serialization will + * initialise the superclass before the subclass. Sometimes however, this isn't + * what you want, as in this case the put() method on read can be + * affected by subclass state. + *

+ * The solution adopted here is to deserialize the state data of this class in + * this protected method. This method must be called by the + * readObject() of the first serializable subclass. + *

+ * Subclasses may override if the subclass has a specific field that must be present + * before put() or calculateThreshold() will work correctly. + * + * @param in the input stream + */ + protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + this.keyType = in.readInt(); + this.valueType = in.readInt(); + this.purgeValues = in.readBoolean(); + this.loadFactor = in.readFloat(); + int capacity = in.readInt(); + init(); + data = new HashEntry[capacity]; + while (true) { + K key = (K) in.readObject(); + if (key == null) { + break; + } + V value = (V) in.readObject(); + put(key, value); + } + threshold = calculateThreshold(data.length, loadFactor); + // do not call super.doReadObject() as code there doesn't work for reference map + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/DefaultMapEntry.java b/source/org/jivesoftware/smack/util/collections/DefaultMapEntry.java new file mode 100644 index 000000000..ef752d0c1 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/DefaultMapEntry.java @@ -0,0 +1,65 @@ +// GenericsNote: Converted. +/* + * Copyright 2001-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + + +import java.util.Map; + +/** + * A restricted implementation of {@link java.util.Map.Entry} that prevents + * the MapEntry contract from being broken. + * + * @author James Strachan + * @author Michael A. Smith + * @author Neil O'Toole + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @since Commons Collections 3.0 + */ +public final class DefaultMapEntry extends AbstractMapEntry { + + /** + * Constructs a new entry with the specified key and given value. + * + * @param key the key for the entry, may be null + * @param value the value for the entry, may be null + */ + public DefaultMapEntry(final K key, final V value) { + super(key, value); + } + + /** + * Constructs a new entry from the specified KeyValue. + * + * @param pair the pair to copy, must not be null + * @throws NullPointerException if the entry is null + */ + public DefaultMapEntry(final KeyValue pair) { + super(pair.getKey(), pair.getValue()); + } + + /** + * Constructs a new entry from the specified MapEntry. + * + * @param entry the entry to copy, must not be null + * @throws NullPointerException if the entry is null + */ + public DefaultMapEntry(final Map.Entry entry) { + super(entry.getKey(), entry.getValue()); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/EmptyIterator.java b/source/org/jivesoftware/smack/util/collections/EmptyIterator.java new file mode 100644 index 000000000..6a8707fe6 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/EmptyIterator.java @@ -0,0 +1,58 @@ +// GenericsNote: Converted. +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.Iterator; + +/** + * Provides an implementation of an empty iterator. + *

+ * This class provides an implementation of an empty iterator. + * This class provides for binary compatability between Commons Collections + * 2.1.1 and 3.1 due to issues with IteratorUtils. + * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ + * @since Commons Collections 2.1.1 and 3.1 + */ +public class EmptyIterator extends AbstractEmptyIterator implements ResettableIterator { + + /** + * Singleton instance of the iterator. + * + * @since Commons Collections 3.1 + */ + public static final ResettableIterator RESETTABLE_INSTANCE = new EmptyIterator(); + /** + * Singleton instance of the iterator. + * + * @since Commons Collections 2.1.1 and 3.1 + */ + public static final Iterator INSTANCE = RESETTABLE_INSTANCE; + + public static Iterator getInstance() { + return INSTANCE; + } + + /** + * Constructor. + */ + protected EmptyIterator() { + super(); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/EmptyMapIterator.java b/source/org/jivesoftware/smack/util/collections/EmptyMapIterator.java new file mode 100644 index 000000000..013f5ed19 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/EmptyMapIterator.java @@ -0,0 +1,42 @@ +// GenericsNote: Converted. +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +/** + * Provides an implementation of an empty map iterator. + * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $ + * @since Commons Collections 3.1 + */ +public class EmptyMapIterator extends AbstractEmptyIterator implements MapIterator, ResettableIterator { + + /** + * Singleton instance of the iterator. + * + * @since Commons Collections 3.1 + */ + public static final MapIterator INSTANCE = new EmptyMapIterator(); + + /** + * Constructor. + */ + protected EmptyMapIterator() { + super(); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/IterableMap.java b/source/org/jivesoftware/smack/util/collections/IterableMap.java new file mode 100644 index 000000000..251b587d2 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/IterableMap.java @@ -0,0 +1,61 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.Map; + +/** + * Defines a map that can be iterated directly without needing to create an entry set. + *

+ * A map iterator is an efficient way of iterating over maps. + * There is no need to access the entry set or cast to Map Entry objects. + *

+ * IterableMap map = new HashedMap();
+ * MapIterator it = map.mapIterator();
+ * while (it.hasNext()) {
+ *   Object key = it.next();
+ *   Object value = it.getValue();
+ *   it.setValue("newValue");
+ * }
+ * 
+ * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ + * @since Commons Collections 3.0 + */ +public interface IterableMap extends Map { + + /** + * Obtains a MapIterator over the map. + *

+ * A map iterator is an efficient way of iterating over maps. + * There is no need to access the entry set or cast to Map Entry objects. + *

+     * IterableMap map = new HashedMap();
+     * MapIterator it = map.mapIterator();
+     * while (it.hasNext()) {
+     *   Object key = it.next();
+     *   Object value = it.getValue();
+     *   it.setValue("newValue");
+     * }
+     * 
+ * + * @return a map iterator + */ + MapIterator mapIterator(); + +} diff --git a/source/org/jivesoftware/smack/util/collections/KeyValue.java b/source/org/jivesoftware/smack/util/collections/KeyValue.java new file mode 100644 index 000000000..c73621df5 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/KeyValue.java @@ -0,0 +1,46 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +/** + * Defines a simple key value pair. + *

+ * A Map Entry has considerable additional semantics over and above a simple + * key-value pair. This interface defines the minimum key value, with just the + * two get methods. + * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ + * @since Commons Collections 3.0 + */ +public interface KeyValue { + + /** + * Gets the key from the pair. + * + * @return the key + */ + K getKey(); + + /** + * Gets the value from the pair. + * + * @return the value + */ + V getValue(); + +} diff --git a/source/org/jivesoftware/smack/util/collections/MapIterator.java b/source/org/jivesoftware/smack/util/collections/MapIterator.java new file mode 100644 index 000000000..fe2398c76 --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/MapIterator.java @@ -0,0 +1,109 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.Iterator; + +/** + * Defines an iterator that operates over a Map. + *

+ * This iterator is a special version designed for maps. It can be more + * efficient to use this rather than an entry set iterator where the option + * is available, and it is certainly more convenient. + *

+ * A map that provides this interface may not hold the data internally using + * Map Entry objects, thus this interface can avoid lots of object creation. + *

+ * In use, this iterator iterates through the keys in the map. After each call + * to next(), the getValue() method provides direct + * access to the value. The value can also be set using setValue(). + *

+ * MapIterator it = map.mapIterator();
+ * while (it.hasNext()) {
+ *   Object key = it.next();
+ *   Object value = it.getValue();
+ *   it.setValue(newValue);
+ * }
+ * 
+ * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ + * @since Commons Collections 3.0 + */ +public interface MapIterator extends Iterator { + + /** + * Checks to see if there are more entries still to be iterated. + * + * @return true if the iterator has more elements + */ + boolean hasNext(); + + /** + * Gets the next key from the Map. + * + * @return the next key in the iteration + * @throws java.util.NoSuchElementException + * if the iteration is finished + */ + K next(); + + //----------------------------------------------------------------------- + /** + * Gets the current key, which is the key returned by the last call + * to next(). + * + * @return the current key + * @throws IllegalStateException if next() has not yet been called + */ + K getKey(); + + /** + * Gets the current value, which is the value associated with the last key + * returned by next(). + * + * @return the current value + * @throws IllegalStateException if next() has not yet been called + */ + V getValue(); + + //----------------------------------------------------------------------- + /** + * Removes the last returned key from the underlying Map (optional operation). + *

+ * This method can be called once per call to next(). + * + * @throws UnsupportedOperationException if remove is not supported by the map + * @throws IllegalStateException if next() has not yet been called + * @throws IllegalStateException if remove() has already been called + * since the last call to next() + */ + void remove(); + + /** + * Sets the value associated with the current key (optional operation). + * + * @param value the new value + * @return the previous value + * @throws UnsupportedOperationException if setValue is not supported by the map + * @throws IllegalStateException if next() has not yet been called + * @throws IllegalStateException if remove() has been called since the + * last call to next() + */ + V setValue(V value); + +} diff --git a/source/org/jivesoftware/smack/util/collections/ReferenceMap.java b/source/org/jivesoftware/smack/util/collections/ReferenceMap.java new file mode 100644 index 000000000..f30954dcf --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/ReferenceMap.java @@ -0,0 +1,161 @@ +// GenericsNote: Converted. +/* + * Copyright 2002-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +/** + * A Map implementation that allows mappings to be + * removed by the garbage collector. + *

+ * When you construct a ReferenceMap, you can specify what kind + * of references are used to store the map's keys and values. + * If non-hard references are used, then the garbage collector can remove + * mappings if a key or value becomes unreachable, or if the JVM's memory is + * running low. For information on how the different reference types behave, + * see {@link java.lang.ref.Reference}. + *

+ * Different types of references can be specified for keys and values. + * The keys can be configured to be weak but the values hard, + * in which case this class will behave like a + * + * WeakHashMap. However, you can also specify hard keys and + * weak values, or any other combination. The default constructor uses + * hard keys and soft values, providing a memory-sensitive cache. + *

+ * This map is similar to ReferenceIdentityMap. + * It differs in that keys and values in this class are compared using equals(). + *

+ * This {@link java.util.Map} implementation does not allow null elements. + * Attempting to add a null key or value to the map will raise a NullPointerException. + *

+ * This implementation is not synchronized. + * You can use {@link java.util.Collections#synchronizedMap} to + * provide synchronized access to a ReferenceMap. + * Remember that synchronization will not stop the garbage collecter removing entries. + *

+ * All the available iterators can be reset back to the start by casting to + * ResettableIterator and calling reset(). + *

+ * NOTE: As from Commons Collections 3.1 this map extends AbstractReferenceMap + * (previously it extended AbstractMap). As a result, the implementation is now + * extensible and provides a MapIterator. + * + * @author Paul Jack + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $ + * @see java.lang.ref.Reference + * @since Commons Collections 3.0 (previously in main package v2.1) + */ +public class ReferenceMap extends AbstractReferenceMap implements Serializable { + + /** + * Serialization version + */ + private static final long serialVersionUID = 1555089888138299607L; + + /** + * Constructs a new ReferenceMap that will + * use hard references to keys and soft references to values. + */ + public ReferenceMap() { + super(HARD, SOFT, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); + } + + /** + * Constructs a new ReferenceMap that will + * use the specified types of references. + * + * @param keyType the type of reference to use for keys; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param valueType the type of reference to use for values; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + */ + public ReferenceMap(int keyType, int valueType) { + super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); + } + + /** + * Constructs a new ReferenceMap that will + * use the specified types of references. + * + * @param keyType the type of reference to use for keys; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param valueType the type of reference to use for values; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param purgeValues should the value be automatically purged when the + * key is garbage collected + */ + public ReferenceMap(int keyType, int valueType, boolean purgeValues) { + super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues); + } + + /** + * Constructs a new ReferenceMap with the + * specified reference types, load factor and initial + * capacity. + * + * @param keyType the type of reference to use for keys; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param valueType the type of reference to use for values; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param capacity the initial capacity for the map + * @param loadFactor the load factor for the map + */ + public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { + super(keyType, valueType, capacity, loadFactor, false); + } + + /** + * Constructs a new ReferenceMap with the + * specified reference types, load factor and initial + * capacity. + * + * @param keyType the type of reference to use for keys; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param valueType the type of reference to use for values; + * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} + * @param capacity the initial capacity for the map + * @param loadFactor the load factor for the map + * @param purgeValues should the value be automatically purged when the + * key is garbage collected + */ + public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor, boolean purgeValues) { + super(keyType, valueType, capacity, loadFactor, purgeValues); + } + + //----------------------------------------------------------------------- + /** + * Write the map out using a custom routine. + */ + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + doWriteObject(out); + } + + /** + * Read the map in using a custom routine. + */ + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + doReadObject(in); + } + +} diff --git a/source/org/jivesoftware/smack/util/collections/ResettableIterator.java b/source/org/jivesoftware/smack/util/collections/ResettableIterator.java new file mode 100644 index 000000000..cf814f77e --- /dev/null +++ b/source/org/jivesoftware/smack/util/collections/ResettableIterator.java @@ -0,0 +1,38 @@ +// GenericsNote: Converted. +/* + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smack.util.collections; + +import java.util.Iterator; + +/** + * Defines an iterator that can be reset back to an initial state. + *

+ * This interface allows an iterator to be repeatedly reused. + * + * @author Matt Hall, John Watkinson, Stephen Colebourne + * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:19 $ + * @since Commons Collections 3.0 + */ +public interface ResettableIterator extends Iterator { + + /** + * Resets the iterator back to the position at which the iterator + * was created. + */ + public void reset(); + +} diff --git a/test/org/jivesoftware/smack/ChatTest.java b/test/org/jivesoftware/smack/ChatTest.java index c678592ef..826641003 100644 --- a/test/org/jivesoftware/smack/ChatTest.java +++ b/test/org/jivesoftware/smack/ChatTest.java @@ -1,54 +1,54 @@ /** -* $RCSfile$ -* $Revision$ -* $Date$ -* -* Copyright (C) 2002-2003 Jive Software. All rights reserved. -* ==================================================================== -* The Jive Software License (based on Apache Software License, Version 1.1) -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in -* the documentation and/or other materials provided with the -* distribution. -* -* 3. The end-user documentation included with the redistribution, -* if any, must include the following acknowledgment: -* "This product includes software developed by -* Jive Software (http://www.jivesoftware.com)." -* Alternately, this acknowledgment may appear in the software itself, -* if and wherever such third-party acknowledgments normally appear. -* -* 4. The names "Smack" and "Jive Software" must not be used to -* endorse or promote products derived from this software without -* prior written permission. For written permission, please -* contact webmaster@jivesoftware.com. -* -* 5. Products derived from this software may not be called "Smack", -* nor may "Smack" appear in their name, without prior written -* permission of Jive Software. -* -* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR -* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -* SUCH DAMAGE. -* ==================================================================== -*/ + * $RCSfile$ + * $Revision$ + * $Date$ + * + * Copyright (C) 2002-2003 Jive Software. All rights reserved. + * ==================================================================== + * The Jive Software License (based on Apache Software License, Version 1.1) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by + * Jive Software (http://www.jivesoftware.com)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The names "Smack" and "Jive Software" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please + * contact webmaster@jivesoftware.com. + * + * 5. Products derived from this software may not be called "Smack", + * nor may "Smack" appear in their name, without prior written + * permission of Jive Software. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + */ package org.jivesoftware.smack; @@ -56,29 +56,27 @@ import java.util.Date; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.test.SmackTestCase; +import org.jivesoftware.smack.filter.ThreadFilter; /** * Tests the chat functionality. - * + * * @author Gaston Dombiak */ public class ChatTest extends SmackTestCase { - /** - * Constructor for ChatTest. - * @param arg0 - */ public ChatTest(String arg0) { super(arg0); } public void testProperties() { try { - Chat newChat = getConnection(0).createChat(getFullJID(1)); - Chat newChat2 = new Chat(getConnection(1), getFullJID(0), newChat.getThreadID()); + Chat newChat = getConnection(0).getChatManager().createChat(getFullJID(1), null); + PacketCollector collector = getConnection(1) + .createPacketCollector(new ThreadFilter(newChat.getThreadID())); - Message msg = newChat.createMessage(); + Message msg = new Message(); msg.setSubject("Subject of the chat"); msg.setBody("Body of the chat"); @@ -90,34 +88,35 @@ public class ChatTest extends SmackTestCase { msg.setProperty("birthdate", new Date()); newChat.sendMessage(msg); - Message msg2 = newChat2.nextMessage(2000); + Message msg2 = (Message) collector.nextResult(2000); + assertNotNull("No message was received", msg2); assertEquals("Subjects are different", msg.getSubject(), msg2.getSubject()); assertEquals("Bodies are different", msg.getBody(), msg2.getBody()); assertEquals( - "favoriteColors are different", - msg.getProperty("favoriteColor"), - msg2.getProperty("favoriteColor")); + "favoriteColors are different", + msg.getProperty("favoriteColor"), + msg2.getProperty("favoriteColor")); assertEquals( - "ages are different", - msg.getProperty("age"), - msg2.getProperty("age")); + "ages are different", + msg.getProperty("age"), + msg2.getProperty("age")); assertEquals( - "distances are different", - msg.getProperty("distance"), - msg2.getProperty("distance")); + "distances are different", + msg.getProperty("distance"), + msg2.getProperty("distance")); assertEquals( - "weights are different", - msg.getProperty("weight"), - msg2.getProperty("weight")); + "weights are different", + msg.getProperty("weight"), + msg2.getProperty("weight")); assertEquals( - "males are different", - msg.getProperty("male"), - msg2.getProperty("male")); + "males are different", + msg.getProperty("male"), + msg2.getProperty("male")); assertEquals( - "birthdates are different", - msg.getProperty("birthdate"), - msg2.getProperty("birthdate")); + "birthdates are different", + msg.getProperty("birthdate"), + msg2.getProperty("birthdate")); } catch (XMPPException e) { e.printStackTrace(); diff --git a/test/org/jivesoftware/smack/FloodTest.java b/test/org/jivesoftware/smack/FloodTest.java index 4885298ca..8bc6a43e3 100644 --- a/test/org/jivesoftware/smack/FloodTest.java +++ b/test/org/jivesoftware/smack/FloodTest.java @@ -21,6 +21,7 @@ package org.jivesoftware.smack; import org.jivesoftware.smack.test.SmackTestCase; +import org.jivesoftware.smack.filter.ThreadFilter; /** * Simple test to measure server performance. @@ -35,14 +36,17 @@ public class FloodTest extends SmackTestCase { public void testMessageFlood() { try { - Chat chat11 = getConnection(0).createChat(getBareJID(1)); - Chat chat12 = new Chat(getConnection(1), getBareJID(0), chat11.getThreadID()); + Chat chat11 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + PacketCollector chat12 = getConnection(1).createPacketCollector( + new ThreadFilter(chat11.getThreadID())); - Chat chat21 = getConnection(0).createChat(getBareJID(2)); - Chat chat22 = new Chat(getConnection(2), getBareJID(0), chat21.getThreadID()); + Chat chat21 = getConnection(0).getChatManager().createChat(getBareJID(2), null); + PacketCollector chat22 = getConnection(2).createPacketCollector( + new ThreadFilter(chat21.getThreadID())); - Chat chat31 = getConnection(0).createChat(getBareJID(3)); - Chat chat32 = new Chat(getConnection(3), getBareJID(0), chat31.getThreadID()); + Chat chat31 = getConnection(0).getChatManager().createChat(getBareJID(3), null); + PacketCollector chat32 = getConnection(3).createPacketCollector( + new ThreadFilter(chat31.getThreadID())); for (int i=0; i<500; i++) { chat11.sendMessage("Hello_1" + i); @@ -50,9 +54,9 @@ public class FloodTest extends SmackTestCase { chat31.sendMessage("Hello_3" + i); } for (int i=0; i<500; i++) { - assertNotNull("Some message was lost (" + i + ")", chat12.nextMessage(1000)); - assertNotNull("Some message was lost (" + i + ")", chat22.nextMessage(1000)); - assertNotNull("Some message was lost (" + i + ")", chat32.nextMessage(1000)); + assertNotNull("Some message was lost (" + i + ")", chat12.nextResult(1000)); + assertNotNull("Some message was lost (" + i + ")", chat22.nextResult(1000)); + assertNotNull("Some message was lost (" + i + ")", chat32.nextResult(1000)); } } catch (Exception e) { diff --git a/test/org/jivesoftware/smack/MessageTest.java b/test/org/jivesoftware/smack/MessageTest.java index 72852859c..f6e06ef95 100644 --- a/test/org/jivesoftware/smack/MessageTest.java +++ b/test/org/jivesoftware/smack/MessageTest.java @@ -48,14 +48,16 @@ public class MessageTest extends SmackTestCase { Thread.sleep(500); // User1 sends some messages to User2 which is not available at the moment - Chat chat = getConnection(0).createChat(getBareJID(1)); + Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null); + PacketCollector collector = getConnection(1).createPacketCollector( + new MessageTypeFilter(Message.Type.chat)); chat.sendMessage("Test 1"); chat.sendMessage("Test 2"); Thread.sleep(500); // User2 becomes available again - PacketCollector collector = getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.CHAT)); + getConnection(1).sendPacket(new Presence(Presence.Type.available)); // Check that offline messages are retrieved by user2 which is now available @@ -66,7 +68,8 @@ public class MessageTest extends SmackTestCase { message = (Message) collector.nextResult(1000); assertNull(message); - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } @@ -84,14 +87,16 @@ public class MessageTest extends SmackTestCase { Thread.sleep(500); // User1 sends some messages to User2 which is not available at the moment - Chat chat = getConnection(0).createChat(getBareJID(1)); + Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null); + PacketCollector collector = getConnection(1).createPacketCollector( + new MessageTypeFilter(Message.Type.chat)); chat.sendMessage("Test \f 1"); chat.sendMessage("Test \r 1"); Thread.sleep(500); // User2 becomes available again - PacketCollector collector = getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.CHAT)); + getConnection(1).sendPacket(new Presence(Presence.Type.available)); // Check that offline messages are retrieved by user2 which is now available @@ -102,7 +107,8 @@ public class MessageTest extends SmackTestCase { message = (Message) collector.nextResult(1000); assertNull(message); - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } @@ -114,12 +120,13 @@ public class MessageTest extends SmackTestCase { */ public void testHugeMessage() { // User2 becomes available again - PacketCollector collector = getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.CHAT)); + PacketCollector collector = getConnection(1).createPacketCollector( + new MessageTypeFilter(Message.Type.chat)); // Create message with a body of 4K characters - Message msg = new Message(getFullJID(1), Message.Type.CHAT); + Message msg = new Message(getFullJID(1), Message.Type.chat); StringBuilder sb = new StringBuilder(5000); - for (int i=0; i<=4000; i++) { + for (int i = 0; i <= 4000; i++) { sb.append("X"); } msg.setBody(sb.toString()); diff --git a/test/org/jivesoftware/smack/filter/AndFilterTest.java b/test/org/jivesoftware/smack/filter/AndFilterTest.java index 68029a681..82a5f8b3b 100644 --- a/test/org/jivesoftware/smack/filter/AndFilterTest.java +++ b/test/org/jivesoftware/smack/filter/AndFilterTest.java @@ -63,7 +63,7 @@ public class AndFilterTest extends TestCase { public void testNullArgs() { PacketFilter filter = null; try { - AndFilter and = new AndFilter(filter, filter); + new AndFilter(filter, filter); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException e) { diff --git a/test/org/jivesoftware/smackx/FormTest.java b/test/org/jivesoftware/smackx/FormTest.java index 3fd0090c1..480130af1 100644 --- a/test/org/jivesoftware/smackx/FormTest.java +++ b/test/org/jivesoftware/smackx/FormTest.java @@ -54,6 +54,8 @@ package org.jivesoftware.smackx; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.PacketCollector; +import org.jivesoftware.smack.filter.ThreadFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.test.SmackTestCase; @@ -64,10 +66,6 @@ import org.jivesoftware.smack.test.SmackTestCase; */ public class FormTest extends SmackTestCase { - /** - * Constructor for FormTest. - * @param arg0 - */ public FormTest(String arg0) { super(arg0); } @@ -113,10 +111,13 @@ public class FormTest extends SmackTestCase { formToSend.addField(field); // Create the chats between the two participants - Chat chat = getConnection(0).createChat(getBareJID(1)); - Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat.getThreadID()); + Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null); + PacketCollector collector = getConnection(0).createPacketCollector( + new ThreadFilter(chat.getThreadID())); + PacketCollector collector2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat.getThreadID())); - Message msg = chat.createMessage(); + Message msg = new Message(); msg.setBody("To enter a case please fill out this form and send it back to me"); msg.addExtension(formToSend.getDataFormToSend()); @@ -125,7 +126,7 @@ public class FormTest extends SmackTestCase { chat.sendMessage(msg); // Get the message with the form to fill out - Message msg2 = chat2.nextMessage(2000); + Message msg2 = (Message)collector2.nextResult(2000); // Retrieve the form to fill out Form formToRespond = Form.getFormFrom(msg2); assertNotNull(formToRespond); @@ -148,15 +149,18 @@ public class FormTest extends SmackTestCase { completedForm.setAnswer("time", true); completedForm.setAnswer("age", 20); // Create a new message to send with the completed form - msg2 = chat2.createMessage(); + msg2 = new Message(); + msg2.setTo(msg.getFrom()); + msg2.setThread(msg.getThread()); + msg2.setType(Message.Type.chat); msg2.setBody("To enter a case please fill out this form and send it back to me"); // Add the completed form to the message msg2.addExtension(completedForm.getDataFormToSend()); // Send the message with the completed form - chat2.sendMessage(msg2); + getConnection(1).sendPacket(msg2); // Get the message with the completed form - Message msg3 = chat.nextMessage(2000); + Message msg3 = (Message) collector.nextResult(2000); // Retrieve the completed form completedForm = Form.getFormFrom(msg3); assertNotNull(completedForm); @@ -173,6 +177,10 @@ public class FormTest extends SmackTestCase { catch (XMPPException ex) { fail(ex.getMessage()); } + finally { + collector.cancel(); + collector2.cancel(); + } } protected int getMaxConnections() { diff --git a/test/org/jivesoftware/smackx/MessageEventManagerTest.java b/test/org/jivesoftware/smackx/MessageEventManagerTest.java index 689b1a1d6..316e5e3a4 100644 --- a/test/org/jivesoftware/smackx/MessageEventManagerTest.java +++ b/test/org/jivesoftware/smackx/MessageEventManagerTest.java @@ -66,10 +66,6 @@ import org.jivesoftware.smack.test.SmackTestCase; */ public class MessageEventManagerTest extends SmackTestCase { - /** - * Constructor for MessageEventManagerTest. - * @param name - */ public MessageEventManagerTest(String name) { super(name); } @@ -83,10 +79,10 @@ public class MessageEventManagerTest extends SmackTestCase { */ public void testSendMessageEventRequest() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("An interesting body comes here..."); // Add to the message all the notifications requests (offline, delivered, displayed, @@ -112,7 +108,7 @@ public class MessageEventManagerTest extends SmackTestCase { */ public void testSendMessageEventRequestAndDisplayNotifications() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); MessageEventManager messageEventManager = new MessageEventManager(getConnection(0)); messageEventManager @@ -139,7 +135,7 @@ public class MessageEventManagerTest extends SmackTestCase { }); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("An interesting body comes here..."); // Add to the message all the notifications requests (offline, delivered, displayed, @@ -166,8 +162,8 @@ public class MessageEventManagerTest extends SmackTestCase { * 5. User_2 will simulate that he/she has cancelled the reply */ public void testRequestsAndNotifications() { - final ArrayList results = new ArrayList(); - ArrayList resultsExpected = new ArrayList(); + final ArrayList results = new ArrayList(); + ArrayList resultsExpected = new ArrayList(); resultsExpected.add("deliveredNotificationRequested"); resultsExpected.add("composingNotificationRequested"); resultsExpected.add("displayedNotificationRequested"); @@ -178,7 +174,7 @@ public class MessageEventManagerTest extends SmackTestCase { resultsExpected.add("cancelledNotification"); // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); MessageEventManager messageEventManager1 = new MessageEventManager(getConnection(0)); messageEventManager1 @@ -241,7 +237,7 @@ public class MessageEventManagerTest extends SmackTestCase { }); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("An interesting body comes here..."); // Add to the message all the notifications requests (offline, delivered, displayed, diff --git a/test/org/jivesoftware/smackx/MultipleRecipientManagerTest.java b/test/org/jivesoftware/smackx/MultipleRecipientManagerTest.java index 30b72f99c..91123d7a4 100644 --- a/test/org/jivesoftware/smackx/MultipleRecipientManagerTest.java +++ b/test/org/jivesoftware/smackx/MultipleRecipientManagerTest.java @@ -49,11 +49,11 @@ public class MultipleRecipientManagerTest extends SmackTestCase { public void testSending() throws XMPPException { PacketCollector collector1 = - getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector2 = - getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector3 = - getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); Message message = new Message(); message.setBody("Hola"); @@ -114,13 +114,13 @@ public class MultipleRecipientManagerTest extends SmackTestCase { */ public void testReplying() throws XMPPException { PacketCollector collector0 = - getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(0).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector1 = - getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector2 = - getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector3 = - getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); // Send the intial message with multiple recipients Message message = new Message(); @@ -196,11 +196,11 @@ public class MultipleRecipientManagerTest extends SmackTestCase { */ public void testNoReply() throws XMPPException { PacketCollector collector1 = - getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(1).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector2 = - getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(2).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); PacketCollector collector3 = - getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.NORMAL)); + getConnection(3).createPacketCollector(new MessageTypeFilter(Message.Type.normal)); // Send the intial message with multiple recipients Message message = new Message(); diff --git a/test/org/jivesoftware/smackx/OfflineMessageManagerTest.java b/test/org/jivesoftware/smackx/OfflineMessageManagerTest.java index 0855cd7ba..b2a6ebe56 100644 --- a/test/org/jivesoftware/smackx/OfflineMessageManagerTest.java +++ b/test/org/jivesoftware/smackx/OfflineMessageManagerTest.java @@ -64,7 +64,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { Thread.sleep(500); // User1 sends some messages to User2 which is not available at the moment - Chat chat = getConnection(0).createChat(getBareJID(1)); + Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null); chat.sendMessage("Test 1"); chat.sendMessage("Test 2"); @@ -76,7 +76,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { // Check the message headers Iterator headers = offlineManager.getHeaders(); assertTrue("No message header was found", headers.hasNext()); - List stamps = new ArrayList(); + List stamps = new ArrayList(); while (headers.hasNext()) { OfflineMessageHeader header = (OfflineMessageHeader) headers.next(); assertEquals("Incorrect sender", getFullJID(0), header.getJid()); @@ -87,7 +87,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { // Get the offline messages Iterator messages = offlineManager.getMessages(stamps); assertTrue("No message was found", messages.hasNext()); - stamps = new ArrayList(); + stamps = new ArrayList(); while (messages.hasNext()) { Message message = (Message) messages.next(); OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline", @@ -102,7 +102,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { // User2 becomes available again PacketCollector collector = getConnection(1).createPacketCollector( - new MessageTypeFilter(Message.Type.CHAT)); + new MessageTypeFilter(Message.Type.chat)); getConnection(1).sendPacket(new Presence(Presence.Type.available)); // Check that no offline messages was sent to the user @@ -133,7 +133,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { Thread.sleep(500); // User1 sends some messages to User2 which is not available at the moment - Chat chat = getConnection(0).createChat(getBareJID(1)); + Chat chat = getConnection(0).getChatManager().createChat(getBareJID(1), null); chat.sendMessage("Test 1"); chat.sendMessage("Test 2"); @@ -145,7 +145,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { // Get all offline messages Iterator messages = offlineManager.getMessages(); assertTrue("No message was found", messages.hasNext()); - List stamps = new ArrayList(); + List stamps = new ArrayList(); while (messages.hasNext()) { Message message = (Message) messages.next(); OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline", @@ -160,7 +160,7 @@ public class OfflineMessageManagerTest extends SmackTestCase { // User2 becomes available again PacketCollector collector = getConnection(1).createPacketCollector( - new MessageTypeFilter(Message.Type.CHAT)); + new MessageTypeFilter(Message.Type.chat)); getConnection(1).sendPacket(new Presence(Presence.Type.available)); // Check that no offline messages was sent to the user diff --git a/test/org/jivesoftware/smackx/ServiceDiscoveryManagerTest.java b/test/org/jivesoftware/smackx/ServiceDiscoveryManagerTest.java index 3f1dfa82a..34f74ce9a 100644 --- a/test/org/jivesoftware/smackx/ServiceDiscoveryManagerTest.java +++ b/test/org/jivesoftware/smackx/ServiceDiscoveryManagerTest.java @@ -66,10 +66,6 @@ import org.jivesoftware.smackx.packet.DiscoverInfo; */ public class ServiceDiscoveryManagerTest extends SmackTestCase { - /** - * Constructor for ServiceDiscoveryManagerTest. - * @param arg0 - */ public ServiceDiscoveryManagerTest(String arg0) { super(arg0); } diff --git a/test/org/jivesoftware/smackx/XHTMLManagerTest.java b/test/org/jivesoftware/smackx/XHTMLManagerTest.java index cd9c65fdd..1835cbb61 100644 --- a/test/org/jivesoftware/smackx/XHTMLManagerTest.java +++ b/test/org/jivesoftware/smackx/XHTMLManagerTest.java @@ -55,6 +55,7 @@ package org.jivesoftware.smackx; import java.util.Iterator; import org.jivesoftware.smack.*; +import org.jivesoftware.smack.filter.ThreadFilter; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.test.SmackTestCase; @@ -83,10 +84,10 @@ public class XHTMLManagerTest extends SmackTestCase { */ public void testSendSimpleXHTMLMessage() { // User1 creates a chat with user2 - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); @@ -123,39 +124,12 @@ public class XHTMLManagerTest extends SmackTestCase { */ public void testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); - - // Create a listener for the chat that will check if the received message includes - // an XHTML extension. Answer an ACK if everything is ok - PacketListener packetListener = new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - assertTrue( - "The received message is not an XHTML Message", - XHTMLManager.isXHTMLMessage(message)); - try { - assertTrue( - "Message without XHTML bodies", - XHTMLManager.getBodies(message).hasNext()); - for (Iterator it = XHTMLManager.getBodies(message); it.hasNext();) { - String body = (String) it.next(); - System.out.println(body); - } - } catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } - try { - chat2.sendMessage("ok"); - } catch (Exception e) { - fail("An error occured sending ack " + e.getMessage()); - } - } - }; - chat2.addMessageListener(packetListener); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); @@ -179,8 +153,24 @@ public class XHTMLManagerTest extends SmackTestCase { } catch (Exception e) { fail("An error occured sending the message with XHTML"); } - // Wait for 1 second for a reply - msg = chat1.nextMessage(1000); + + Packet packet = chat2.nextResult(2000); + Message message = (Message) packet; + assertTrue( + "The received message is not an XHTML Message", + XHTMLManager.isXHTMLMessage(message)); + try { + assertTrue( + "Message without XHTML bodies", + XHTMLManager.getBodies(message).hasNext()); + for (Iterator it = XHTMLManager.getBodies(message); it.hasNext();) { + String body = (String) it.next(); + System.out.println(body); + } + } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); + } assertNotNull("No reply received", msg); } @@ -194,37 +184,12 @@ public class XHTMLManagerTest extends SmackTestCase { */ public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); - - // Create a listener for the chat that will check if the received message includes - // an XHTML extension. Answer an ACK if everything is ok - PacketListener packetListener = new PacketListener() { - public void processPacket(Packet packet) { - int received = 0; - Message message = (Message) packet; - assertTrue( - "The received message is not an XHTML Message", - XHTMLManager.isXHTMLMessage(message)); - try { - assertTrue( - "Message without XHTML bodies", - XHTMLManager.getBodies(message).hasNext()); - for (Iterator it = XHTMLManager.getBodies(message); it.hasNext();) { - received++; - String body = (String) it.next(); - System.out.println(body); - } - bodiesReceived = received; - } catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } - } - }; - chat2.addMessageListener(packetListener); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody( "awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds."); @@ -266,11 +231,31 @@ public class XHTMLManagerTest extends SmackTestCase { bodiesSent = 2; bodiesReceived = 0; chat1.sendMessage(msg); - // Wait half second so that the complete test can run - Thread.sleep(300); } catch (Exception e) { fail("An error occured sending the message with XHTML"); } + + Packet packet = chat2.nextResult(2000); + int received = 0; + Message message = (Message) packet; + assertTrue( + "The received message is not an XHTML Message", + XHTMLManager.isXHTMLMessage(message)); + try { + assertTrue( + "Message without XHTML bodies", + XHTMLManager.getBodies(message).hasNext()); + for (Iterator it = XHTMLManager.getBodies(message); it.hasNext();) { + received++; + String body = (String) it.next(); + System.out.println(body); + } + bodiesReceived = received; + } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers" + + "is misconfigured"); + } assertEquals( "Number of sent and received XHTMP bodies does not match", bodiesSent, diff --git a/test/org/jivesoftware/smackx/muc/MultiUserChatTest.java b/test/org/jivesoftware/smackx/muc/MultiUserChatTest.java index 4893127c3..aebf90eed 100644 --- a/test/org/jivesoftware/smackx/muc/MultiUserChatTest.java +++ b/test/org/jivesoftware/smackx/muc/MultiUserChatTest.java @@ -53,9 +53,6 @@ package org.jivesoftware.smackx.muc; import org.jivesoftware.smack.*; -import org.jivesoftware.smack.filter.AndFilter; -import org.jivesoftware.smack.filter.MessageTypeFilter; -import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.test.SmackTestCase; import org.jivesoftware.smackx.Form; @@ -78,10 +75,6 @@ public class MultiUserChatTest extends SmackTestCase { private MultiUserChat muc; - /** - * Constructor for MultiUserChatTest. - * @param arg0 - */ public MultiUserChatTest(String arg0) { super(arg0); } @@ -440,8 +433,8 @@ public class MultiUserChatTest extends SmackTestCase { assertFalse("No room was found", rooms.isEmpty()); // Check that we have discovered the room used by this test boolean found = false; - for (Iterator it = rooms.iterator(); it.hasNext();) { - HostedRoom hostedRoom = (HostedRoom) it.next(); + for (Object room1 : rooms) { + HostedRoom hostedRoom = (HostedRoom) room1; if (room.equals(hostedRoom.getJid())) { found = true; break; @@ -461,14 +454,12 @@ public class MultiUserChatTest extends SmackTestCase { MultiUserChat muc2 = new MultiUserChat(getConnection(1), room); muc2.join("testbot2"); - getConnection(0).addPacketListener(new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - Chat chat2 = new Chat(getConnection(0), message.getFrom(), message.getThread()); + getConnection(0).getChatManager().addChatListener(new ChatListener() { + public void chatCreated(Chat chat2, boolean createdLocally) { assertEquals( "Sender of chat is incorrect", room + "/testbot2", - message.getFrom()); + chat2.getParticipant()); try { chat2.sendMessage("ACK"); } @@ -476,16 +467,15 @@ public class MultiUserChatTest extends SmackTestCase { fail(e.getMessage()); } } - }, - new AndFilter( - new MessageTypeFilter(Message.Type.CHAT), - new PacketTypeFilter(Message.class))); + }); // Start a private chat with another participant - Chat chat = muc2.createPrivateChat(room + "/testbot"); + Chat chat = muc2.createPrivateChat(room + "/testbot", null); + PacketCollector collector = chat.createCollector(); chat.sendMessage("Hello there"); - Message response = chat.nextMessage(2000); + Message response = (Message) collector.nextResult(2000); + assertNotNull("No response", response); assertEquals("Sender of response is incorrect", room + "/testbot", response.getFrom()); assertEquals("Body of response is incorrect", "ACK", response.getBody()); @@ -1561,8 +1551,8 @@ public class MultiUserChatTest extends SmackTestCase { // Check that the owner list is correct Collection affiliates = muc.getOwners(); assertEquals("Room does not have 2 owners", 2, affiliates.size()); - for (Iterator it =affiliates.iterator(); it.hasNext();) { - Affiliate affiliate = (Affiliate)it.next(); + for (Object affiliate1 : affiliates) { + Affiliate affiliate = (Affiliate) affiliate1; if (getBareJID(0).equals(affiliate.getJid())) { assertEquals("Wrong affiliation", "owner", affiliate.getAffiliation()); assertEquals("Wrong role", "moderator", affiliate.getRole()); @@ -1600,8 +1590,8 @@ public class MultiUserChatTest extends SmackTestCase { // Check that the moderator list is correct Collection occupants = muc.getModerators(); assertEquals("Room does not have 2 moderators", 2, occupants.size()); - for (Iterator it =occupants.iterator(); it.hasNext();) { - Occupant occupant = (Occupant)it.next(); + for (Object occupant1 : occupants) { + Occupant occupant = (Occupant) occupant1; if (getFullJID(0).equals(occupant.getJid())) { assertEquals("Wrong affiliation", "owner", occupant.getAffiliation()); assertEquals("Wrong role", "moderator", occupant.getRole()); @@ -1854,7 +1844,7 @@ public class MultiUserChatTest extends SmackTestCase { answerForm.setAnswer("muc#roomconfig_moderatedroom", true); // Keep the room owner try { - List owners = new ArrayList(); + List owners = new ArrayList(); owners.add(getBareJID(0)); answerForm.setAnswer("muc#roomconfig_roomowners", owners); } @@ -1884,6 +1874,7 @@ public class MultiUserChatTest extends SmackTestCase { muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT)); } catch (Exception e) { + e.printStackTrace(); fail(e.getMessage()); } } diff --git a/test/org/jivesoftware/smackx/packet/MessageEventTest.java b/test/org/jivesoftware/smackx/packet/MessageEventTest.java index 7dc4186ca..ad791a5ad 100644 --- a/test/org/jivesoftware/smackx/packet/MessageEventTest.java +++ b/test/org/jivesoftware/smackx/packet/MessageEventTest.java @@ -65,10 +65,6 @@ import org.jivesoftware.smack.test.SmackTestCase; */ public class MessageEventTest extends SmackTestCase { - /** - * Constructor for MessageEventTest. - * @param name - */ public MessageEventTest(String name) { super(name); } @@ -82,10 +78,10 @@ public class MessageEventTest extends SmackTestCase { */ public void testSendMessageEventRequest() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("An interesting body comes here..."); // Create a MessageEvent Package and add it to the message @@ -118,7 +114,7 @@ public class MessageEventTest extends SmackTestCase { */ public void testSendMessageEventRequestAndDisplayNotifications() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // Create a Listener that listens for Messages with the extension "jabber:x:roster" // This listener will listen on the conn2 and answer an ACK if everything is ok @@ -143,7 +139,7 @@ public class MessageEventTest extends SmackTestCase { getConnection(0).addPacketListener(packetListener, packetFilter); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("An interesting body comes here..."); // Create a MessageEvent Package and add it to the message diff --git a/test/org/jivesoftware/smackx/packet/RosterExchangeTest.java b/test/org/jivesoftware/smackx/packet/RosterExchangeTest.java index 5537d2f6a..2e589b4b9 100644 --- a/test/org/jivesoftware/smackx/packet/RosterExchangeTest.java +++ b/test/org/jivesoftware/smackx/packet/RosterExchangeTest.java @@ -20,10 +20,6 @@ import org.jivesoftware.smackx.*; */ public class RosterExchangeTest extends SmackTestCase { - /** - * Constructor for RosterExchangeTest. - * @param arg0 - */ public RosterExchangeTest(String arg0) { super(arg0); } @@ -35,10 +31,10 @@ public class RosterExchangeTest extends SmackTestCase { */ public void testSendRosterEntries() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("This message contains roster items."); // Create a RosterExchange Package and add it to the message @@ -62,40 +58,12 @@ public class RosterExchangeTest extends SmackTestCase { */ public void testSendAndReceiveRosterEntries() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); - - // Create a Listener that listens for Messages with the extension "jabber:x:roster" - // This listener will listen on the conn2 and answer an ACK if everything is ok - PacketFilter packetFilter = new PacketExtensionFilter("x", "jabber:x:roster"); - PacketListener packetListener = new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - assertNotNull("Body is null", message.getBody()); - try { - RosterExchange rosterExchange = - (RosterExchange) message.getExtension("x", "jabber:x:roster"); - assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange); - assertTrue( - "Roster without entries", - rosterExchange.getRosterEntries().hasNext()); - for (Iterator it = rosterExchange.getRosterEntries(); it.hasNext();) { - RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) it.next(); - } - } catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } - try { - chat2.sendMessage("ok"); - } catch (Exception e) { - fail("An error occured sending ack " + e.getMessage()); - } - } - }; - getConnection(1).addPacketListener(packetListener, packetFilter); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("This message contains roster items."); // Create a RosterExchange Package and add it to the message @@ -110,8 +78,20 @@ public class RosterExchangeTest extends SmackTestCase { fail("An error occured sending the message with the roster"); } // Wait for 2 seconds for a reply - msg = chat1.nextMessage(2000); - assertNotNull("No reply received", msg); + Packet packet = chat2.nextResult(2000); + Message message = (Message) packet; + assertNotNull("Body is null", message.getBody()); + try { + rosterExchange = + (RosterExchange) message.getExtension("x", "jabber:x:roster"); + assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange); + assertTrue( + "Roster without entries", + rosterExchange.getRosterEntries().hasNext()); + } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); + } } /** @@ -122,47 +102,12 @@ public class RosterExchangeTest extends SmackTestCase { */ public void testSendAndAcceptRosterEntries() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); - - // Create a Listener that listens for Messages with the extension "jabber:x:roster" - // This listener will listen on the conn2, save the roster entries and answer an ACK if everything is ok - PacketFilter packetFilter = new PacketExtensionFilter("x", "jabber:x:roster"); - PacketListener packetListener = new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - assertNotNull("Body is null", message.getBody()); - try { - RosterExchange rosterExchange = - (RosterExchange) message.getExtension("x", "jabber:x:roster"); - assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange); - assertTrue( - "Roster without entries", - rosterExchange.getRosterEntries().hasNext()); - // Add the roster entries to user2's roster - for (Iterator it = rosterExchange.getRosterEntries(); it.hasNext();) { - RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) it.next(); - getConnection(1).getRoster().createEntry( - remoteRosterEntry.getUser(), - remoteRosterEntry.getName(), - remoteRosterEntry.getGroupArrayNames()); - } - } catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } catch (Exception e) { - fail(e.toString()); - } - try { - chat2.sendMessage("ok"); - } catch (Exception e) { - fail("An error occured sending ack " + e.getMessage()); - } - } - }; - getConnection(1).addPacketListener(packetListener, packetFilter); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // Create the message to send with the roster - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("This message contains roster items."); // Create a RosterExchange Package and add it to the message @@ -177,12 +122,32 @@ public class RosterExchangeTest extends SmackTestCase { fail("An error occured sending the message with the roster"); } // Wait for 10 seconds for a reply - msg = chat1.nextMessage(5000); - assertNotNull("No reply received", msg); + Packet packet = chat2.nextResult(5000); + Message message = (Message) packet; + assertNotNull("Body is null", message.getBody()); try { - Thread.sleep(200); - } catch (Exception e) { + rosterExchange = + (RosterExchange) message.getExtension("x", "jabber:x:roster"); + assertNotNull("Message without extension \"jabber:x:roster\"", rosterExchange); + assertTrue( + "Roster without entries", + rosterExchange.getRosterEntries().hasNext()); + // Add the roster entries to user2's roster + for (Iterator it = rosterExchange.getRosterEntries(); it.hasNext();) { + RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) it.next(); + getConnection(1).getRoster().createEntry( + remoteRosterEntry.getUser(), + remoteRosterEntry.getName(), + remoteRosterEntry.getGroupArrayNames()); + } } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); + } + catch (Exception e) { + fail(e.toString()); + } + assertTrue("Roster2 has no entries", getConnection(1).getRoster().getEntryCount() > 0); } diff --git a/test/org/jivesoftware/smackx/packet/XHTMLExtensionTest.java b/test/org/jivesoftware/smackx/packet/XHTMLExtensionTest.java index b44e60d4d..9fb993126 100644 --- a/test/org/jivesoftware/smackx/packet/XHTMLExtensionTest.java +++ b/test/org/jivesoftware/smackx/packet/XHTMLExtensionTest.java @@ -69,10 +69,6 @@ public class XHTMLExtensionTest extends SmackTestCase { private int bodiesSent; private int bodiesReceived; - /** - * Constructor for XHTMLExtensionTest. - * @param name - */ public XHTMLExtensionTest(String name) { super(name); } @@ -84,16 +80,16 @@ public class XHTMLExtensionTest extends SmackTestCase { */ public void testSendSimpleXHTMLMessage() { // User1 creates a chat with user2 - Chat chat1 = getConnection(0).createChat(getBareJID(1)); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); // Create a XHTMLExtension Package and add it to the message XHTMLExtension xhtmlExtension = new XHTMLExtension(); xhtmlExtension.addBody( - "

Hey John, this is my new green!!!!

"); + "

Hey John, this is my new green!!!!

"); msg.addExtension(xhtmlExtension); // User1 sends the message that contains the XHTML to user2 @@ -107,62 +103,27 @@ public class XHTMLExtensionTest extends SmackTestCase { } /** - * Low level API test. - * 1. User_1 will send a message with XHTML to user_2 - * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything - * is fine - * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then - * something is wrong - */ + * Low level API test. + * 1. User_1 will send a message with XHTML to user_2 + * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything + * is fine + * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then + * something is wrong + */ public void testSendSimpleXHTMLMessageAndDisplayReceivedXHTMLMessage() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); - - // Create a Listener that listens for Messages with the extension - //"http://jabber.org/protocol/xhtml-im" - // This listener will listen on the conn2 and answer an ACK if everything is ok - PacketFilter packetFilter = - new PacketExtensionFilter("html", "http://jabber.org/protocol/xhtml-im"); - PacketListener packetListener = new PacketListener() { - public void processPacket(Packet packet) { - Message message = (Message) packet; - assertNotNull("Body is null", message.getBody()); - try { - XHTMLExtension xhtmlExtension = - (XHTMLExtension) message.getExtension( - "html", - "http://jabber.org/protocol/xhtml-im"); - assertNotNull( - "Message without extension \"http://jabber.org/protocol/xhtml-im\"", - xhtmlExtension); - assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0); - for (Iterator it = xhtmlExtension.getBodies(); it.hasNext();) { - String body = (String) it.next(); - System.out.println(body); - } - } - catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } - try { - chat2.sendMessage("ok"); - } - catch (Exception e) { - fail("An error occured sending ack " + e.getMessage()); - } - } - }; - getConnection(1).addPacketListener(packetListener, packetFilter); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody("Hey John, this is my new green!!!!"); // Create a XHTMLExtension Package and add it to the message XHTMLExtension xhtmlExtension = new XHTMLExtension(); xhtmlExtension.addBody( - "

Hey John, this is my new green!!!!

"); + "

Hey John, this is my new green!!!!

"); msg.addExtension(xhtmlExtension); // User1 sends the message that contains the XHTML to user2 @@ -172,67 +133,65 @@ public class XHTMLExtensionTest extends SmackTestCase { catch (Exception e) { fail("An error occured sending the message with XHTML"); } - // Wait for 2 seconds for a reply - msg = chat1.nextMessage(1000); - assertNotNull("No reply received", msg); + Packet packet = chat2.nextResult(2000); + Message message = (Message) packet; + assertNotNull("Body is null", message.getBody()); + try { + xhtmlExtension = + (XHTMLExtension) message.getExtension( + "html", + "http://jabber.org/protocol/xhtml-im"); + assertNotNull( + "Message without extension \"http://jabber.org/protocol/xhtml-im\"", + xhtmlExtension); + assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0); + for (Iterator it = xhtmlExtension.getBodies(); it.hasNext();) { + String body = (String) it.next(); + System.out.println(body); + } + } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); + } } /** - * Low level API test. Test a message with two XHTML bodies and several XHTML tags. - * 1. User_1 will send a message with XHTML to user_2 - * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything - * is fine - * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then - * something is wrong - */ + * Low level API test. Test a message with two XHTML bodies and several XHTML tags. + * 1. User_1 will send a message with XHTML to user_2 + * 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything + * is fine + * 3. User_1 will wait several seconds for an ACK from user_2, if none is received then + * something is wrong + */ public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() { // Create a chat for each connection - Chat chat1 = getConnection(0).createChat(getBareJID(1)); - final Chat chat2 = new Chat(getConnection(1), getBareJID(0), chat1.getThreadID()); + Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null); + final PacketCollector chat2 = getConnection(1).createPacketCollector( + new ThreadFilter(chat1.getThreadID())); // Create a Listener that listens for Messages with the extension //"http://jabber.org/protocol/xhtml-im" // This listener will listen on the conn2 and answer an ACK if everything is ok PacketFilter packetFilter = - new PacketExtensionFilter("html", "http://jabber.org/protocol/xhtml-im"); + new PacketExtensionFilter("html", "http://jabber.org/protocol/xhtml-im"); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { - int received = 0; - Message message = (Message) packet; - assertNotNull("Body is null", message.getBody()); - try { - XHTMLExtension xhtmlExtension = - (XHTMLExtension) message.getExtension( - "html", - "http://jabber.org/protocol/xhtml-im"); - assertNotNull( - "Message without extension \"http://jabber.org/protocol/xhtml-im\"", - xhtmlExtension); - assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0); - for (Iterator it = xhtmlExtension.getBodies(); it.hasNext();) { - received++; - System.out.println((String) it.next()); - } - bodiesReceived = received; - } - catch (ClassCastException e) { - fail("ClassCastException - Most probable cause is that smack providers is misconfigured"); - } + } }; getConnection(1).addPacketListener(packetListener, packetFilter); // User1 creates a message to send to user2 - Message msg = chat1.createMessage(); + Message msg = new Message(); msg.setSubject("Any subject you want"); msg.setBody( - "awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds."); + "awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds."); // Create an XHTMLExtension and add it to the message XHTMLExtension xhtmlExtension = new XHTMLExtension(); xhtmlExtension.addBody( - "

impresionante!

Como Emerson dijo una vez:

Una consistencia ridícula es el espantajo de mentes pequeñas.

"); + "

impresionante!

Como Emerson dijo una vez:

Una consistencia ridícula es el espantajo de mentes pequeñas.

"); xhtmlExtension.addBody( - "

awesome!

As Emerson once said:

A foolish consistency is the hobgoblin of little minds.

"); + "

awesome!

As Emerson once said:

A foolish consistency is the hobgoblin of little minds.

"); msg.addExtension(xhtmlExtension); // User1 sends the message that contains the XHTML to user2 @@ -240,16 +199,38 @@ public class XHTMLExtensionTest extends SmackTestCase { bodiesSent = xhtmlExtension.getBodiesCount(); bodiesReceived = 0; chat1.sendMessage(msg); - Thread.sleep(300); } catch (Exception e) { fail("An error occured sending the message with XHTML"); } + Packet packet = chat2.nextResult(2000); + int received = 0; + Message message = (Message) packet; + assertNotNull("Body is null", message.getBody()); + try { + xhtmlExtension = + (XHTMLExtension) message.getExtension( + "html", + "http://jabber.org/protocol/xhtml-im"); + assertNotNull( + "Message without extension \"http://jabber.org/protocol/xhtml-im\"", + xhtmlExtension); + assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0); + for (Iterator it = xhtmlExtension.getBodies(); it.hasNext();) { + received++; + System.out.println((String) it.next()); + } + bodiesReceived = received; + } + catch (ClassCastException e) { + fail("ClassCastException - Most probable cause is that smack providers is " + + "misconfigured"); + } // Wait half second so that the complete test can run assertEquals( - "Number of sent and received XHTMP bodies does not match", - bodiesSent, - bodiesReceived); + "Number of sent and received XHTMP bodies does not match", + bodiesSent, + bodiesReceived); } protected int getMaxConnections() {