diff --git a/source/org/jivesoftware/smack/AccountManager.java b/source/org/jivesoftware/smack/AccountManager.java index 7fb515d7b..5a0ebfb17 100644 --- a/source/org/jivesoftware/smack/AccountManager.java +++ b/source/org/jivesoftware/smack/AccountManager.java @@ -20,12 +20,18 @@ package org.jivesoftware.smack; -import org.jivesoftware.smack.packet.Registration; +import org.jivesoftware.smack.filter.AndFilter; +import org.jivesoftware.smack.filter.PacketFilter; +import org.jivesoftware.smack.filter.PacketIDFilter; +import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; -import org.jivesoftware.smack.filter.*; +import org.jivesoftware.smack.packet.Registration; import org.jivesoftware.smack.util.StringUtils; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** * Allows creation and management of accounts on an XMPP server. @@ -90,17 +96,19 @@ public class AccountManager { * * @return the required account attributes. */ - public Iterator getAccountAttributes() { + public Iterator getAccountAttributes() { try { if (info == null) { getRegistrationInfo(); } - Map attributes = info.getAttributes(); + Map attributes = info.getAttributes(); if (attributes != null) { return attributes.keySet().iterator(); } } - catch (XMPPException xe) { } + catch (XMPPException xe) { + xe.printStackTrace(); + } return Collections.EMPTY_LIST.iterator(); } @@ -117,9 +125,11 @@ public class AccountManager { if (info == null) { getRegistrationInfo(); } - return (String) info.getAttributes().get(name); + return info.getAttributes().get(name); + } + catch (XMPPException xe) { + xe.printStackTrace(); } - catch (XMPPException xe) { } return null; } @@ -159,9 +169,9 @@ public class AccountManager { throw new XMPPException("Server does not support account creation."); } // Create a map for all the required attributes, but give them blank values. - Map attributes = new HashMap(); - for (Iterator i=getAccountAttributes(); i.hasNext(); ) { - String attributeName = (String)i.next(); + Map attributes = new HashMap(); + for (Iterator i=getAccountAttributes(); i.hasNext(); ) { + String attributeName = i.next(); attributes.put(attributeName, ""); } createAccount(username, password, attributes); @@ -178,7 +188,7 @@ public class AccountManager { * @throws XMPPException if an error occurs creating the account. * @see #getAccountAttributes() */ - public void createAccount(String username, String password, Map attributes) + public void createAccount(String username, String password, Map attributes) throws XMPPException { if (!supportsAccountCreation()) { @@ -217,7 +227,7 @@ public class AccountManager { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); - HashMap map = new HashMap(); + Map map = new HashMap(); map.put("username",StringUtils.parseName(connection.getUser())); map.put("password",newPassword); reg.setAttributes(map); @@ -251,7 +261,7 @@ public class AccountManager { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); - Map attributes = new HashMap(); + Map attributes = new HashMap(); // To delete an account, we add a single attribute, "remove", that is blank. attributes.put("remove", ""); reg.setAttributes(attributes); diff --git a/source/org/jivesoftware/smack/Chat.java b/source/org/jivesoftware/smack/Chat.java index 57e1633e4..b82c91e30 100644 --- a/source/org/jivesoftware/smack/Chat.java +++ b/source/org/jivesoftware/smack/Chat.java @@ -20,12 +20,15 @@ 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 org.jivesoftware.smack.filter.*; -import java.util.*; import java.lang.ref.WeakReference; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; /** * A chat is a series of messages sent between two users. Each chat has a unique @@ -66,7 +69,8 @@ public class Chat { private String participant; private PacketFilter messageFilter; private PacketCollector messageCollector; - private Set listeners = new HashSet(); + private final Set> listeners = + new HashSet>(); /** * Creates a new chat with the specified user. @@ -94,7 +98,7 @@ public class Chat { // 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)); + new WeakReference(this)); // Filter the messages whose thread equals Chat's id messageFilter = new ThreadFilter(threadID); @@ -222,7 +226,7 @@ public class Chat { // 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)); + listeners.add(new WeakReference(listener)); } } @@ -242,10 +246,10 @@ public class Chat { messageCollector.processPacket(message); synchronized (listeners) { - for (Iterator i=listeners.iterator(); i.hasNext(); ) { - WeakReference listenerRef = (WeakReference)i.next(); + for (Iterator> i=listeners.iterator(); i.hasNext(); ) { + WeakReference listenerRef = i.next(); PacketListener listener; - if ((listener = (PacketListener)listenerRef.get()) != null) { + if ((listener = listenerRef.get()) != null) { listener.processPacket(message); } // If the reference was cleared, remove it from the set. diff --git a/source/org/jivesoftware/smack/ConnectionConfiguration.java b/source/org/jivesoftware/smack/ConnectionConfiguration.java index 7e4b3d7c6..bdb3e617a 100644 --- a/source/org/jivesoftware/smack/ConnectionConfiguration.java +++ b/source/org/jivesoftware/smack/ConnectionConfiguration.java @@ -62,7 +62,7 @@ public class ConnectionConfiguration implements Cloneable { // Build the default path to the cacert truststore file. By default we are // going to use the file located in $JREHOME/lib/security/cacerts. String javaHome = System.getProperty("java.home"); - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); buffer.append(javaHome).append(File.separator).append("lib"); buffer.append(File.separator).append("security"); buffer.append(File.separator).append("cacerts"); diff --git a/source/org/jivesoftware/smack/PacketCollector.java b/source/org/jivesoftware/smack/PacketCollector.java index 737def22e..3a1733f1b 100644 --- a/source/org/jivesoftware/smack/PacketCollector.java +++ b/source/org/jivesoftware/smack/PacketCollector.java @@ -48,7 +48,7 @@ public class PacketCollector { private static final int MAX_PACKETS = 65536; private PacketFilter packetFilter; - private LinkedList resultQueue; + private LinkedList resultQueue; private PacketReader packetReader; private boolean cancelled = false; @@ -62,7 +62,7 @@ public class PacketCollector { protected PacketCollector(PacketReader packetReader, PacketFilter packetFilter) { this.packetReader = packetReader; this.packetFilter = packetFilter; - this.resultQueue = new LinkedList(); + this.resultQueue = new LinkedList(); } /** @@ -101,7 +101,7 @@ public class PacketCollector { return null; } else { - return (Packet)resultQueue.removeLast(); + return resultQueue.removeLast(); } } @@ -121,7 +121,7 @@ public class PacketCollector { // Ignore. } } - return (Packet)resultQueue.removeLast(); + return resultQueue.removeLast(); } /** @@ -159,12 +159,12 @@ public class PacketCollector { } // Return the packet that was found. else { - return (Packet)resultQueue.removeLast(); + return resultQueue.removeLast(); } } // There's already a packet waiting, so return it. else { - return (Packet)resultQueue.removeLast(); + return resultQueue.removeLast(); } } diff --git a/source/org/jivesoftware/smack/PacketReader.java b/source/org/jivesoftware/smack/PacketReader.java index 3cfcf4023..32277ec25 100644 --- a/source/org/jivesoftware/smack/PacketReader.java +++ b/source/org/jivesoftware/smack/PacketReader.java @@ -48,9 +48,11 @@ class PacketReader { private XMPPConnection connection; private XmlPullParser parser; private boolean done = false; - private final VolatileMemberCollection collectors = new VolatileMemberCollection(50); + private final VolatileMemberCollection collectors = + new VolatileMemberCollection(50); private final VolatileMemberCollection listeners = new VolatileMemberCollection(50); - protected final List connectionListeners = new ArrayList(); + protected final List connectionListeners = + new ArrayList(); private String connectionID = null; private final Object connectionIDLock = new Object(); @@ -176,12 +178,11 @@ class PacketReader { public void shutdown() { // Notify connection listeners of the connection closing if done hasn't already been set. if (!done) { - ArrayList listenersCopy; + List listenersCopy; synchronized (connectionListeners) { // Make a copy since it's possible that a listener will be removed from the list - listenersCopy = new ArrayList(connectionListeners); - for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) { - ConnectionListener listener = (ConnectionListener)i.next(); + listenersCopy = new ArrayList(connectionListeners); + for (ConnectionListener listener : listenersCopy) { listener.connectionClosed(); } } @@ -206,12 +207,11 @@ class PacketReader { // Print the stack trace to help catch the problem e.printStackTrace(); // Notify connection listeners of the error. - ArrayList listenersCopy; + List listenersCopy; synchronized (connectionListeners) { // Make a copy since it's possible that a listener will be removed from the list - listenersCopy = new ArrayList(connectionListeners); - for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) { - ConnectionListener listener = (ConnectionListener)i.next(); + listenersCopy = new ArrayList(connectionListeners); + for (ConnectionListener listener : listenersCopy) { listener.connectionClosedOnError(e); } } @@ -489,8 +489,8 @@ class PacketReader { * @return a collection of Stings with the mechanisms included in the mechanisms stanza. * @throws Exception if an exception occurs while parsing the stanza. */ - private Collection parseMechanisms(XmlPullParser parser) throws Exception { - List mechanisms = new ArrayList(); + private Collection parseMechanisms(XmlPullParser parser) throws Exception { + List mechanisms = new ArrayList(); boolean done = false; while (!done) { int eventType = parser.next(); @@ -510,9 +510,9 @@ class PacketReader { return mechanisms; } - private Collection parseCompressionMethods(XmlPullParser parser) + private Collection parseCompressionMethods(XmlPullParser parser) throws IOException, XmlPullParserException { - List methods = new ArrayList(); + List methods = new ArrayList(); boolean done = false; while (!done) { int eventType = parser.next(); @@ -698,7 +698,7 @@ class PacketReader { private Registration parseRegistration(XmlPullParser parser) throws Exception { Registration registration = new Registration(); - Map fields = null; + Map fields = null; boolean done = false; while (!done) { int eventType = parser.next(); @@ -709,7 +709,7 @@ class PacketReader { String name = parser.getName(); String value = ""; if (fields == null) { - fields = new HashMap(); + fields = new HashMap(); } if (parser.next() == XmlPullParser.TEXT) { @@ -772,19 +772,19 @@ class PacketReader { * volatile. In other words, many are added and deleted and 'null' values are skipped by the * returned iterator. */ - static class VolatileMemberCollection { + static class VolatileMemberCollection { private final Object mutex = new Object(); - private final ArrayList collectors; + private final ArrayList collectors; private int nullIndex = -1; private int[] nullArray; VolatileMemberCollection(int initialCapacity) { - collectors = new ArrayList(initialCapacity); + collectors = new ArrayList(initialCapacity); nullArray = new int[initialCapacity]; } - public void add(Object member) { + public void add(E member) { synchronized (mutex) { if (nullIndex < 0) { ensureCapacity(); @@ -808,7 +808,7 @@ class PacketReader { } } - public void remove(Object member) { + public void remove(E member) { synchronized (mutex) { int index = collectors.lastIndexOf(member); if (index >= 0) { diff --git a/source/org/jivesoftware/smack/PacketWriter.java b/source/org/jivesoftware/smack/PacketWriter.java index 93cb37e68..d1c3bb8ec 100644 --- a/source/org/jivesoftware/smack/PacketWriter.java +++ b/source/org/jivesoftware/smack/PacketWriter.java @@ -41,10 +41,10 @@ class PacketWriter { private Thread writerThread; private Writer writer; private XMPPConnection connection; - final private LinkedList queue; + final private LinkedList queue; private boolean done = false; - final private List listeners = new ArrayList(); + final private List listeners = new ArrayList(); private boolean listenersDeleted = false; /** @@ -72,7 +72,7 @@ class PacketWriter { protected PacketWriter(XMPPConnection connection) { this.connection = connection; this.writer = connection.writer; - this.queue = new LinkedList(); + this.queue = new LinkedList(); writerThread = new Thread() { public void run() { @@ -130,7 +130,7 @@ class PacketWriter { public void removePacketListener(PacketListener packetListener) { synchronized (listeners) { for (int i=0; i 0) { - return (Packet)queue.removeLast(); + return queue.removeLast(); } else { return null; @@ -308,7 +308,7 @@ class PacketWriter { // Notify the listeners of the new sent packet int size = listeners.size(); for (int i=0; i groups; - private List entries; - private List unfiledEntries; - private List rosterListeners; - private Map presenceMap; + private final Map groups; + private final List entries; + private final List unfiledEntries; + private final List rosterListeners; + private Map> presenceMap; // The roster is marked as initialized when at least a single roster packet // has been recieved and processed. boolean rosterInitialized = false; @@ -81,11 +86,11 @@ public class Roster { private int subscriptionMode = getDefaultSubscriptionMode(); /** - * Returns the default subscription processing mode to use when a new Roster is created. The - * subscription processing mode dictates what action Smack will take when subscription - * requests from other users are made. The default subscription mode + * Returns the default subscription processing mode to use when a new Roster is created. The + * subscription processing mode dictates what action Smack will take when subscription + * requests from other users are made. The default subscription mode * is {@link #SUBSCRIPTION_ACCEPT_ALL}. - * + * * @return the default subscription mode to use for new Rosters */ public static int getDefaultSubscriptionMode() { @@ -93,9 +98,9 @@ public class Roster { } /** - * Sets the default subscription processing mode to use when a new Roster is created. The - * subscription processing mode dictates what action Smack will take when subscription - * requests from other users are made. The default subscription mode + * Sets the default subscription processing mode to use when a new Roster is created. The + * subscription processing mode dictates what action Smack will take when subscription + * requests from other users are made. The default subscription mode * is {@link #SUBSCRIPTION_ACCEPT_ALL}. * * @param subscriptionMode the default subscription mode to use for new Rosters. @@ -112,10 +117,10 @@ public class Roster { Roster(final XMPPConnection connection) { this.connection = connection; groups = new ConcurrentHashMap(); - unfiledEntries = new ArrayList(); - entries = new ArrayList(); + unfiledEntries = new ArrayList(); + entries = new ArrayList(); rosterListeners = new ArrayList(); - presenceMap = new HashMap(); + presenceMap = new HashMap>(); // Listen for any roster packets. PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class); connection.addPacketListener(new RosterPacketListener(), rosterFilter); @@ -230,9 +235,9 @@ public class Roster { rosterPacket.setType(IQ.Type.SET); RosterPacket.Item item = new RosterPacket.Item(user, name); if (groups != null) { - for (int i=0; i getUnfiledEntries() { synchronized (unfiledEntries) { - return Collections.unmodifiableList(new ArrayList(unfiledEntries)).iterator(); + return Collections.unmodifiableList(new ArrayList(unfiledEntries)) + .iterator(); } } @@ -362,8 +368,7 @@ public class Roster { } String userLowerCase = user.toLowerCase(); synchronized (entries) { - for (Iterator i=entries.iterator(); i.hasNext(); ) { - RosterEntry entry = (RosterEntry)i.next(); + for (RosterEntry entry : entries) { if (entry.getUser().equals(userLowerCase)) { return entry; } @@ -435,19 +440,19 @@ public class Roster { */ public Presence getPresence(String user) { String key = getPresenceMapKey(user); - Map userPresences = (Map) presenceMap.get(key); + Map userPresences = presenceMap.get(key); if (userPresences == null) { return null; } else { // Find the resource with the highest priority // Might be changed to use the resource with the highest availability instead. - Iterator it = userPresences.keySet().iterator(); + Iterator it = userPresences.keySet().iterator(); Presence p; Presence presence = null; while (it.hasNext()) { - p = (Presence) userPresences.get(it.next()); + p = userPresences.get(it.next()); if (presence == null) { presence = p; } @@ -473,12 +478,12 @@ public class Roster { public Presence getPresenceResource(String userResource) { String key = getPresenceMapKey(userResource); String resource = StringUtils.parseResource(userResource); - Map userPresences = (Map)presenceMap.get(key); + Map userPresences = presenceMap.get(key); if (userPresences == null) { return null; } else { - return (Presence) userPresences.get(resource); + return userPresences.get(resource); } } @@ -492,15 +497,15 @@ public class Roster { * or null if the user is unavailable or if no presence information * is available. */ - public Iterator getPresences(String user) { + public Iterator getPresences(String user) { String key = getPresenceMapKey(user); - Map userPresences = (Map)presenceMap.get(key); + Map userPresences = presenceMap.get(key); if (userPresences == null) { return null; } else { synchronized (userPresences) { - return new HashMap(userPresences).values().iterator(); + return new HashMap(userPresences).values().iterator(); } } } @@ -543,15 +548,15 @@ public class Roster { listeners = new RosterListener[rosterListeners.size()]; rosterListeners.toArray(listeners); } - for (int i=0; i userPresences; // Get the user presence map if (presenceMap.get(key) == null) { - userPresences = new HashMap(); + userPresences = new HashMap(); presenceMap.put(key, userPresences); } else { - userPresences = (Map)presenceMap.get(key); + userPresences = presenceMap.get(key); } // Add the new presence, using the resources as a key. synchronized (userPresences) { @@ -597,8 +602,7 @@ public class Roster { } // If the user is in the roster, fire an event. synchronized (entries) { - for (Iterator i = entries.iterator(); i.hasNext();) { - RosterEntry entry = (RosterEntry) i.next(); + for (RosterEntry entry : entries) { if (entry.getUser().equals(key)) { fireRosterPresenceEvent(from); } @@ -608,7 +612,7 @@ public class Roster { // If an "unavailable" packet, remove any entries in the presence map. else if (presence.getType() == Presence.Type.unavailable) { if (presenceMap.get(key) != null) { - Map userPresences = (Map) presenceMap.get(key); + Map userPresences = presenceMap.get(key); synchronized (userPresences) { userPresences.remove(StringUtils.parseResource(from)); } @@ -618,8 +622,7 @@ public class Roster { } // If the user is in the roster, fire an event. synchronized (entries) { - for (Iterator i=entries.iterator(); i.hasNext(); ) { - RosterEntry entry = (RosterEntry)i.next(); + for (RosterEntry entry : entries) { if (entry.getUser().equals(key)) { fireRosterPresenceEvent(from); } @@ -663,11 +666,11 @@ public class Roster { public void processPacket(Packet packet) { // Keep a registry of the entries that were added, deleted or updated. An event // will be fired for each affected entry - Collection addedEntries = new ArrayList(); - Collection updatedEntries = new ArrayList(); - Collection deletedEntries = new ArrayList(); + Collection addedEntries = new ArrayList(); + Collection updatedEntries = new ArrayList(); + Collection deletedEntries = new ArrayList(); - RosterPacket rosterPacket = (RosterPacket)packet; + RosterPacket rosterPacket = (RosterPacket) packet; for (RosterPacket.Item item : rosterPacket.getRosterItems()) { RosterEntry entry = new RosterEntry(item.getUser(), item.getName(), item.getItemType(), item.getItemStatus(), connection); @@ -701,8 +704,7 @@ public class Roster { } else { // If the entry was in then list then update its state with the new values - RosterEntry existingEntry = - (RosterEntry) entries.get(entries.indexOf(entry)); + RosterEntry existingEntry = entries.get(entries.indexOf(entry)); existingEntry .updateState(entry.getName(), entry.getType(), entry.getStatus()); // Keep note that an entry has been updated @@ -752,15 +754,14 @@ public class Roster { // We have the list of old and new group names. We now need to // remove the entry from the all the groups it may no longer belong // to. We do this by subracting the new group set from the old. - for (int m=0; m entries; + private final List entries; /** * Creates a new roster group instance. @@ -70,10 +73,9 @@ public class RosterGroup { */ public void setName(String name) { synchronized (entries) { - for (int i=0; i implementedMechanisms = new HashMap(); + private static List mechanismsPreferences = new ArrayList(); private XMPPConnection connection; - private Collection serverMechanisms = new ArrayList(); + private Collection serverMechanisms = new ArrayList(); private SASLMechanism currentMechanism = null; /** * Boolean indicating if SASL negotiation has finished and was successful. @@ -115,10 +115,10 @@ public class SASLAuthentication implements UserAuthentication { * * @return the registerd SASLMechanism classes sorted by the level of preference. */ - public static List getRegisterSASLMechanisms() { - List answer = new ArrayList(); - for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) { - answer.add(implementedMechanisms.get(it.next())); + public static List getRegisterSASLMechanisms() { + List answer = new ArrayList(); + for (String mechanismsPreference : mechanismsPreferences) { + answer.add(implementedMechanisms.get(mechanismsPreference)); } return answer; } @@ -171,11 +171,10 @@ public class SASLAuthentication implements UserAuthentication { throws XMPPException { // Locate the SASLMechanism to use Class selected = null; - for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) { - String mechanism = (String) it.next(); + for (String mechanism : mechanismsPreferences) { if (implementedMechanisms.containsKey(mechanism) && serverMechanisms.contains(mechanism)) { - selected = (Class) implementedMechanisms.get(mechanism); + selected = implementedMechanisms.get(mechanism); break; } } @@ -339,7 +338,7 @@ public class SASLAuthentication implements UserAuthentication { * @param mechanisms collection of strings with the available SASL mechanism reported * by the server. */ - void setAvailableSASLMethods(Collection mechanisms) { + void setAvailableSASLMethods(Collection mechanisms) { this.serverMechanisms = mechanisms; } diff --git a/source/org/jivesoftware/smack/SmackConfiguration.java b/source/org/jivesoftware/smack/SmackConfiguration.java index b3ccd2d7d..40500f442 100644 --- a/source/org/jivesoftware/smack/SmackConfiguration.java +++ b/source/org/jivesoftware/smack/SmackConfiguration.java @@ -63,8 +63,8 @@ public final class SmackConfiguration { try { // Get an array of class loaders to try loading the providers files from. ClassLoader[] classLoaders = getClassLoaders(); - for (int i = 0; i < classLoaders.length; i++) { - Enumeration configEnum = classLoaders[i].getResources("META-INF/smack-config.xml"); + for (ClassLoader classLoader : classLoaders) { + Enumeration configEnum = classLoader.getResources("META-INF/smack-config.xml"); while (configEnum.hasMoreElements()) { URL url = (URL) configEnum.nextElement(); InputStream systemStream = null; @@ -81,7 +81,8 @@ public final class SmackConfiguration { parseClassToLoad(parser); } else if (parser.getName().equals("packetReplyTimeout")) { - packetReplyTimeout = parseIntProperty(parser, packetReplyTimeout); + packetReplyTimeout = + parseIntProperty(parser, packetReplyTimeout); } else if (parser.getName().equals("keepAliveInterval")) { keepAliveInterval = parseIntProperty(parser, keepAliveInterval); @@ -200,7 +201,7 @@ public final class SmackConfiguration { */ private static ClassLoader[] getClassLoaders() { ClassLoader[] classLoaders = new ClassLoader[2]; - classLoaders[0] = new SmackConfiguration().getClass().getClassLoader(); + classLoaders[0] = SmackConfiguration.class.getClassLoader(); classLoaders[1] = Thread.currentThread().getContextClassLoader(); return classLoaders; } diff --git a/source/org/jivesoftware/smack/XMPPConnection.java b/source/org/jivesoftware/smack/XMPPConnection.java index 246a84ade..d7ed5fa25 100644 --- a/source/org/jivesoftware/smack/XMPPConnection.java +++ b/source/org/jivesoftware/smack/XMPPConnection.java @@ -39,7 +39,11 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.Socket; import java.net.UnknownHostException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * Creates a connection to a XMPP server. A simple use of this API might @@ -73,7 +77,8 @@ public class XMPPConnection { */ public static boolean DEBUG_ENABLED = false; - private static List connectionEstablishedListeners = new ArrayList(); + private final static List connectionEstablishedListeners = + new ArrayList(); static { // Use try block since we may not have permission to get a system @@ -128,7 +133,7 @@ public class XMPPConnection { * does not interfere with garbage collection. The map of chats must be stored * with each connection. */ - Map chats = Collections.synchronizedMap(new HashMap()); + Map> chats = new ConcurrentHashMap>(); /** * Collection of available stream compression methods offered by the server. @@ -289,7 +294,9 @@ public class XMPPConnection { // constructor it cannot be modified this.configuration = (ConnectionConfiguration) config.clone(); } - catch (CloneNotSupportedException e) {} + catch (CloneNotSupportedException e) { + // Do nothing + } init(); } @@ -419,7 +426,7 @@ public class XMPPConnection { // Do partial version of nameprep on the username. username = username.toLowerCase().trim(); - String response = null; + String response; if (configuration.isSASLAuthenticationEnabled() && saslAuthentication.hasNonAnonymousAuthentication()) { // Authenticate using SASL @@ -488,7 +495,7 @@ public class XMPPConnection { throw new IllegalStateException("Already logged in to server."); } - String response = null; + String response; if (configuration.isSASLAuthenticationEnabled() && saslAuthentication.hasAnonymousAuthentication()) { response = saslAuthentication.authenticateAnonymously(); @@ -876,12 +883,12 @@ public class XMPPConnection { if (message.getThread() == null && message.getType() != Message.Type.GROUP_CHAT && message.getType() != Message.Type.HEADLINE) { - WeakReference chatRef = (WeakReference)chats.get( - StringUtils.parseBareAddress(message.getFrom())); + WeakReference chatRef = + chats.get(StringUtils.parseBareAddress(message.getFrom())); if (chatRef != null) { // Do some extra clean-up if the reference was cleared. - Chat chat; - if ((chat = (Chat)chatRef.get()) == null) { + Chat chat = chatRef.get(); + if (chat == null) { chats.remove(message.getFrom()); } else { @@ -931,9 +938,9 @@ public class XMPPConnection { } else { try { - Class zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream"); + Class zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream"); //ZOutputStream out = new ZOutputStream(socket.getOutputStream(), JZlib.Z_BEST_COMPRESSION); - Constructor constructor = + Constructor constructor = zoClass.getConstructor(new Class[]{OutputStream.class, Integer.TYPE}); Object out = constructor.newInstance(new Object[] {socket.getOutputStream(), new Integer(9)}); //out.setFlushMode(JZlib.Z_PARTIAL_FLUSH); @@ -941,7 +948,7 @@ public class XMPPConnection { method.invoke(out, new Object[] {new Integer(1)}); writer = new BufferedWriter(new OutputStreamWriter((OutputStream) out, "UTF-8")); - Class ziClass = Class.forName("com.jcraft.jzlib.ZInputStream"); + Class ziClass = Class.forName("com.jcraft.jzlib.ZInputStream"); //ZInputStream in = new ZInputStream(socket.getInputStream()); constructor = ziClass.getConstructor(new Class[]{InputStream.class}); Object in = constructor.newInstance(new Object[] {socket.getInputStream()}); @@ -976,7 +983,7 @@ public class XMPPConnection { } catch (Throwable t) { } - Class debuggerClass = null; + Class debuggerClass = null; if (className != null) { try { debuggerClass = Class.forName(className); @@ -1002,7 +1009,7 @@ public class XMPPConnection { // Create a new debugger instance. If an exception occurs then disable the debugging // option try { - Constructor constructor = + Constructor constructor = debuggerClass.getConstructor( new Class[] { XMPPConnection.class, Writer.class, Reader.class }); debugger = (SmackDebugger) constructor @@ -1027,13 +1034,13 @@ public class XMPPConnection { * Fires listeners on connection established events. */ private static void connectionEstablished(XMPPConnection connection) { - ConnectionEstablishedListener[] listeners = null; + ConnectionEstablishedListener[] listeners; synchronized (connectionEstablishedListeners) { listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()]; connectionEstablishedListeners.toArray(listeners); } - for (int i = 0; i < listeners.length; i++) { - listeners[i].connectionEstablished(connection); + for (ConnectionEstablishedListener listener : listeners) { + listener.connectionEstablished(connection); } } diff --git a/source/org/jivesoftware/smack/XMPPException.java b/source/org/jivesoftware/smack/XMPPException.java index 5b60220ba..1e875b295 100644 --- a/source/org/jivesoftware/smack/XMPPException.java +++ b/source/org/jivesoftware/smack/XMPPException.java @@ -20,8 +20,8 @@ package org.jivesoftware.smack; -import org.jivesoftware.smack.packet.XMPPError; import org.jivesoftware.smack.packet.StreamError; +import org.jivesoftware.smack.packet.XMPPError; import java.io.PrintStream; import java.io.PrintWriter; @@ -199,7 +199,7 @@ public class XMPPException extends Exception { } public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); String message = super.getMessage(); if (message != null) { buf.append(message).append(": "); diff --git a/source/org/jivesoftware/smack/packet/Authentication.java b/source/org/jivesoftware/smack/packet/Authentication.java index dce690b40..723e4e445 100644 --- a/source/org/jivesoftware/smack/packet/Authentication.java +++ b/source/org/jivesoftware/smack/packet/Authentication.java @@ -146,7 +146,7 @@ public class Authentication extends IQ { } public String getChildElementXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(""); if (username != null) { if (username.equals("")) { diff --git a/source/org/jivesoftware/smack/packet/Bind.java b/source/org/jivesoftware/smack/packet/Bind.java index 9d589b921..74875fef8 100644 --- a/source/org/jivesoftware/smack/packet/Bind.java +++ b/source/org/jivesoftware/smack/packet/Bind.java @@ -57,7 +57,7 @@ public class Bind extends IQ { } public String getChildElementXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(""); if (resource != null) { buf.append("").append(resource).append(""); diff --git a/source/org/jivesoftware/smack/packet/DefaultPacketExtension.java b/source/org/jivesoftware/smack/packet/DefaultPacketExtension.java index cbf1b5efe..3a04356ae 100644 --- a/source/org/jivesoftware/smack/packet/DefaultPacketExtension.java +++ b/source/org/jivesoftware/smack/packet/DefaultPacketExtension.java @@ -20,7 +20,10 @@ package org.jivesoftware.smack.packet; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** * Default implementation of the PacketExtension interface. Unless a PacketExtensionProvider @@ -80,7 +83,7 @@ public class DefaultPacketExtension implements PacketExtension { } public String toXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">"); for (Iterator i=getNames(); i.hasNext(); ) { String name = (String)i.next(); diff --git a/source/org/jivesoftware/smack/packet/IQ.java b/source/org/jivesoftware/smack/packet/IQ.java index 926e4e422..5b9dfe62a 100644 --- a/source/org/jivesoftware/smack/packet/IQ.java +++ b/source/org/jivesoftware/smack/packet/IQ.java @@ -67,7 +67,7 @@ public abstract class IQ extends Packet { } public String toXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(" attributes = null; /** * Returns the registration instructions, or null if no instructions @@ -76,7 +75,7 @@ public class Registration extends IQ { * * @return the account attributes. */ - public Map getAttributes() { + public Map getAttributes() { return attributes; } @@ -85,21 +84,19 @@ public class Registration extends IQ { * * @param attributes the account attributes. */ - public void setAttributes(Map attributes) { + public void setAttributes(Map attributes) { this.attributes = attributes; } public String getChildElementXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(""); if (instructions != null) { buf.append("").append(instructions).append(""); } if (attributes != null && attributes.size() > 0) { - Iterator fieldNames = attributes.keySet().iterator(); - while (fieldNames.hasNext()) { - String name = (String)fieldNames.next(); - String value = (String)attributes.get(name); + for (String name : attributes.keySet()) { + String value = attributes.get(name); buf.append("<").append(name).append(">"); buf.append(value); buf.append(""); diff --git a/source/org/jivesoftware/smack/packet/RosterPacket.java b/source/org/jivesoftware/smack/packet/RosterPacket.java index 5b0502815..53c738349 100644 --- a/source/org/jivesoftware/smack/packet/RosterPacket.java +++ b/source/org/jivesoftware/smack/packet/RosterPacket.java @@ -68,7 +68,7 @@ public class RosterPacket extends IQ { } public String getChildElementXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(""); synchronized (rosterItems) { for (Item entry : rosterItems) { @@ -197,7 +197,7 @@ public class RosterPacket extends IQ { } public String toXML() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(""); if (message != null) { buf.append(message); @@ -107,7 +107,7 @@ public class XMPPError { } public String toString() { - StringBuffer txt = new StringBuffer(); + StringBuilder txt = new StringBuilder(); txt.append("(").append(code).append(")"); if (message != null) { txt.append(" ").append(message); diff --git a/source/org/jivesoftware/smack/provider/ProviderManager.java b/source/org/jivesoftware/smack/provider/ProviderManager.java index f7cd792da..4149a05e4 100644 --- a/source/org/jivesoftware/smack/provider/ProviderManager.java +++ b/source/org/jivesoftware/smack/provider/ProviderManager.java @@ -22,11 +22,12 @@ package org.jivesoftware.smack.provider; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.PacketExtension; -import org.xmlpull.v1.*; import org.xmlpull.mxp1.MXParser; +import org.xmlpull.v1.XmlPullParser; -import java.util.*; +import java.io.InputStream; import java.net.URL; +import java.util.*; /** * Manages providers for parsing custom XML sub-documents of XMPP packets. Two types of @@ -117,12 +118,12 @@ public class ProviderManager { try { // Get an array of class loaders to try loading the providers files from. ClassLoader[] classLoaders = getClassLoaders(); - for (int i=0; i<").append(namespace).append("/>"); return buf.toString(); } diff --git a/source/org/jivesoftware/smack/sasl/SASLMechanism.java b/source/org/jivesoftware/smack/sasl/SASLMechanism.java index 2b775456a..9a2771f62 100644 --- a/source/org/jivesoftware/smack/sasl/SASLMechanism.java +++ b/source/org/jivesoftware/smack/sasl/SASLMechanism.java @@ -55,7 +55,7 @@ public abstract class SASLMechanism { */ public void authenticate(String username, String host, String password) throws IOException { // Build the authentication stanza encoding the authentication text - StringBuffer stanza = new StringBuffer(); + StringBuilder stanza = new StringBuilder(); stanza.append(""); String authenticationText = getAuthenticationText(username, host, password); @@ -76,7 +76,7 @@ public abstract class SASLMechanism { */ public void challengeReceived(String challenge) throws IOException { // Build the challenge response stanza encoding the response text - StringBuffer stanza = new StringBuffer(); + StringBuilder stanza = new StringBuilder(); stanza.append(""); String authenticationText = getChallengeResponse(StringUtils.decodeBase64(challenge)); if (authenticationText != null) { diff --git a/source/org/jivesoftware/smack/sasl/SASLPlainMechanism.java b/source/org/jivesoftware/smack/sasl/SASLPlainMechanism.java index 7c534216d..ccd257461 100644 --- a/source/org/jivesoftware/smack/sasl/SASLPlainMechanism.java +++ b/source/org/jivesoftware/smack/sasl/SASLPlainMechanism.java @@ -42,7 +42,7 @@ public class SASLPlainMechanism extends SASLMechanism { protected String getAuthenticationText(String username, String host, String password) { // Build the text containing the "authorization identity" + NUL char + // "authentication identity" + NUL char + "clear-text password" - StringBuffer text = new StringBuffer(); + StringBuilder text = new StringBuilder(); text.append(username).append("@").append(host); text.append('\0'); text.append(username); diff --git a/source/org/jivesoftware/smack/util/Cache.java b/source/org/jivesoftware/smack/util/Cache.java index 009e23b8a..f4cbaeede 100644 --- a/source/org/jivesoftware/smack/util/Cache.java +++ b/source/org/jivesoftware/smack/util/Cache.java @@ -549,7 +549,7 @@ public class Cache implements Map { */ public String toString() { LinkedListNode node = head.next; - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); while (node != head) { buf.append(node.toString()).append(", "); node = node.next; diff --git a/source/org/jivesoftware/smack/util/StringUtils.java b/source/org/jivesoftware/smack/util/StringUtils.java index 629be2931..d0d685788 100644 --- a/source/org/jivesoftware/smack/util/StringUtils.java +++ b/source/org/jivesoftware/smack/util/StringUtils.java @@ -20,9 +20,9 @@ package org.jivesoftware.smack.util; +import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.io.UnsupportedEncodingException; import java.util.Random; /** @@ -143,7 +143,7 @@ public class StringUtils { int last=0; char[] input = string.toCharArray(); int len = input.length; - StringBuffer out = new StringBuffer((int)(len*1.3)); + StringBuilder out = new StringBuilder((int)(len*1.3)); for (; i < len; i++) { ch = input[i]; if (ch > '>') { @@ -243,13 +243,13 @@ public class StringUtils { * @return generated hex string. */ public static String encodeHex(byte[] bytes) { - StringBuffer hex = new StringBuffer(bytes.length * 2); + StringBuilder hex = new StringBuilder(bytes.length * 2); - for (int i=0; i @@ -334,8 +338,8 @@ public class Form { // Clear the old values field.resetValues(); // Set the default value - for (Iterator it = field.getValues(); it.hasNext();) { - field.addValue((String) it.next()); + for (Iterator it = field.getValues(); it.hasNext();) { + field.addValue(it.next()); } } else { @@ -348,7 +352,7 @@ public class Form { * * @return an Iterator for the fields that are part of the form. */ - public Iterator getFields() { + public Iterator getFields() { return dataForm.getFields(); } @@ -366,8 +370,8 @@ public class Form { } // Look for the field whose variable matches the requested variable FormField field; - for (Iterator it=getFields();it.hasNext();) { - field = (FormField)it.next(); + for (Iterator it=getFields();it.hasNext();) { + field = it.next(); if (variable.equals(field.getVariable())) { return field; } @@ -381,7 +385,7 @@ public class Form { * @return instructions that explain how to fill out the form. */ public String getInstructions() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); // Join the list of instructions together separated by newlines for (Iterator it = dataForm.getInstructions(); it.hasNext();) { sb.append((String) it.next()); @@ -432,7 +436,7 @@ public class Form { */ public void setInstructions(String instructions) { // Split the instructions into multiple instructions for each existent newline - ArrayList instructionsList = new ArrayList(); + ArrayList instructionsList = new ArrayList(); StringTokenizer st = new StringTokenizer(instructions, "\n"); while (st.hasMoreTokens()) { instructionsList.add(st.nextToken()); @@ -464,8 +468,8 @@ public class Form { if (isSubmitType()) { // Create a new DataForm that contains only the answered fields DataForm dataFormToSend = new DataForm(getType()); - for(Iterator it=getFields();it.hasNext();) { - FormField field = (FormField)it.next(); + for(Iterator it=getFields();it.hasNext();) { + FormField field = it.next(); if (field.getValues().hasNext()) { dataFormToSend.addField(field); } @@ -513,8 +517,8 @@ public class Form { } // Create a new Form Form form = new Form(TYPE_SUBMIT); - for (Iterator fields=getFields(); fields.hasNext();) { - FormField field = (FormField)fields.next(); + for (Iterator fields=getFields(); fields.hasNext();) { + FormField field = fields.next(); // Add to the new form any type of field that includes a variable. // Note: The fields of type FIXED are the only ones that don't specify a variable if (field.getVariable() != null) { @@ -525,9 +529,9 @@ public class Form { if (FormField.TYPE_HIDDEN.equals(field.getType())) { // Since a hidden field could have many values we need to collect them // in a list - List values = new ArrayList(); - for (Iterator it=field.getValues();it.hasNext();) { - values.add((String)it.next()); + List values = new ArrayList(); + for (Iterator it=field.getValues();it.hasNext();) { + values.add(it.next()); } form.setAnswer(field.getVariable(), values); } diff --git a/source/org/jivesoftware/smackx/FormField.java b/source/org/jivesoftware/smackx/FormField.java index c8fafb965..643ca7a91 100644 --- a/source/org/jivesoftware/smackx/FormField.java +++ b/source/org/jivesoftware/smackx/FormField.java @@ -20,7 +20,10 @@ package org.jivesoftware.smackx; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; /** * Represents a field of a form. The field could be used to represent a question to complete, @@ -46,8 +49,8 @@ public class FormField { private String label; private String variable; private String type; - private List options = new ArrayList(); - private List values = new ArrayList(); + private final List