1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-26 14:02:06 +01:00

1. Clean up code

2. Refactoring work
3. Optimization work. SMACK-153
4. Fixed roster test cases. SMACK-154
4. Fixed vCard issue. SMACK-152

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@4538 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Gaston Dombiak 2006-07-18 05:14:33 +00:00 committed by gato
parent 14b50d790a
commit f57ff10ad9
77 changed files with 995 additions and 932 deletions

View file

@ -20,12 +20,18 @@
package org.jivesoftware.smack; 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.packet.IQ;
import org.jivesoftware.smack.filter.*; import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils; 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. * Allows creation and management of accounts on an XMPP server.
@ -90,17 +96,19 @@ public class AccountManager {
* *
* @return the required account attributes. * @return the required account attributes.
*/ */
public Iterator getAccountAttributes() { public Iterator<String> getAccountAttributes() {
try { try {
if (info == null) { if (info == null) {
getRegistrationInfo(); getRegistrationInfo();
} }
Map attributes = info.getAttributes(); Map<String, String> attributes = info.getAttributes();
if (attributes != null) { if (attributes != null) {
return attributes.keySet().iterator(); return attributes.keySet().iterator();
} }
} }
catch (XMPPException xe) { } catch (XMPPException xe) {
xe.printStackTrace();
}
return Collections.EMPTY_LIST.iterator(); return Collections.EMPTY_LIST.iterator();
} }
@ -117,9 +125,11 @@ public class AccountManager {
if (info == null) { if (info == null) {
getRegistrationInfo(); getRegistrationInfo();
} }
return (String) info.getAttributes().get(name); return info.getAttributes().get(name);
}
catch (XMPPException xe) {
xe.printStackTrace();
} }
catch (XMPPException xe) { }
return null; return null;
} }
@ -159,9 +169,9 @@ public class AccountManager {
throw new XMPPException("Server does not support account creation."); throw new XMPPException("Server does not support account creation.");
} }
// Create a map for all the required attributes, but give them blank values. // Create a map for all the required attributes, but give them blank values.
Map attributes = new HashMap(); Map<String, String> attributes = new HashMap<String, String>();
for (Iterator i=getAccountAttributes(); i.hasNext(); ) { for (Iterator<String> i=getAccountAttributes(); i.hasNext(); ) {
String attributeName = (String)i.next(); String attributeName = i.next();
attributes.put(attributeName, ""); attributes.put(attributeName, "");
} }
createAccount(username, password, attributes); createAccount(username, password, attributes);
@ -178,7 +188,7 @@ public class AccountManager {
* @throws XMPPException if an error occurs creating the account. * @throws XMPPException if an error occurs creating the account.
* @see #getAccountAttributes() * @see #getAccountAttributes()
*/ */
public void createAccount(String username, String password, Map attributes) public void createAccount(String username, String password, Map<String, String> attributes)
throws XMPPException throws XMPPException
{ {
if (!supportsAccountCreation()) { if (!supportsAccountCreation()) {
@ -217,7 +227,7 @@ public class AccountManager {
Registration reg = new Registration(); Registration reg = new Registration();
reg.setType(IQ.Type.SET); reg.setType(IQ.Type.SET);
reg.setTo(connection.getServiceName()); reg.setTo(connection.getServiceName());
HashMap map = new HashMap(); Map<String, String> map = new HashMap<String, String>();
map.put("username",StringUtils.parseName(connection.getUser())); map.put("username",StringUtils.parseName(connection.getUser()));
map.put("password",newPassword); map.put("password",newPassword);
reg.setAttributes(map); reg.setAttributes(map);
@ -251,7 +261,7 @@ public class AccountManager {
Registration reg = new Registration(); Registration reg = new Registration();
reg.setType(IQ.Type.SET); reg.setType(IQ.Type.SET);
reg.setTo(connection.getServiceName()); reg.setTo(connection.getServiceName());
Map attributes = new HashMap(); Map<String, String> attributes = new HashMap<String, String>();
// To delete an account, we add a single attribute, "remove", that is blank. // To delete an account, we add a single attribute, "remove", that is blank.
attributes.put("remove", ""); attributes.put("remove", "");
reg.setAttributes(attributes); reg.setAttributes(attributes);

View file

@ -20,12 +20,15 @@
package org.jivesoftware.smack; 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.packet.Message;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.filter.*;
import java.util.*;
import java.lang.ref.WeakReference; 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 * 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 String participant;
private PacketFilter messageFilter; private PacketFilter messageFilter;
private PacketCollector messageCollector; private PacketCollector messageCollector;
private Set listeners = new HashSet(); private final Set<WeakReference<PacketListener>> listeners =
new HashSet<WeakReference<PacketListener>>();
/** /**
* Creates a new chat with the specified user. * 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 // Register with the map of chats so that messages with no thread ID
// set will be delivered to this Chat. // set will be delivered to this Chat.
connection.chats.put(StringUtils.parseBareAddress(participant), connection.chats.put(StringUtils.parseBareAddress(participant),
new WeakReference(this)); new WeakReference<Chat>(this));
// Filter the messages whose thread equals Chat's id // Filter the messages whose thread equals Chat's id
messageFilter = new ThreadFilter(threadID); messageFilter = new ThreadFilter(threadID);
@ -222,7 +226,7 @@ public class Chat {
// Keep track of the listener so that we can manually deliver extra // Keep track of the listener so that we can manually deliver extra
// messages to it later if needed. // messages to it later if needed.
synchronized (listeners) { synchronized (listeners) {
listeners.add(new WeakReference(listener)); listeners.add(new WeakReference<PacketListener>(listener));
} }
} }
@ -242,10 +246,10 @@ public class Chat {
messageCollector.processPacket(message); messageCollector.processPacket(message);
synchronized (listeners) { synchronized (listeners) {
for (Iterator i=listeners.iterator(); i.hasNext(); ) { for (Iterator<WeakReference<PacketListener>> i=listeners.iterator(); i.hasNext(); ) {
WeakReference listenerRef = (WeakReference)i.next(); WeakReference<PacketListener> listenerRef = i.next();
PacketListener listener; PacketListener listener;
if ((listener = (PacketListener)listenerRef.get()) != null) { if ((listener = listenerRef.get()) != null) {
listener.processPacket(message); listener.processPacket(message);
} }
// If the reference was cleared, remove it from the set. // If the reference was cleared, remove it from the set.

View file

@ -62,7 +62,7 @@ public class ConnectionConfiguration implements Cloneable {
// Build the default path to the cacert truststore file. By default we are // Build the default path to the cacert truststore file. By default we are
// going to use the file located in $JREHOME/lib/security/cacerts. // going to use the file located in $JREHOME/lib/security/cacerts.
String javaHome = System.getProperty("java.home"); String javaHome = System.getProperty("java.home");
StringBuffer buffer = new StringBuffer(); StringBuilder buffer = new StringBuilder();
buffer.append(javaHome).append(File.separator).append("lib"); buffer.append(javaHome).append(File.separator).append("lib");
buffer.append(File.separator).append("security"); buffer.append(File.separator).append("security");
buffer.append(File.separator).append("cacerts"); buffer.append(File.separator).append("cacerts");

View file

@ -48,7 +48,7 @@ public class PacketCollector {
private static final int MAX_PACKETS = 65536; private static final int MAX_PACKETS = 65536;
private PacketFilter packetFilter; private PacketFilter packetFilter;
private LinkedList resultQueue; private LinkedList<Packet> resultQueue;
private PacketReader packetReader; private PacketReader packetReader;
private boolean cancelled = false; private boolean cancelled = false;
@ -62,7 +62,7 @@ public class PacketCollector {
protected PacketCollector(PacketReader packetReader, PacketFilter packetFilter) { protected PacketCollector(PacketReader packetReader, PacketFilter packetFilter) {
this.packetReader = packetReader; this.packetReader = packetReader;
this.packetFilter = packetFilter; this.packetFilter = packetFilter;
this.resultQueue = new LinkedList(); this.resultQueue = new LinkedList<Packet>();
} }
/** /**
@ -101,7 +101,7 @@ public class PacketCollector {
return null; return null;
} }
else { else {
return (Packet)resultQueue.removeLast(); return resultQueue.removeLast();
} }
} }
@ -121,7 +121,7 @@ public class PacketCollector {
// Ignore. // Ignore.
} }
} }
return (Packet)resultQueue.removeLast(); return resultQueue.removeLast();
} }
/** /**
@ -159,12 +159,12 @@ public class PacketCollector {
} }
// Return the packet that was found. // Return the packet that was found.
else { else {
return (Packet)resultQueue.removeLast(); return resultQueue.removeLast();
} }
} }
// There's already a packet waiting, so return it. // There's already a packet waiting, so return it.
else { else {
return (Packet)resultQueue.removeLast(); return resultQueue.removeLast();
} }
} }

View file

@ -48,9 +48,11 @@ class PacketReader {
private XMPPConnection connection; private XMPPConnection connection;
private XmlPullParser parser; private XmlPullParser parser;
private boolean done = false; private boolean done = false;
private final VolatileMemberCollection collectors = new VolatileMemberCollection(50); private final VolatileMemberCollection<PacketCollector> collectors =
new VolatileMemberCollection<PacketCollector>(50);
private final VolatileMemberCollection listeners = new VolatileMemberCollection(50); private final VolatileMemberCollection listeners = new VolatileMemberCollection(50);
protected final List connectionListeners = new ArrayList(); protected final List<ConnectionListener> connectionListeners =
new ArrayList<ConnectionListener>();
private String connectionID = null; private String connectionID = null;
private final Object connectionIDLock = new Object(); private final Object connectionIDLock = new Object();
@ -176,12 +178,11 @@ class PacketReader {
public void shutdown() { public void shutdown() {
// Notify connection listeners of the connection closing if done hasn't already been set. // Notify connection listeners of the connection closing if done hasn't already been set.
if (!done) { if (!done) {
ArrayList listenersCopy; List<ConnectionListener> listenersCopy;
synchronized (connectionListeners) { synchronized (connectionListeners) {
// Make a copy since it's possible that a listener will be removed from the list // Make a copy since it's possible that a listener will be removed from the list
listenersCopy = new ArrayList(connectionListeners); listenersCopy = new ArrayList<ConnectionListener>(connectionListeners);
for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) { for (ConnectionListener listener : listenersCopy) {
ConnectionListener listener = (ConnectionListener)i.next();
listener.connectionClosed(); listener.connectionClosed();
} }
} }
@ -206,12 +207,11 @@ class PacketReader {
// Print the stack trace to help catch the problem // Print the stack trace to help catch the problem
e.printStackTrace(); e.printStackTrace();
// Notify connection listeners of the error. // Notify connection listeners of the error.
ArrayList listenersCopy; List<ConnectionListener> listenersCopy;
synchronized (connectionListeners) { synchronized (connectionListeners) {
// Make a copy since it's possible that a listener will be removed from the list // Make a copy since it's possible that a listener will be removed from the list
listenersCopy = new ArrayList(connectionListeners); listenersCopy = new ArrayList<ConnectionListener>(connectionListeners);
for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) { for (ConnectionListener listener : listenersCopy) {
ConnectionListener listener = (ConnectionListener)i.next();
listener.connectionClosedOnError(e); listener.connectionClosedOnError(e);
} }
} }
@ -489,8 +489,8 @@ class PacketReader {
* @return a collection of Stings with the mechanisms included in the mechanisms stanza. * @return a collection of Stings with the mechanisms included in the mechanisms stanza.
* @throws Exception if an exception occurs while parsing the stanza. * @throws Exception if an exception occurs while parsing the stanza.
*/ */
private Collection parseMechanisms(XmlPullParser parser) throws Exception { private Collection<String> parseMechanisms(XmlPullParser parser) throws Exception {
List mechanisms = new ArrayList(); List<String> mechanisms = new ArrayList<String>();
boolean done = false; boolean done = false;
while (!done) { while (!done) {
int eventType = parser.next(); int eventType = parser.next();
@ -510,9 +510,9 @@ class PacketReader {
return mechanisms; return mechanisms;
} }
private Collection parseCompressionMethods(XmlPullParser parser) private Collection<String> parseCompressionMethods(XmlPullParser parser)
throws IOException, XmlPullParserException { throws IOException, XmlPullParserException {
List methods = new ArrayList(); List<String> methods = new ArrayList<String>();
boolean done = false; boolean done = false;
while (!done) { while (!done) {
int eventType = parser.next(); int eventType = parser.next();
@ -698,7 +698,7 @@ class PacketReader {
private Registration parseRegistration(XmlPullParser parser) throws Exception { private Registration parseRegistration(XmlPullParser parser) throws Exception {
Registration registration = new Registration(); Registration registration = new Registration();
Map fields = null; Map<String, String> fields = null;
boolean done = false; boolean done = false;
while (!done) { while (!done) {
int eventType = parser.next(); int eventType = parser.next();
@ -709,7 +709,7 @@ class PacketReader {
String name = parser.getName(); String name = parser.getName();
String value = ""; String value = "";
if (fields == null) { if (fields == null) {
fields = new HashMap(); fields = new HashMap<String, String>();
} }
if (parser.next() == XmlPullParser.TEXT) { 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 * volatile. In other words, many are added and deleted and 'null' values are skipped by the
* returned iterator. * returned iterator.
*/ */
static class VolatileMemberCollection { static class VolatileMemberCollection<E> {
private final Object mutex = new Object(); private final Object mutex = new Object();
private final ArrayList collectors; private final ArrayList<E> collectors;
private int nullIndex = -1; private int nullIndex = -1;
private int[] nullArray; private int[] nullArray;
VolatileMemberCollection(int initialCapacity) { VolatileMemberCollection(int initialCapacity) {
collectors = new ArrayList(initialCapacity); collectors = new ArrayList<E>(initialCapacity);
nullArray = new int[initialCapacity]; nullArray = new int[initialCapacity];
} }
public void add(Object member) { public void add(E member) {
synchronized (mutex) { synchronized (mutex) {
if (nullIndex < 0) { if (nullIndex < 0) {
ensureCapacity(); ensureCapacity();
@ -808,7 +808,7 @@ class PacketReader {
} }
} }
public void remove(Object member) { public void remove(E member) {
synchronized (mutex) { synchronized (mutex) {
int index = collectors.lastIndexOf(member); int index = collectors.lastIndexOf(member);
if (index >= 0) { if (index >= 0) {

View file

@ -41,10 +41,10 @@ class PacketWriter {
private Thread writerThread; private Thread writerThread;
private Writer writer; private Writer writer;
private XMPPConnection connection; private XMPPConnection connection;
final private LinkedList queue; final private LinkedList<Packet> queue;
private boolean done = false; private boolean done = false;
final private List listeners = new ArrayList(); final private List<ListenerWrapper> listeners = new ArrayList<ListenerWrapper>();
private boolean listenersDeleted = false; private boolean listenersDeleted = false;
/** /**
@ -72,7 +72,7 @@ class PacketWriter {
protected PacketWriter(XMPPConnection connection) { protected PacketWriter(XMPPConnection connection) {
this.connection = connection; this.connection = connection;
this.writer = connection.writer; this.writer = connection.writer;
this.queue = new LinkedList(); this.queue = new LinkedList<Packet>();
writerThread = new Thread() { writerThread = new Thread() {
public void run() { public void run() {
@ -130,7 +130,7 @@ class PacketWriter {
public void removePacketListener(PacketListener packetListener) { public void removePacketListener(PacketListener packetListener) {
synchronized (listeners) { synchronized (listeners) {
for (int i=0; i<listeners.size(); i++) { for (int i=0; i<listeners.size(); i++) {
ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i); ListenerWrapper wrapper = listeners.get(i);
if (wrapper != null && wrapper.packetListener.equals(packetListener)) { if (wrapper != null && wrapper.packetListener.equals(packetListener)) {
listeners.set(i, null); listeners.set(i, null);
// Set the flag to indicate that the listener list needs // Set the flag to indicate that the listener list needs
@ -239,7 +239,7 @@ class PacketWriter {
} }
} }
if (queue.size() > 0) { if (queue.size() > 0) {
return (Packet)queue.removeLast(); return queue.removeLast();
} }
else { else {
return null; return null;
@ -308,7 +308,7 @@ class PacketWriter {
// Notify the listeners of the new sent packet // Notify the listeners of the new sent packet
int size = listeners.size(); int size = listeners.size();
for (int i=0; i<size; i++) { for (int i=0; i<size; i++) {
ListenerWrapper listenerWrapper = (ListenerWrapper)listeners.get(i); ListenerWrapper listenerWrapper = listeners.get(i);
if (listenerWrapper != null) { if (listenerWrapper != null) {
listenerWrapper.notifyListener(packet); listenerWrapper.notifyListener(packet);
} }
@ -357,7 +357,7 @@ class PacketWriter {
* @throws IOException If an error occurs while sending the stanza to the server. * @throws IOException If an error occurs while sending the stanza to the server.
*/ */
void openStream() throws IOException { void openStream() throws IOException {
StringBuffer stream = new StringBuffer(); StringBuilder stream = new StringBuilder();
stream.append("<stream:stream"); stream.append("<stream:stream");
stream.append(" to=\"").append(connection.serviceName).append("\""); stream.append(" to=\"").append(connection.serviceName).append("\"");
stream.append(" xmlns=\"jabber:client\""); stream.append(" xmlns=\"jabber:client\"");

View file

@ -20,8 +20,13 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.*; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import java.util.*; import java.util.*;
@ -63,17 +68,17 @@ public class Roster {
public static final int SUBSCRIPTION_MANUAL = 2; public static final int SUBSCRIPTION_MANUAL = 2;
/** /**
* The default subscription processing mode to use when a Roster is created. By default * The default subscription processing mode to use when a Roster is created. By default
* all subscription requests are automatically accepted. * all subscription requests are automatically accepted.
*/ */
private static int defaultSubscriptionMode = SUBSCRIPTION_ACCEPT_ALL; private static int defaultSubscriptionMode = SUBSCRIPTION_ACCEPT_ALL;
private XMPPConnection connection; private XMPPConnection connection;
private Map<String,RosterGroup> groups; private final Map<String, RosterGroup> groups;
private List entries; private final List<RosterEntry> entries;
private List unfiledEntries; private final List<RosterEntry> unfiledEntries;
private List<RosterListener> rosterListeners; private final List<RosterListener> rosterListeners;
private Map presenceMap; private Map<String, Map<String, Presence>> presenceMap;
// The roster is marked as initialized when at least a single roster packet // The roster is marked as initialized when at least a single roster packet
// has been recieved and processed. // has been recieved and processed.
boolean rosterInitialized = false; boolean rosterInitialized = false;
@ -81,11 +86,11 @@ public class Roster {
private int subscriptionMode = getDefaultSubscriptionMode(); private int subscriptionMode = getDefaultSubscriptionMode();
/** /**
* Returns the default subscription processing mode to use when a new Roster is created. The * 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 * subscription processing mode dictates what action Smack will take when subscription
* requests from other users are made. The default subscription mode * requests from other users are made. The default subscription mode
* is {@link #SUBSCRIPTION_ACCEPT_ALL}. * is {@link #SUBSCRIPTION_ACCEPT_ALL}.
* *
* @return the default subscription mode to use for new Rosters * @return the default subscription mode to use for new Rosters
*/ */
public static int getDefaultSubscriptionMode() { 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 * 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 * subscription processing mode dictates what action Smack will take when subscription
* requests from other users are made. The default subscription mode * requests from other users are made. The default subscription mode
* is {@link #SUBSCRIPTION_ACCEPT_ALL}. * is {@link #SUBSCRIPTION_ACCEPT_ALL}.
* *
* @param subscriptionMode the default subscription mode to use for new Rosters. * @param subscriptionMode the default subscription mode to use for new Rosters.
@ -112,10 +117,10 @@ public class Roster {
Roster(final XMPPConnection connection) { Roster(final XMPPConnection connection) {
this.connection = connection; this.connection = connection;
groups = new ConcurrentHashMap<String,RosterGroup>(); groups = new ConcurrentHashMap<String,RosterGroup>();
unfiledEntries = new ArrayList(); unfiledEntries = new ArrayList<RosterEntry>();
entries = new ArrayList(); entries = new ArrayList<RosterEntry>();
rosterListeners = new ArrayList<RosterListener>(); rosterListeners = new ArrayList<RosterListener>();
presenceMap = new HashMap(); presenceMap = new HashMap<String, Map<String, Presence>>();
// Listen for any roster packets. // Listen for any roster packets.
PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class); PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class);
connection.addPacketListener(new RosterPacketListener(), rosterFilter); connection.addPacketListener(new RosterPacketListener(), rosterFilter);
@ -230,9 +235,9 @@ public class Roster {
rosterPacket.setType(IQ.Type.SET); rosterPacket.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item(user, name); RosterPacket.Item item = new RosterPacket.Item(user, name);
if (groups != null) { if (groups != null) {
for (int i=0; i<groups.length; i++) { for (String group : groups) {
if (groups[i] != null) { if (group != null) {
item.addGroupName(groups[i]); item.addGroupName(group);
} }
} }
} }
@ -258,7 +263,7 @@ public class Roster {
} }
/** /**
* Removes a roster entry from the roster. The roster entry will also be removed from the * Removes a roster entry from the roster. The roster entry will also be removed from the
* unfiled entries or from any roster group where it could belong and will no longer be part * unfiled entries or from any roster group where it could belong and will no longer be part
* of the roster. Note that this is an asynchronous call -- Smack must wait for the server * of the roster. Note that this is an asynchronous call -- Smack must wait for the server
* to send an updated subscription status. * to send an updated subscription status.
@ -342,9 +347,10 @@ public class Roster {
* *
* @return an iterator the unfiled roster entries. * @return an iterator the unfiled roster entries.
*/ */
public Iterator getUnfiledEntries() { public Iterator<RosterEntry> getUnfiledEntries() {
synchronized (unfiledEntries) { synchronized (unfiledEntries) {
return Collections.unmodifiableList(new ArrayList(unfiledEntries)).iterator(); return Collections.unmodifiableList(new ArrayList<RosterEntry>(unfiledEntries))
.iterator();
} }
} }
@ -362,8 +368,7 @@ public class Roster {
} }
String userLowerCase = user.toLowerCase(); String userLowerCase = user.toLowerCase();
synchronized (entries) { synchronized (entries) {
for (Iterator i=entries.iterator(); i.hasNext(); ) { for (RosterEntry entry : entries) {
RosterEntry entry = (RosterEntry)i.next();
if (entry.getUser().equals(userLowerCase)) { if (entry.getUser().equals(userLowerCase)) {
return entry; return entry;
} }
@ -435,19 +440,19 @@ public class Roster {
*/ */
public Presence getPresence(String user) { public Presence getPresence(String user) {
String key = getPresenceMapKey(user); String key = getPresenceMapKey(user);
Map userPresences = (Map) presenceMap.get(key); Map<String, Presence> userPresences = presenceMap.get(key);
if (userPresences == null) { if (userPresences == null) {
return null; return null;
} }
else { else {
// Find the resource with the highest priority // Find the resource with the highest priority
// Might be changed to use the resource with the highest availability instead. // Might be changed to use the resource with the highest availability instead.
Iterator it = userPresences.keySet().iterator(); Iterator<String> it = userPresences.keySet().iterator();
Presence p; Presence p;
Presence presence = null; Presence presence = null;
while (it.hasNext()) { while (it.hasNext()) {
p = (Presence) userPresences.get(it.next()); p = userPresences.get(it.next());
if (presence == null) { if (presence == null) {
presence = p; presence = p;
} }
@ -473,12 +478,12 @@ public class Roster {
public Presence getPresenceResource(String userResource) { public Presence getPresenceResource(String userResource) {
String key = getPresenceMapKey(userResource); String key = getPresenceMapKey(userResource);
String resource = StringUtils.parseResource(userResource); String resource = StringUtils.parseResource(userResource);
Map userPresences = (Map)presenceMap.get(key); Map<String, Presence> userPresences = presenceMap.get(key);
if (userPresences == null) { if (userPresences == null) {
return null; return null;
} }
else { else {
return (Presence) userPresences.get(resource); return userPresences.get(resource);
} }
} }
@ -492,15 +497,15 @@ public class Roster {
* or <tt>null</tt> if the user is unavailable or if no presence information * or <tt>null</tt> if the user is unavailable or if no presence information
* is available. * is available.
*/ */
public Iterator getPresences(String user) { public Iterator<Presence> getPresences(String user) {
String key = getPresenceMapKey(user); String key = getPresenceMapKey(user);
Map userPresences = (Map)presenceMap.get(key); Map<String, Presence> userPresences = presenceMap.get(key);
if (userPresences == null) { if (userPresences == null) {
return null; return null;
} }
else { else {
synchronized (userPresences) { synchronized (userPresences) {
return new HashMap(userPresences).values().iterator(); return new HashMap<String, Presence>(userPresences).values().iterator();
} }
} }
} }
@ -543,15 +548,15 @@ public class Roster {
listeners = new RosterListener[rosterListeners.size()]; listeners = new RosterListener[rosterListeners.size()];
rosterListeners.toArray(listeners); rosterListeners.toArray(listeners);
} }
for (int i=0; i<listeners.length; i++) { for (RosterListener listener : listeners) {
if (!addedEntries.isEmpty()) { if (!addedEntries.isEmpty()) {
listeners[i].entriesAdded(addedEntries); listener.entriesAdded(addedEntries);
} }
if (!updatedEntries.isEmpty()) { if (!updatedEntries.isEmpty()) {
listeners[i].entriesUpdated(updatedEntries); listener.entriesUpdated(updatedEntries);
} }
if (!deletedEntries.isEmpty()) { if (!deletedEntries.isEmpty()) {
listeners[i].entriesDeleted(deletedEntries); listener.entriesDeleted(deletedEntries);
} }
} }
} }
@ -565,8 +570,8 @@ public class Roster {
listeners = new RosterListener[rosterListeners.size()]; listeners = new RosterListener[rosterListeners.size()];
rosterListeners.toArray(listeners); rosterListeners.toArray(listeners);
} }
for (int i=0; i<listeners.length; i++) { for (RosterListener listener : listeners) {
listeners[i].presenceChanged(user); listener.presenceChanged(user);
} }
} }
@ -582,14 +587,14 @@ public class Roster {
// If an "available" packet, add it to the presence map. Each presence map will hold // If an "available" packet, add it to the presence map. Each presence map will hold
// for a particular user a map with the presence packets saved for each resource. // for a particular user a map with the presence packets saved for each resource.
if (presence.getType() == Presence.Type.available) { if (presence.getType() == Presence.Type.available) {
Map userPresences; Map<String, Presence> userPresences;
// Get the user presence map // Get the user presence map
if (presenceMap.get(key) == null) { if (presenceMap.get(key) == null) {
userPresences = new HashMap(); userPresences = new HashMap<String, Presence>();
presenceMap.put(key, userPresences); presenceMap.put(key, userPresences);
} }
else { else {
userPresences = (Map)presenceMap.get(key); userPresences = presenceMap.get(key);
} }
// Add the new presence, using the resources as a key. // Add the new presence, using the resources as a key.
synchronized (userPresences) { synchronized (userPresences) {
@ -597,8 +602,7 @@ public class Roster {
} }
// If the user is in the roster, fire an event. // If the user is in the roster, fire an event.
synchronized (entries) { synchronized (entries) {
for (Iterator i = entries.iterator(); i.hasNext();) { for (RosterEntry entry : entries) {
RosterEntry entry = (RosterEntry) i.next();
if (entry.getUser().equals(key)) { if (entry.getUser().equals(key)) {
fireRosterPresenceEvent(from); fireRosterPresenceEvent(from);
} }
@ -608,7 +612,7 @@ public class Roster {
// If an "unavailable" packet, remove any entries in the presence map. // If an "unavailable" packet, remove any entries in the presence map.
else if (presence.getType() == Presence.Type.unavailable) { else if (presence.getType() == Presence.Type.unavailable) {
if (presenceMap.get(key) != null) { if (presenceMap.get(key) != null) {
Map userPresences = (Map) presenceMap.get(key); Map<String, Presence> userPresences = presenceMap.get(key);
synchronized (userPresences) { synchronized (userPresences) {
userPresences.remove(StringUtils.parseResource(from)); userPresences.remove(StringUtils.parseResource(from));
} }
@ -618,8 +622,7 @@ public class Roster {
} }
// If the user is in the roster, fire an event. // If the user is in the roster, fire an event.
synchronized (entries) { synchronized (entries) {
for (Iterator i=entries.iterator(); i.hasNext(); ) { for (RosterEntry entry : entries) {
RosterEntry entry = (RosterEntry)i.next();
if (entry.getUser().equals(key)) { if (entry.getUser().equals(key)) {
fireRosterPresenceEvent(from); fireRosterPresenceEvent(from);
} }
@ -663,11 +666,11 @@ public class Roster {
public void processPacket(Packet packet) { public void processPacket(Packet packet) {
// Keep a registry of the entries that were added, deleted or updated. An event // Keep a registry of the entries that were added, deleted or updated. An event
// will be fired for each affected entry // will be fired for each affected entry
Collection addedEntries = new ArrayList(); Collection<String> addedEntries = new ArrayList<String>();
Collection updatedEntries = new ArrayList(); Collection<String> updatedEntries = new ArrayList<String>();
Collection deletedEntries = new ArrayList(); Collection<String> deletedEntries = new ArrayList<String>();
RosterPacket rosterPacket = (RosterPacket)packet; RosterPacket rosterPacket = (RosterPacket) packet;
for (RosterPacket.Item item : rosterPacket.getRosterItems()) { for (RosterPacket.Item item : rosterPacket.getRosterItems()) {
RosterEntry entry = new RosterEntry(item.getUser(), item.getName(), RosterEntry entry = new RosterEntry(item.getUser(), item.getName(),
item.getItemType(), item.getItemStatus(), connection); item.getItemType(), item.getItemStatus(), connection);
@ -701,8 +704,7 @@ public class Roster {
} }
else { else {
// If the entry was in then list then update its state with the new values // If the entry was in then list then update its state with the new values
RosterEntry existingEntry = RosterEntry existingEntry = entries.get(entries.indexOf(entry));
(RosterEntry) entries.get(entries.indexOf(entry));
existingEntry existingEntry
.updateState(entry.getName(), entry.getType(), entry.getStatus()); .updateState(entry.getName(), entry.getType(), entry.getStatus());
// Keep note that an entry has been updated // 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 // 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 // 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. // to. We do this by subracting the new group set from the old.
for (int m=0; m<newGroupNames.size(); m++) { for (String newGroupName : newGroupNames) {
currentGroupNames.remove(newGroupNames.get(m)); currentGroupNames.remove(newGroupName);
} }
} }
// Loop through any groups that remain and remove the entries. // Loop through any groups that remain and remove the entries.
// This is neccessary for the case of remote entry removals. // This is neccessary for the case of remote entry removals.
for (int n=0; n<currentGroupNames.size(); n++) { for (String groupName : currentGroupNames) {
String groupName = (String)currentGroupNames.get(n);
RosterGroup group = getGroup(groupName); RosterGroup group = getGroup(groupName);
group.removeEntryLocal(entry); group.removeEntryLocal(entry);
if (group.getEntryCount() == 0) { if (group.getEntryCount() == 0) {

View file

@ -20,8 +20,8 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.RosterPacket;
import java.util.*; import java.util.*;
@ -146,7 +146,7 @@ public class RosterEntry {
} }
public String toString() { public String toString() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
if (name != null) { if (name != null) {
buf.append(name).append(": "); buf.append(name).append(": ");
} }

View file

@ -20,12 +20,15 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.util.StringUtils;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/** /**
* A group of roster entries. * A group of roster entries.
@ -37,7 +40,7 @@ public class RosterGroup {
private String name; private String name;
private XMPPConnection connection; private XMPPConnection connection;
private List<RosterEntry> entries; private final List<RosterEntry> entries;
/** /**
* Creates a new roster group instance. * Creates a new roster group instance.
@ -70,10 +73,9 @@ public class RosterGroup {
*/ */
public void setName(String name) { public void setName(String name) {
synchronized (entries) { synchronized (entries) {
for (int i=0; i<entries.size(); i++) { for (RosterEntry entry : entries) {
RosterPacket packet = new RosterPacket(); RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET); packet.setType(IQ.Type.SET);
RosterEntry entry = (RosterEntry)entries.get(i);
RosterPacket.Item item = RosterEntry.toRosterItem(entry); RosterPacket.Item item = RosterEntry.toRosterItem(entry);
item.removeGroupName(this.name); item.removeGroupName(this.name);
item.addGroupName(name); item.addGroupName(name);
@ -121,8 +123,7 @@ public class RosterGroup {
user = StringUtils.parseBareAddress(user); user = StringUtils.parseBareAddress(user);
String userLowerCase = user.toLowerCase(); String userLowerCase = user.toLowerCase();
synchronized (entries) { synchronized (entries) {
for (Iterator i=entries.iterator(); i.hasNext(); ) { for (RosterEntry entry : entries) {
RosterEntry entry = (RosterEntry)i.next();
if (entry.getUser().equals(userLowerCase)) { if (entry.getUser().equals(userLowerCase)) {
return entry; return entry;
} }

View file

@ -59,11 +59,11 @@ import java.util.*;
*/ */
public class SASLAuthentication implements UserAuthentication { public class SASLAuthentication implements UserAuthentication {
private static Map implementedMechanisms = new HashMap(); private static Map<String, Class> implementedMechanisms = new HashMap<String, Class>();
private static List mechanismsPreferences = new ArrayList(); private static List<String> mechanismsPreferences = new ArrayList<String>();
private XMPPConnection connection; private XMPPConnection connection;
private Collection serverMechanisms = new ArrayList(); private Collection<String> serverMechanisms = new ArrayList<String>();
private SASLMechanism currentMechanism = null; private SASLMechanism currentMechanism = null;
/** /**
* Boolean indicating if SASL negotiation has finished and was successful. * 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. * @return the registerd SASLMechanism classes sorted by the level of preference.
*/ */
public static List getRegisterSASLMechanisms() { public static List<Class> getRegisterSASLMechanisms() {
List answer = new ArrayList(); List<Class> answer = new ArrayList<Class>();
for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) { for (String mechanismsPreference : mechanismsPreferences) {
answer.add(implementedMechanisms.get(it.next())); answer.add(implementedMechanisms.get(mechanismsPreference));
} }
return answer; return answer;
} }
@ -171,11 +171,10 @@ public class SASLAuthentication implements UserAuthentication {
throws XMPPException { throws XMPPException {
// Locate the SASLMechanism to use // Locate the SASLMechanism to use
Class selected = null; Class selected = null;
for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) { for (String mechanism : mechanismsPreferences) {
String mechanism = (String) it.next();
if (implementedMechanisms.containsKey(mechanism) && if (implementedMechanisms.containsKey(mechanism) &&
serverMechanisms.contains(mechanism)) { serverMechanisms.contains(mechanism)) {
selected = (Class) implementedMechanisms.get(mechanism); selected = implementedMechanisms.get(mechanism);
break; break;
} }
} }
@ -339,7 +338,7 @@ public class SASLAuthentication implements UserAuthentication {
* @param mechanisms collection of strings with the available SASL mechanism reported * @param mechanisms collection of strings with the available SASL mechanism reported
* by the server. * by the server.
*/ */
void setAvailableSASLMethods(Collection mechanisms) { void setAvailableSASLMethods(Collection<String> mechanisms) {
this.serverMechanisms = mechanisms; this.serverMechanisms = mechanisms;
} }

View file

@ -63,8 +63,8 @@ public final class SmackConfiguration {
try { try {
// Get an array of class loaders to try loading the providers files from. // Get an array of class loaders to try loading the providers files from.
ClassLoader[] classLoaders = getClassLoaders(); ClassLoader[] classLoaders = getClassLoaders();
for (int i = 0; i < classLoaders.length; i++) { for (ClassLoader classLoader : classLoaders) {
Enumeration configEnum = classLoaders[i].getResources("META-INF/smack-config.xml"); Enumeration configEnum = classLoader.getResources("META-INF/smack-config.xml");
while (configEnum.hasMoreElements()) { while (configEnum.hasMoreElements()) {
URL url = (URL) configEnum.nextElement(); URL url = (URL) configEnum.nextElement();
InputStream systemStream = null; InputStream systemStream = null;
@ -81,7 +81,8 @@ public final class SmackConfiguration {
parseClassToLoad(parser); parseClassToLoad(parser);
} }
else if (parser.getName().equals("packetReplyTimeout")) { else if (parser.getName().equals("packetReplyTimeout")) {
packetReplyTimeout = parseIntProperty(parser, packetReplyTimeout); packetReplyTimeout =
parseIntProperty(parser, packetReplyTimeout);
} }
else if (parser.getName().equals("keepAliveInterval")) { else if (parser.getName().equals("keepAliveInterval")) {
keepAliveInterval = parseIntProperty(parser, keepAliveInterval); keepAliveInterval = parseIntProperty(parser, keepAliveInterval);
@ -200,7 +201,7 @@ public final class SmackConfiguration {
*/ */
private static ClassLoader[] getClassLoaders() { private static ClassLoader[] getClassLoaders() {
ClassLoader[] classLoaders = new ClassLoader[2]; ClassLoader[] classLoaders = new ClassLoader[2];
classLoaders[0] = new SmackConfiguration().getClass().getClassLoader(); classLoaders[0] = SmackConfiguration.class.getClassLoader();
classLoaders[1] = Thread.currentThread().getContextClassLoader(); classLoaders[1] = Thread.currentThread().getContextClassLoader();
return classLoaders; return classLoaders;
} }

View file

@ -39,7 +39,11 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; 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 * 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; public static boolean DEBUG_ENABLED = false;
private static List connectionEstablishedListeners = new ArrayList(); private final static List<ConnectionEstablishedListener> connectionEstablishedListeners =
new ArrayList<ConnectionEstablishedListener>();
static { static {
// Use try block since we may not have permission to get a system // 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 * does not interfere with garbage collection. The map of chats must be stored
* with each connection. * with each connection.
*/ */
Map chats = Collections.synchronizedMap(new HashMap()); Map<String, WeakReference<Chat>> chats = new ConcurrentHashMap<String, WeakReference<Chat>>();
/** /**
* Collection of available stream compression methods offered by the server. * Collection of available stream compression methods offered by the server.
@ -289,7 +294,9 @@ public class XMPPConnection {
// constructor it cannot be modified // constructor it cannot be modified
this.configuration = (ConnectionConfiguration) config.clone(); this.configuration = (ConnectionConfiguration) config.clone();
} }
catch (CloneNotSupportedException e) {} catch (CloneNotSupportedException e) {
// Do nothing
}
init(); init();
} }
@ -419,7 +426,7 @@ public class XMPPConnection {
// Do partial version of nameprep on the username. // Do partial version of nameprep on the username.
username = username.toLowerCase().trim(); username = username.toLowerCase().trim();
String response = null; String response;
if (configuration.isSASLAuthenticationEnabled() && if (configuration.isSASLAuthenticationEnabled() &&
saslAuthentication.hasNonAnonymousAuthentication()) { saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL // Authenticate using SASL
@ -488,7 +495,7 @@ public class XMPPConnection {
throw new IllegalStateException("Already logged in to server."); throw new IllegalStateException("Already logged in to server.");
} }
String response = null; String response;
if (configuration.isSASLAuthenticationEnabled() && if (configuration.isSASLAuthenticationEnabled() &&
saslAuthentication.hasAnonymousAuthentication()) { saslAuthentication.hasAnonymousAuthentication()) {
response = saslAuthentication.authenticateAnonymously(); response = saslAuthentication.authenticateAnonymously();
@ -876,12 +883,12 @@ public class XMPPConnection {
if (message.getThread() == null && if (message.getThread() == null &&
message.getType() != Message.Type.GROUP_CHAT && message.getType() != Message.Type.GROUP_CHAT &&
message.getType() != Message.Type.HEADLINE) { message.getType() != Message.Type.HEADLINE) {
WeakReference chatRef = (WeakReference)chats.get( WeakReference<Chat> chatRef =
StringUtils.parseBareAddress(message.getFrom())); chats.get(StringUtils.parseBareAddress(message.getFrom()));
if (chatRef != null) { if (chatRef != null) {
// Do some extra clean-up if the reference was cleared. // Do some extra clean-up if the reference was cleared.
Chat chat; Chat chat = chatRef.get();
if ((chat = (Chat)chatRef.get()) == null) { if (chat == null) {
chats.remove(message.getFrom()); chats.remove(message.getFrom());
} }
else { else {
@ -931,9 +938,9 @@ public class XMPPConnection {
} }
else { else {
try { 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); //ZOutputStream out = new ZOutputStream(socket.getOutputStream(), JZlib.Z_BEST_COMPRESSION);
Constructor constructor = Constructor<?> constructor =
zoClass.getConstructor(new Class[]{OutputStream.class, Integer.TYPE}); zoClass.getConstructor(new Class[]{OutputStream.class, Integer.TYPE});
Object out = constructor.newInstance(new Object[] {socket.getOutputStream(), new Integer(9)}); Object out = constructor.newInstance(new Object[] {socket.getOutputStream(), new Integer(9)});
//out.setFlushMode(JZlib.Z_PARTIAL_FLUSH); //out.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
@ -941,7 +948,7 @@ public class XMPPConnection {
method.invoke(out, new Object[] {new Integer(1)}); method.invoke(out, new Object[] {new Integer(1)});
writer = new BufferedWriter(new OutputStreamWriter((OutputStream) out, "UTF-8")); 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()); //ZInputStream in = new ZInputStream(socket.getInputStream());
constructor = ziClass.getConstructor(new Class[]{InputStream.class}); constructor = ziClass.getConstructor(new Class[]{InputStream.class});
Object in = constructor.newInstance(new Object[] {socket.getInputStream()}); Object in = constructor.newInstance(new Object[] {socket.getInputStream()});
@ -976,7 +983,7 @@ public class XMPPConnection {
} }
catch (Throwable t) { catch (Throwable t) {
} }
Class debuggerClass = null; Class<?> debuggerClass = null;
if (className != null) { if (className != null) {
try { try {
debuggerClass = Class.forName(className); debuggerClass = Class.forName(className);
@ -1002,7 +1009,7 @@ public class XMPPConnection {
// Create a new debugger instance. If an exception occurs then disable the debugging // Create a new debugger instance. If an exception occurs then disable the debugging
// option // option
try { try {
Constructor constructor = Constructor<?> constructor =
debuggerClass.getConstructor( debuggerClass.getConstructor(
new Class[] { XMPPConnection.class, Writer.class, Reader.class }); new Class[] { XMPPConnection.class, Writer.class, Reader.class });
debugger = (SmackDebugger) constructor debugger = (SmackDebugger) constructor
@ -1027,13 +1034,13 @@ public class XMPPConnection {
* Fires listeners on connection established events. * Fires listeners on connection established events.
*/ */
private static void connectionEstablished(XMPPConnection connection) { private static void connectionEstablished(XMPPConnection connection) {
ConnectionEstablishedListener[] listeners = null; ConnectionEstablishedListener[] listeners;
synchronized (connectionEstablishedListeners) { synchronized (connectionEstablishedListeners) {
listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()]; listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()];
connectionEstablishedListeners.toArray(listeners); connectionEstablishedListeners.toArray(listeners);
} }
for (int i = 0; i < listeners.length; i++) { for (ConnectionEstablishedListener listener : listeners) {
listeners[i].connectionEstablished(connection); listener.connectionEstablished(connection);
} }
} }

View file

@ -20,8 +20,8 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.StreamError; import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.packet.XMPPError;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
@ -199,7 +199,7 @@ public class XMPPException extends Exception {
} }
public String toString() { public String toString() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
String message = super.getMessage(); String message = super.getMessage();
if (message != null) { if (message != null) {
buf.append(message).append(": "); buf.append(message).append(": ");

View file

@ -146,7 +146,7 @@ public class Authentication extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:auth\">"); buf.append("<query xmlns=\"jabber:iq:auth\">");
if (username != null) { if (username != null) {
if (username.equals("")) { if (username.equals("")) {

View file

@ -57,7 +57,7 @@ public class Bind extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"); buf.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
if (resource != null) { if (resource != null) {
buf.append("<resource>").append(resource).append("</resource>"); buf.append("<resource>").append(resource).append("</resource>");

View file

@ -20,7 +20,10 @@
package org.jivesoftware.smack.packet; 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 * Default implementation of the PacketExtension interface. Unless a PacketExtensionProvider
@ -80,7 +83,7 @@ public class DefaultPacketExtension implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">"); buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">");
for (Iterator i=getNames(); i.hasNext(); ) { for (Iterator i=getNames(); i.hasNext(); ) {
String name = (String)i.next(); String name = (String)i.next();

View file

@ -67,7 +67,7 @@ public abstract class IQ extends Packet {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<iq "); buf.append("<iq ");
if (getPacketID() != null) { if (getPacketID() != null) {
buf.append("id=\"" + getPacketID() + "\" "); buf.append("id=\"" + getPacketID() + "\" ");

View file

@ -165,7 +165,7 @@ public class Message extends Packet {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<message"); buf.append("<message");
if (getPacketID() != null) { if (getPacketID() != null) {
buf.append(" id=\"").append(getPacketID()).append("\""); buf.append(" id=\"").append(getPacketID()).append("\"");

View file

@ -22,8 +22,10 @@ package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.*; import java.util.*;
import java.io.*;
/** /**
* Base class for XMPP packets. Every packet has a unique ID (which is automatically * Base class for XMPP packets. Every packet has a unique ID (which is automatically
@ -351,7 +353,7 @@ public abstract class Packet {
* are no packet extensions. * are no packet extensions.
*/ */
protected synchronized String getExtensionsXML() { protected synchronized String getExtensionsXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
// Add in all standard extension sub-packets. // Add in all standard extension sub-packets.
Iterator extensions = getExtensions(); Iterator extensions = getExtensions();
while (extensions.hasNext()) { while (extensions.hasNext()) {

View file

@ -169,7 +169,7 @@ public class Presence extends Packet {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<presence"); buf.append("<presence");
if (getPacketID() != null) { if (getPacketID() != null) {
buf.append(" id=\"").append(getPacketID()).append("\""); buf.append(" id=\"").append(getPacketID()).append("\"");
@ -208,7 +208,7 @@ public class Presence extends Packet {
} }
public String toString() { public String toString() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append(type); buf.append(type);
if (mode != null) { if (mode != null) {
buf.append(": ").append(mode); buf.append(": ").append(mode);

View file

@ -21,7 +21,6 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import java.util.Map; import java.util.Map;
import java.util.Iterator;
/** /**
* Represents registration packets. An empty GET query will cause the server to return information * Represents registration packets. An empty GET query will cause the server to return information
@ -49,7 +48,7 @@ import java.util.Iterator;
public class Registration extends IQ { public class Registration extends IQ {
private String instructions = null; private String instructions = null;
private Map attributes = null; private Map<String, String> attributes = null;
/** /**
* Returns the registration instructions, or <tt>null</tt> if no instructions * Returns the registration instructions, or <tt>null</tt> if no instructions
@ -76,7 +75,7 @@ public class Registration extends IQ {
* *
* @return the account attributes. * @return the account attributes.
*/ */
public Map getAttributes() { public Map<String, String> getAttributes() {
return attributes; return attributes;
} }
@ -85,21 +84,19 @@ public class Registration extends IQ {
* *
* @param attributes the account attributes. * @param attributes the account attributes.
*/ */
public void setAttributes(Map attributes) { public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes; this.attributes = attributes;
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:register\">"); buf.append("<query xmlns=\"jabber:iq:register\">");
if (instructions != null) { if (instructions != null) {
buf.append("<instructions>").append(instructions).append("</instructions>"); buf.append("<instructions>").append(instructions).append("</instructions>");
} }
if (attributes != null && attributes.size() > 0) { if (attributes != null && attributes.size() > 0) {
Iterator fieldNames = attributes.keySet().iterator(); for (String name : attributes.keySet()) {
while (fieldNames.hasNext()) { String value = attributes.get(name);
String name = (String)fieldNames.next();
String value = (String)attributes.get(name);
buf.append("<").append(name).append(">"); buf.append("<").append(name).append(">");
buf.append(value); buf.append(value);
buf.append("</").append(name).append(">"); buf.append("</").append(name).append(">");

View file

@ -68,7 +68,7 @@ public class RosterPacket extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:roster\">"); buf.append("<query xmlns=\"jabber:iq:roster\">");
synchronized (rosterItems) { synchronized (rosterItems) {
for (Item entry : rosterItems) { for (Item entry : rosterItems) {
@ -197,7 +197,7 @@ public class RosterPacket extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item jid=\"").append(user).append("\""); buf.append("<item jid=\"").append(user).append("\"");
if (name != null) { if (name != null) {
buf.append(" name=\"").append(name).append("\""); buf.append(" name=\"").append(name).append("\"");

View file

@ -99,7 +99,7 @@ public class StreamError {
} }
public String toString() { public String toString() {
StringBuffer txt = new StringBuffer(); StringBuilder txt = new StringBuilder();
txt.append("stream:error (").append(code).append(")"); txt.append("stream:error (").append(code).append(")");
return txt.toString(); return txt.toString();
} }

View file

@ -97,7 +97,7 @@ public class XMPPError {
* @return the error as XML. * @return the error as XML.
*/ */
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<error code=\"").append(code).append("\">"); buf.append("<error code=\"").append(code).append("\">");
if (message != null) { if (message != null) {
buf.append(message); buf.append(message);
@ -107,7 +107,7 @@ public class XMPPError {
} }
public String toString() { public String toString() {
StringBuffer txt = new StringBuffer(); StringBuilder txt = new StringBuilder();
txt.append("(").append(code).append(")"); txt.append("(").append(code).append(")");
if (message != null) { if (message != null) {
txt.append(" ").append(message); txt.append(" ").append(message);

View file

@ -22,11 +22,12 @@ package org.jivesoftware.smack.provider;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import org.xmlpull.v1.*;
import org.xmlpull.mxp1.MXParser; import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import java.util.*; import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.*;
/** /**
* Manages providers for parsing custom XML sub-documents of XMPP packets. Two types of * Manages providers for parsing custom XML sub-documents of XMPP packets. Two types of
@ -117,12 +118,12 @@ public class ProviderManager {
try { try {
// Get an array of class loaders to try loading the providers files from. // Get an array of class loaders to try loading the providers files from.
ClassLoader[] classLoaders = getClassLoaders(); ClassLoader[] classLoaders = getClassLoaders();
for (int i=0; i<classLoaders.length; i++) { for (ClassLoader classLoader : classLoaders) {
Enumeration providerEnum = classLoaders[i].getResources( Enumeration providerEnum = classLoader.getResources(
"META-INF/smack.providers"); "META-INF/smack.providers");
while (providerEnum.hasMoreElements()) { while (providerEnum.hasMoreElements()) {
URL url = (URL)providerEnum.nextElement(); URL url = (URL) providerEnum.nextElement();
java.io.InputStream providerStream = null; InputStream providerStream = null;
try { try {
providerStream = url.openStream(); providerStream = url.openStream();
XmlPullParser parser = new MXParser(); XmlPullParser parser = new MXParser();
@ -187,13 +188,11 @@ public class ProviderManager {
// Add the provider to the map. // Add the provider to the map.
Class provider = Class.forName(className); Class provider = Class.forName(className);
if (PacketExtensionProvider.class.isAssignableFrom( if (PacketExtensionProvider.class.isAssignableFrom(
provider)) provider)) {
{
extensionProviders.put(key, provider.newInstance()); extensionProviders.put(key, provider.newInstance());
} }
else if (PacketExtension.class.isAssignableFrom( else if (PacketExtension.class.isAssignableFrom(
provider)) provider)) {
{
extensionProviders.put(key, provider); extensionProviders.put(key, provider);
} }
} }
@ -204,11 +203,15 @@ public class ProviderManager {
} }
} }
eventType = parser.next(); eventType = parser.next();
} while (eventType != XmlPullParser.END_DOCUMENT); }
while (eventType != XmlPullParser.END_DOCUMENT);
} }
finally { finally {
try { providerStream.close(); } try {
catch (Exception e) { } providerStream.close();
}
catch (Exception e) {
}
} }
} }
} }
@ -362,7 +365,7 @@ public class ProviderManager {
* @return a unique key for the element name and namespace pair. * @return a unique key for the element name and namespace pair.
*/ */
private static String getProviderKey(String elementName, String namespace) { private static String getProviderKey(String elementName, String namespace) {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(elementName).append("/><").append(namespace).append("/>"); buf.append("<").append(elementName).append("/><").append(namespace).append("/>");
return buf.toString(); return buf.toString();
} }

View file

@ -55,7 +55,7 @@ public abstract class SASLMechanism {
*/ */
public void authenticate(String username, String host, String password) throws IOException { public void authenticate(String username, String host, String password) throws IOException {
// Build the authentication stanza encoding the authentication text // Build the authentication stanza encoding the authentication text
StringBuffer stanza = new StringBuffer(); StringBuilder stanza = new StringBuilder();
stanza.append("<auth mechanism=\"").append(getName()); stanza.append("<auth mechanism=\"").append(getName());
stanza.append("\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"); stanza.append("\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
String authenticationText = getAuthenticationText(username, host, password); String authenticationText = getAuthenticationText(username, host, password);
@ -76,7 +76,7 @@ public abstract class SASLMechanism {
*/ */
public void challengeReceived(String challenge) throws IOException { public void challengeReceived(String challenge) throws IOException {
// Build the challenge response stanza encoding the response text // Build the challenge response stanza encoding the response text
StringBuffer stanza = new StringBuffer(); StringBuilder stanza = new StringBuilder();
stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"); stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
String authenticationText = getChallengeResponse(StringUtils.decodeBase64(challenge)); String authenticationText = getChallengeResponse(StringUtils.decodeBase64(challenge));
if (authenticationText != null) { if (authenticationText != null) {

View file

@ -42,7 +42,7 @@ public class SASLPlainMechanism extends SASLMechanism {
protected String getAuthenticationText(String username, String host, String password) { protected String getAuthenticationText(String username, String host, String password) {
// Build the text containing the "authorization identity" + NUL char + // Build the text containing the "authorization identity" + NUL char +
// "authentication identity" + NUL char + "clear-text password" // "authentication identity" + NUL char + "clear-text password"
StringBuffer text = new StringBuffer(); StringBuilder text = new StringBuilder();
text.append(username).append("@").append(host); text.append(username).append("@").append(host);
text.append('\0'); text.append('\0');
text.append(username); text.append(username);

View file

@ -549,7 +549,7 @@ public class Cache implements Map {
*/ */
public String toString() { public String toString() {
LinkedListNode node = head.next; LinkedListNode node = head.next;
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
while (node != head) { while (node != head) {
buf.append(node.toString()).append(", "); buf.append(node.toString()).append(", ");
node = node.next; node = node.next;

View file

@ -20,9 +20,9 @@
package org.jivesoftware.smack.util; package org.jivesoftware.smack.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.Random; import java.util.Random;
/** /**
@ -143,7 +143,7 @@ public class StringUtils {
int last=0; int last=0;
char[] input = string.toCharArray(); char[] input = string.toCharArray();
int len = input.length; int len = input.length;
StringBuffer out = new StringBuffer((int)(len*1.3)); StringBuilder out = new StringBuilder((int)(len*1.3));
for (; i < len; i++) { for (; i < len; i++) {
ch = input[i]; ch = input[i];
if (ch > '>') { if (ch > '>') {
@ -243,13 +243,13 @@ public class StringUtils {
* @return generated hex string. * @return generated hex string.
*/ */
public static String encodeHex(byte[] bytes) { 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<bytes.length; i++) { for (byte aByte : bytes) {
if (((int) bytes[i] & 0xff) < 0x10) { if (((int) aByte & 0xff) < 0x10) {
hex.append("0"); hex.append("0");
} }
hex.append(Integer.toString((int) bytes[i] & 0xff, 16)); hex.append(Integer.toString((int) aByte & 0xff, 16));
} }
return hex.toString(); return hex.toString();

View file

@ -20,11 +20,15 @@
package org.jivesoftware.smackx; package org.jivesoftware.smackx;
import java.util.*; import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smackx.packet.DataForm; import org.jivesoftware.smackx.packet.DataForm;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
/** /**
* Represents a Form for gathering data. The form could be of the following types: * Represents a Form for gathering data. The form could be of the following types:
* <ul> * <ul>
@ -334,8 +338,8 @@ public class Form {
// Clear the old values // Clear the old values
field.resetValues(); field.resetValues();
// Set the default value // Set the default value
for (Iterator it = field.getValues(); it.hasNext();) { for (Iterator<String> it = field.getValues(); it.hasNext();) {
field.addValue((String) it.next()); field.addValue(it.next());
} }
} }
else { else {
@ -348,7 +352,7 @@ public class Form {
* *
* @return an Iterator for the fields that are part of the form. * @return an Iterator for the fields that are part of the form.
*/ */
public Iterator getFields() { public Iterator<FormField> getFields() {
return dataForm.getFields(); return dataForm.getFields();
} }
@ -366,8 +370,8 @@ public class Form {
} }
// Look for the field whose variable matches the requested variable // Look for the field whose variable matches the requested variable
FormField field; FormField field;
for (Iterator it=getFields();it.hasNext();) { for (Iterator<FormField> it=getFields();it.hasNext();) {
field = (FormField)it.next(); field = it.next();
if (variable.equals(field.getVariable())) { if (variable.equals(field.getVariable())) {
return field; return field;
} }
@ -381,7 +385,7 @@ public class Form {
* @return instructions that explain how to fill out the form. * @return instructions that explain how to fill out the form.
*/ */
public String getInstructions() { public String getInstructions() {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
// Join the list of instructions together separated by newlines // Join the list of instructions together separated by newlines
for (Iterator it = dataForm.getInstructions(); it.hasNext();) { for (Iterator it = dataForm.getInstructions(); it.hasNext();) {
sb.append((String) it.next()); sb.append((String) it.next());
@ -432,7 +436,7 @@ public class Form {
*/ */
public void setInstructions(String instructions) { public void setInstructions(String instructions) {
// Split the instructions into multiple instructions for each existent newline // Split the instructions into multiple instructions for each existent newline
ArrayList instructionsList = new ArrayList(); ArrayList<String> instructionsList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(instructions, "\n"); StringTokenizer st = new StringTokenizer(instructions, "\n");
while (st.hasMoreTokens()) { while (st.hasMoreTokens()) {
instructionsList.add(st.nextToken()); instructionsList.add(st.nextToken());
@ -464,8 +468,8 @@ public class Form {
if (isSubmitType()) { if (isSubmitType()) {
// Create a new DataForm that contains only the answered fields // Create a new DataForm that contains only the answered fields
DataForm dataFormToSend = new DataForm(getType()); DataForm dataFormToSend = new DataForm(getType());
for(Iterator it=getFields();it.hasNext();) { for(Iterator<FormField> it=getFields();it.hasNext();) {
FormField field = (FormField)it.next(); FormField field = it.next();
if (field.getValues().hasNext()) { if (field.getValues().hasNext()) {
dataFormToSend.addField(field); dataFormToSend.addField(field);
} }
@ -513,8 +517,8 @@ public class Form {
} }
// Create a new Form // Create a new Form
Form form = new Form(TYPE_SUBMIT); Form form = new Form(TYPE_SUBMIT);
for (Iterator fields=getFields(); fields.hasNext();) { for (Iterator<FormField> fields=getFields(); fields.hasNext();) {
FormField field = (FormField)fields.next(); FormField field = fields.next();
// Add to the new form any type of field that includes a variable. // 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 // Note: The fields of type FIXED are the only ones that don't specify a variable
if (field.getVariable() != null) { if (field.getVariable() != null) {
@ -525,9 +529,9 @@ public class Form {
if (FormField.TYPE_HIDDEN.equals(field.getType())) { if (FormField.TYPE_HIDDEN.equals(field.getType())) {
// Since a hidden field could have many values we need to collect them // Since a hidden field could have many values we need to collect them
// in a list // in a list
List values = new ArrayList(); List<String> values = new ArrayList<String>();
for (Iterator it=field.getValues();it.hasNext();) { for (Iterator<String> it=field.getValues();it.hasNext();) {
values.add((String)it.next()); values.add(it.next());
} }
form.setAnswer(field.getVariable(), values); form.setAnswer(field.getVariable(), values);
} }

View file

@ -20,7 +20,10 @@
package org.jivesoftware.smackx; 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, * 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 label;
private String variable; private String variable;
private String type; private String type;
private List options = new ArrayList(); private final List<Option> options = new ArrayList<Option>();
private List values = new ArrayList(); private final List<String> values = new ArrayList<String>();
/** /**
* Creates a new FormField with the variable name that uniquely identifies the field * Creates a new FormField with the variable name that uniquely identifies the field
@ -97,9 +100,9 @@ public class FormField {
* *
* @return Iterator for the available options. * @return Iterator for the available options.
*/ */
public Iterator getOptions() { public Iterator<Option> getOptions() {
synchronized (options) { synchronized (options) {
return Collections.unmodifiableList(new ArrayList(options)).iterator(); return Collections.unmodifiableList(new ArrayList<Option>(options)).iterator();
} }
} }
@ -144,9 +147,9 @@ public class FormField {
* *
* @return an Iterator for the default values or answered values of the question. * @return an Iterator for the default values or answered values of the question.
*/ */
public Iterator getValues() { public Iterator<String> getValues() {
synchronized (values) { synchronized (values) {
return Collections.unmodifiableList(new ArrayList(values)).iterator(); return Collections.unmodifiableList(new ArrayList<String>(values)).iterator();
} }
} }
@ -234,7 +237,7 @@ public class FormField {
* *
* @param newValues default values or an answered values of the question. * @param newValues default values or an answered values of the question.
*/ */
public void addValues(List newValues) { public void addValues(List<String> newValues) {
synchronized (values) { synchronized (values) {
values.addAll(newValues); values.addAll(newValues);
} }
@ -246,7 +249,7 @@ public class FormField {
*/ */
protected void resetValues() { protected void resetValues() {
synchronized (values) { synchronized (values) {
values.removeAll(new ArrayList(values)); values.removeAll(new ArrayList<String>(values));
} }
} }
@ -263,7 +266,7 @@ public class FormField {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<field"); buf.append("<field");
// Add attributes // Add attributes
if (getLabel() != null) { if (getLabel() != null) {
@ -284,7 +287,7 @@ public class FormField {
buf.append("<required/>"); buf.append("<required/>");
} }
// Loop through all the values and append them to the string buffer // Loop through all the values and append them to the string buffer
for (Iterator i = getValues(); i.hasNext();) { for (Iterator<String> i = getValues(); i.hasNext();) {
buf.append("<value>").append(i.next()).append("</value>"); buf.append("<value>").append(i.next()).append("</value>");
} }
// Loop through all the values and append them to the string buffer // Loop through all the values and append them to the string buffer
@ -337,7 +340,7 @@ public class FormField {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<option"); buf.append("<option");
// Add attribute // Add attribute
if (getLabel() != null) { if (getLabel() != null) {

View file

@ -99,7 +99,7 @@ public class GroupChatInvitation implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<x xmlns=\"jabber:x:conference\" jid=\"").append(roomAddress).append("\"/>"); buf.append("<x xmlns=\"jabber:x:conference\" jid=\"").append(roomAddress).append("\"/>");
return buf.toString(); return buf.toString();
} }

View file

@ -20,6 +20,8 @@
package org.jivesoftware.smackx; package org.jivesoftware.smackx;
import org.jivesoftware.smackx.packet.DiscoverItems;
import java.util.Iterator; import java.util.Iterator;
@ -40,7 +42,7 @@ public interface NodeInformationProvider {
* *
* @return an Iterator on the Items defined in the node. * @return an Iterator on the Items defined in the node.
*/ */
public abstract Iterator getNodeItems(); public abstract Iterator<DiscoverItems.Item> getNodeItems();
/** /**
* Returns an Iterator on the features defined in the node. For * Returns an Iterator on the features defined in the node. For
@ -50,5 +52,5 @@ public interface NodeInformationProvider {
* *
* @return an Iterator on the feature strings defined in the node. * @return an Iterator on the feature strings defined in the node.
*/ */
public abstract Iterator getNodeFeatures(); public abstract Iterator<String> getNodeFeatures();
} }

View file

@ -93,7 +93,7 @@ public class OfflineMessageManager {
namespace); namespace);
Form extendedInfo = Form.getFormFrom(info); Form extendedInfo = Form.getFormFrom(info);
if (extendedInfo != null) { if (extendedInfo != null) {
String value = (String) extendedInfo.getField("number_of_messages").getValues().next(); String value = extendedInfo.getField("number_of_messages").getValues().next();
return Integer.parseInt(value); return Integer.parseInt(value);
} }
return 0; return 0;
@ -109,8 +109,8 @@ public class OfflineMessageManager {
* @throws XMPPException If the user is not allowed to make this request or the server does * @throws XMPPException If the user is not allowed to make this request or the server does
* not support offline message retrieval. * not support offline message retrieval.
*/ */
public Iterator getHeaders() throws XMPPException { public Iterator<OfflineMessageHeader> getHeaders() throws XMPPException {
List answer = new ArrayList(); List<OfflineMessageHeader> answer = new ArrayList<OfflineMessageHeader>();
DiscoverItems items = ServiceDiscoveryManager.getInstanceFor(connection).discoverItems( DiscoverItems items = ServiceDiscoveryManager.getInstanceFor(connection).discoverItems(
null, namespace); null, namespace);
for (Iterator it = items.getItems(); it.hasNext();) { for (Iterator it = items.getItems(); it.hasNext();) {
@ -132,11 +132,11 @@ public class OfflineMessageManager {
* @throws XMPPException If the user is not allowed to make this request or the server does * @throws XMPPException If the user is not allowed to make this request or the server does
* not support offline message retrieval. * not support offline message retrieval.
*/ */
public Iterator getMessages(final List nodes) throws XMPPException { public Iterator<Message> getMessages(final List<String> nodes) throws XMPPException {
List messages = new ArrayList(); List<Message> messages = new ArrayList<Message>();
OfflineMessageRequest request = new OfflineMessageRequest(); OfflineMessageRequest request = new OfflineMessageRequest();
for (Iterator it = nodes.iterator(); it.hasNext();) { for (String node : nodes) {
OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next()); OfflineMessageRequest.Item item = new OfflineMessageRequest.Item(node);
item.setAction("view"); item.setAction("view");
request.addItem(item); request.addItem(item);
} }
@ -188,8 +188,8 @@ public class OfflineMessageManager {
* @throws XMPPException If the user is not allowed to make this request or the server does * @throws XMPPException If the user is not allowed to make this request or the server does
* not support offline message retrieval. * not support offline message retrieval.
*/ */
public Iterator getMessages() throws XMPPException { public Iterator<Message> getMessages() throws XMPPException {
List messages = new ArrayList(); List<Message> messages = new ArrayList<Message>();
OfflineMessageRequest request = new OfflineMessageRequest(); OfflineMessageRequest request = new OfflineMessageRequest();
request.setFetch(true); request.setFetch(true);
// Filter packets looking for an answer from the server. // Filter packets looking for an answer from the server.
@ -232,10 +232,10 @@ public class OfflineMessageManager {
* @throws XMPPException If the user is not allowed to make this request or the server does * @throws XMPPException If the user is not allowed to make this request or the server does
* not support offline message retrieval. * not support offline message retrieval.
*/ */
public void deleteMessages(List nodes) throws XMPPException { public void deleteMessages(List<String> nodes) throws XMPPException {
OfflineMessageRequest request = new OfflineMessageRequest(); OfflineMessageRequest request = new OfflineMessageRequest();
for (Iterator it = nodes.iterator(); it.hasNext();) { for (String node : nodes) {
OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next()); OfflineMessageRequest.Item item = new OfflineMessageRequest.Item(node);
item.setAction("remove"); item.setAction("remove");
request.addItem(item); request.addItem(item);
} }

View file

@ -20,16 +20,20 @@
package org.jivesoftware.smackx; package org.jivesoftware.smackx;
import org.jivesoftware.smack.*; import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.provider.IQProvider; import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.packet.*; import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smackx.provider.*; import org.jivesoftware.smackx.packet.DefaultPrivateData;
import org.jivesoftware.smackx.packet.PrivateData;
import org.jivesoftware.smackx.provider.PrivateDataProvider;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
import java.util.Map;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Map;
/** /**
* Manages private data, which is a mechanism to allow users to store arbitrary XML * Manages private data, which is a mechanism to allow users to store arbitrary XML
@ -177,7 +181,7 @@ public class PrivateDataManager {
// Create an IQ packet to get the private data. // Create an IQ packet to get the private data.
IQ privateDataGet = new IQ() { IQ privateDataGet = new IQ() {
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:private\">"); buf.append("<query xmlns=\"jabber:iq:private\">");
buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\"/>"); buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\"/>");
buf.append("</query>"); buf.append("</query>");
@ -223,7 +227,7 @@ public class PrivateDataManager {
// Create an IQ packet to set the private data. // Create an IQ packet to set the private data.
IQ privateDataSet = new IQ() { IQ privateDataSet = new IQ() {
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:private\">"); buf.append("<query xmlns=\"jabber:iq:private\">");
buf.append(privateData.toXML()); buf.append(privateData.toXML());
buf.append("</query>"); buf.append("</query>");
@ -264,7 +268,7 @@ public class PrivateDataManager {
* @return a unique key for the element name and namespace pair. * @return a unique key for the element name and namespace pair.
*/ */
private static String getProviderKey(String elementName, String namespace) { private static String getProviderKey(String elementName, String namespace) {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(elementName).append("/><").append(namespace).append("/>"); buf.append("<").append(elementName).append("/><").append(namespace).append("/>");
return buf.toString(); return buf.toString();
} }
@ -343,7 +347,7 @@ public class PrivateDataManager {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:private\">"); buf.append("<query xmlns=\"jabber:iq:private\">");
if (privateData != null) { if (privateData != null) {
privateData.toXML(); privateData.toXML();

View file

@ -99,7 +99,7 @@ public class RemoteRosterEntry {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item jid=\"").append(user).append("\""); buf.append("<item jid=\"").append(user).append("\"");
if (name != null) { if (name != null) {
buf.append(" name=\"").append(name).append("\""); buf.append(" name=\"").append(name).append("\"");

View file

@ -20,11 +20,15 @@
package org.jivesoftware.smackx; package org.jivesoftware.smackx;
import java.util.*; import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smackx.packet.DataForm; import org.jivesoftware.smackx.packet.DataForm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* Represents a set of data results returned as part of a search. The report is structured * Represents a set of data results returned as part of a search. The report is structured
* in columns and rows. * in columns and rows.
@ -33,8 +37,8 @@ import org.jivesoftware.smackx.packet.DataForm;
*/ */
public class ReportedData { public class ReportedData {
private List columns = new ArrayList(); private List<Column> columns = new ArrayList<Column>();
private List rows = new ArrayList(); private List<Row> rows = new ArrayList<Row>();
private String title = ""; private String title = "";
/** /**
@ -73,13 +77,13 @@ public class ReportedData {
// Add the rows to the report based on the form's items // Add the rows to the report based on the form's items
for (Iterator items = dataForm.getItems(); items.hasNext();) { for (Iterator items = dataForm.getItems(); items.hasNext();) {
DataForm.Item item = (DataForm.Item)items.next(); DataForm.Item item = (DataForm.Item)items.next();
List fieldList = new ArrayList(columns.size()); List<Field> fieldList = new ArrayList<Field>(columns.size());
FormField field; FormField field;
for (Iterator fields = item.getFields(); fields.hasNext();) { for (Iterator fields = item.getFields(); fields.hasNext();) {
field = (FormField) fields.next(); field = (FormField) fields.next();
// The field is created with all the values of the data form's field // The field is created with all the values of the data form's field
List values = new ArrayList(); List<String> values = new ArrayList<String>();
for (Iterator it=field.getValues(); it.hasNext();) { for (Iterator<String> it=field.getValues(); it.hasNext();) {
values.add(it.next()); values.add(it.next());
} }
fieldList.add(new Field(field.getVariable(), values)); fieldList.add(new Field(field.getVariable(), values));
@ -118,8 +122,8 @@ public class ReportedData {
* *
* @return an Iterator for the rows returned from a search. * @return an Iterator for the rows returned from a search.
*/ */
public Iterator getRows() { public Iterator<Row> getRows() {
return Collections.unmodifiableList(new ArrayList(rows)).iterator(); return Collections.unmodifiableList(new ArrayList<Row>(rows)).iterator();
} }
/** /**
@ -127,8 +131,8 @@ public class ReportedData {
* *
* @return an Iterator for the columns returned from a search. * @return an Iterator for the columns returned from a search.
*/ */
public Iterator getColumns() { public Iterator<Column> getColumns() {
return Collections.unmodifiableList(new ArrayList(columns)).iterator(); return Collections.unmodifiableList(new ArrayList<Column>(columns)).iterator();
} }
@ -215,9 +219,9 @@ public class ReportedData {
} }
public static class Row { public static class Row {
private List fields = new ArrayList(); private List<Field> fields = new ArrayList<Field>();
public Row(List fields) { public Row(List<Field> fields) {
this.fields = fields; this.fields = fields;
} }
@ -228,8 +232,8 @@ public class ReportedData {
* @return the values of the field whose variable matches the requested variable. * @return the values of the field whose variable matches the requested variable.
*/ */
public Iterator getValues(String variable) { public Iterator getValues(String variable) {
for(Iterator it=getFields();it.hasNext();) { for(Iterator<Field> it=getFields();it.hasNext();) {
Field field = (Field) it.next(); Field field = it.next();
if (variable.equalsIgnoreCase(field.getVariable())) { if (variable.equalsIgnoreCase(field.getVariable())) {
return field.getValues(); return field.getValues();
} }
@ -242,16 +246,16 @@ public class ReportedData {
* *
* @return the fields that define the data that goes with the item. * @return the fields that define the data that goes with the item.
*/ */
private Iterator getFields() { private Iterator<Field> getFields() {
return Collections.unmodifiableList(new ArrayList(fields)).iterator(); return Collections.unmodifiableList(new ArrayList<Field>(fields)).iterator();
} }
} }
public static class Field { public static class Field {
private String variable; private String variable;
private List values; private List<String> values;
public Field(String variable, List values) { public Field(String variable, List<String> values) {
this.variable = variable; this.variable = variable;
this.values = values; this.values = values;
} }
@ -270,7 +274,7 @@ public class ReportedData {
* *
* @return the returned values of the search. * @return the returned values of the search.
*/ */
public Iterator getValues() { public Iterator<String> getValues() {
return Collections.unmodifiableList(values).iterator(); return Collections.unmodifiableList(values).iterator();
} }
} }

View file

@ -31,6 +31,7 @@ import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems; import org.jivesoftware.smackx.packet.DiscoverItems;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* Manages discovery of services in XMPP entities. This class provides: * Manages discovery of services in XMPP entities. This class provides:
@ -48,11 +49,13 @@ public class ServiceDiscoveryManager {
private static String identityName = "Smack"; private static String identityName = "Smack";
private static String identityType = "pc"; private static String identityType = "pc";
private static Map instances = new Hashtable(); private static Map<XMPPConnection, ServiceDiscoveryManager> instances =
new ConcurrentHashMap<XMPPConnection, ServiceDiscoveryManager>();
private XMPPConnection connection; private XMPPConnection connection;
private List features = new ArrayList(); private final List<String> features = new ArrayList<String>();
private Map nodeInformationProviders = new Hashtable(); private Map<String, NodeInformationProvider> nodeInformationProviders =
new ConcurrentHashMap<String, NodeInformationProvider>();
// Create a new ServiceDiscoveryManager on every established connection // Create a new ServiceDiscoveryManager on every established connection
static { static {
@ -82,7 +85,7 @@ public class ServiceDiscoveryManager {
* @return the ServiceDiscoveryManager associated with a given XMPPConnection. * @return the ServiceDiscoveryManager associated with a given XMPPConnection.
*/ */
public static ServiceDiscoveryManager getInstanceFor(XMPPConnection connection) { public static ServiceDiscoveryManager getInstanceFor(XMPPConnection connection) {
return (ServiceDiscoveryManager) instances.get(connection); return instances.get(connection);
} }
/** /**
@ -211,8 +214,8 @@ public class ServiceDiscoveryManager {
response.addIdentity(identity); response.addIdentity(identity);
// Add the registered features to the response // Add the registered features to the response
synchronized (features) { synchronized (features) {
for (Iterator it = getFeatures(); it.hasNext();) { for (Iterator<String> it = getFeatures(); it.hasNext();) {
response.addFeature((String) it.next()); response.addFeature(it.next());
} }
} }
} }
@ -258,7 +261,7 @@ public class ServiceDiscoveryManager {
if (node == null) { if (node == null) {
return null; return null;
} }
return (NodeInformationProvider) nodeInformationProviders.get(node); return nodeInformationProviders.get(node);
} }
/** /**
@ -297,9 +300,9 @@ public class ServiceDiscoveryManager {
* *
* @return an Iterator on the supported features by this XMPP entity. * @return an Iterator on the supported features by this XMPP entity.
*/ */
public Iterator getFeatures() { public Iterator<String> getFeatures() {
synchronized (features) { synchronized (features) {
return Collections.unmodifiableList(new ArrayList(features)).iterator(); return Collections.unmodifiableList(new ArrayList<String>(features)).iterator();
} }
} }

View file

@ -30,7 +30,7 @@ import org.jivesoftware.smack.util.StringUtils;
*/ */
public class XHTMLText { public class XHTMLText {
private StringBuffer text = new StringBuffer(30); private StringBuilder text = new StringBuilder(30);
/** /**
* Creates a new XHTMLText with body tag params. * Creates a new XHTMLText with body tag params.
@ -49,7 +49,7 @@ public class XHTMLText {
* @param style the XHTML style of the anchor * @param style the XHTML style of the anchor
*/ */
public void appendOpenAnchorTag(String href, String style) { public void appendOpenAnchorTag(String href, String style) {
StringBuffer sb = new StringBuffer("<a"); StringBuilder sb = new StringBuilder("<a");
if (href != null) { if (href != null) {
sb.append(" href=\""); sb.append(" href=\"");
sb.append(href); sb.append(href);
@ -78,7 +78,7 @@ public class XHTMLText {
* @param style the XHTML style of the blockquote * @param style the XHTML style of the blockquote
*/ */
public void appendOpenBlockQuoteTag(String style) { public void appendOpenBlockQuoteTag(String style) {
StringBuffer sb = new StringBuffer("<blockquote"); StringBuilder sb = new StringBuilder("<blockquote");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -103,7 +103,7 @@ public class XHTMLText {
* @param lang the language of the body * @param lang the language of the body
*/ */
private void appendOpenBodyTag(String style, String lang) { private void appendOpenBodyTag(String style, String lang) {
StringBuffer sb = new StringBuffer("<body"); StringBuilder sb = new StringBuilder("<body");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -184,7 +184,7 @@ public class XHTMLText {
if (level > 3 || level < 1) { if (level > 3 || level < 1) {
return; return;
} }
StringBuffer sb = new StringBuffer("<h"); StringBuilder sb = new StringBuilder("<h");
sb.append(level); sb.append(level);
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
@ -204,7 +204,7 @@ public class XHTMLText {
if (level > 3 || level < 1) { if (level > 3 || level < 1) {
return; return;
} }
StringBuffer sb = new StringBuffer("</h"); StringBuilder sb = new StringBuilder("</h");
sb.append(level); sb.append(level);
sb.append(">"); sb.append(">");
text.append(sb.toString()); text.append(sb.toString());
@ -220,7 +220,7 @@ public class XHTMLText {
* @param width how wide is the picture * @param width how wide is the picture
*/ */
public void appendImageTag(String align, String alt, String height, String src, String width) { public void appendImageTag(String align, String alt, String height, String src, String width) {
StringBuffer sb = new StringBuffer("<img"); StringBuilder sb = new StringBuilder("<img");
if (align != null) { if (align != null) {
sb.append(" align=\""); sb.append(" align=\"");
sb.append(align); sb.append(align);
@ -256,7 +256,7 @@ public class XHTMLText {
* @param style the style of the line item * @param style the style of the line item
*/ */
public void appendLineItemTag(String style) { public void appendLineItemTag(String style) {
StringBuffer sb = new StringBuffer("<li"); StringBuilder sb = new StringBuilder("<li");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -273,7 +273,7 @@ public class XHTMLText {
* @param style the style of the ordered list * @param style the style of the ordered list
*/ */
public void appendOpenOrderedListTag(String style) { public void appendOpenOrderedListTag(String style) {
StringBuffer sb = new StringBuffer("<ol"); StringBuilder sb = new StringBuilder("<ol");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -298,7 +298,7 @@ public class XHTMLText {
* @param style the style of the unordered list * @param style the style of the unordered list
*/ */
public void appendOpenUnorderedListTag(String style) { public void appendOpenUnorderedListTag(String style) {
StringBuffer sb = new StringBuffer("<ul"); StringBuilder sb = new StringBuilder("<ul");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -323,7 +323,7 @@ public class XHTMLText {
* @param style the style of the paragraph * @param style the style of the paragraph
*/ */
public void appendOpenParagraphTag(String style) { public void appendOpenParagraphTag(String style) {
StringBuffer sb = new StringBuffer("<p"); StringBuilder sb = new StringBuilder("<p");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -348,7 +348,7 @@ public class XHTMLText {
* @param style the style of the inlined quote * @param style the style of the inlined quote
*/ */
public void appendOpenInlinedQuoteTag(String style) { public void appendOpenInlinedQuoteTag(String style) {
StringBuffer sb = new StringBuffer("<q"); StringBuilder sb = new StringBuilder("<q");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);
@ -372,7 +372,7 @@ public class XHTMLText {
* @param style the style for a span of text * @param style the style for a span of text
*/ */
public void appendOpenSpanTag(String style) { public void appendOpenSpanTag(String style) {
StringBuffer sb = new StringBuffer("<span"); StringBuilder sb = new StringBuilder("<span");
if (style != null) { if (style != null) {
sb.append(" style=\""); sb.append(" style=\"");
sb.append(style); sb.append(style);

View file

@ -12,10 +12,10 @@ import org.jivesoftware.smackx.provider.PrivateDataProvider;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.io.IOException;
/** /**
* Bookmarks is used for storing and retrieving URLS and Conference rooms. * Bookmarks is used for storing and retrieving URLS and Conference rooms.
@ -155,7 +155,7 @@ public class Bookmarks implements PrivateData {
* @return the private data as XML. * @return the private data as XML.
*/ */
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<storage xmlns=\"storage:bookmarks\">"); buf.append("<storage xmlns=\"storage:bookmarks\">");
final Iterator urls = getBookmarkedURLS().iterator(); final Iterator urls = getBookmarkedURLS().iterator();

View file

@ -312,7 +312,7 @@ public class FileTransferNegotiator {
* @return Returns a new, unique, stream ID to identify a file transfer. * @return Returns a new, unique, stream ID to identify a file transfer.
*/ */
public String getNextStreamID() { public String getNextStreamID() {
StringBuffer buffer = new StringBuffer(); StringBuilder buffer = new StringBuilder();
buffer.append(STREAM_INIT_PREFIX); buffer.append(STREAM_INIT_PREFIX);
buffer.append(Math.abs(randomGenerator.nextLong())); buffer.append(Math.abs(randomGenerator.nextLong()));
@ -398,8 +398,8 @@ public class FileTransferNegotiator {
String variable; String variable;
boolean isByteStream = false; boolean isByteStream = false;
boolean isIBB = false; boolean isIBB = false;
for (Iterator it = field.getValues(); it.hasNext();) { for (Iterator<String> it = field.getValues(); it.hasNext();) {
variable = (it.next().toString()); variable = it.next();
if (variable.equals(BYTE_STREAM) && !IBB_ONLY) { if (variable.equals(BYTE_STREAM) && !IBB_ONLY) {
isByteStream = true; isByteStream = true;
} }

View file

@ -65,7 +65,7 @@ public class DeafOccupantInterceptor implements PacketInterceptor {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()) buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace())
.append("\">"); .append("\">");
buf.append("<deaf-occupant/>"); buf.append("<deaf-occupant/>");

File diff suppressed because it is too large Load diff

View file

@ -20,8 +20,8 @@
package org.jivesoftware.smackx.muc; package org.jivesoftware.smackx.muc;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.Form; import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.packet.DiscoverInfo;
/** /**
* Represents the room information that was discovered using Service Discovery. It's possible to * Represents the room information that was discovered using Service Discovery. It's possible to
@ -87,10 +87,10 @@ public class RoomInfo {
Form form = Form.getFormFrom(info); Form form = Form.getFormFrom(info);
if (form != null) { if (form != null) {
this.description = this.description =
(String) form.getField("muc#roominfo_description").getValues().next(); form.getField("muc#roominfo_description").getValues().next();
this.subject = (String) form.getField("muc#roominfo_subject").getValues().next(); this.subject = form.getField("muc#roominfo_subject").getValues().next();
this.occupantsCount = this.occupantsCount =
Integer.parseInt((String) form.getField("muc#roominfo_occupants").getValues() Integer.parseInt(form.getField("muc#roominfo_occupants").getValues()
.next()); .next());
} }
} }

View file

@ -223,7 +223,7 @@ public class Bytestream extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"http://jabber.org/protocol/bytestreams\""); buf.append("<query xmlns=\"http://jabber.org/protocol/bytestreams\"");
if (this.getType().equals(IQ.Type.SET)) { if (this.getType().equals(IQ.Type.SET)) {
@ -337,7 +337,7 @@ public class Bytestream extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" "); buf.append("<").append(getElementName()).append(" ");
buf.append("jid=\"").append(getJID()).append("\" "); buf.append("jid=\"").append(getJID()).append("\" ");
@ -394,7 +394,7 @@ public class Bytestream extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" "); buf.append("<").append(getElementName()).append(" ");
buf.append("jid=\"").append(getJID()).append("\" "); buf.append("jid=\"").append(getJID()).append("\" ");
buf.append("/>"); buf.append("/>");
@ -443,7 +443,7 @@ public class Bytestream extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(">"); buf.append("<").append(getElementName()).append(">");
buf.append(getTarget()); buf.append(getTarget());
buf.append("</").append(getElementName()).append(">"); buf.append("</").append(getElementName()).append(">");

View file

@ -20,14 +20,14 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.FormField;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.FormField;
/** /**
* Represents a form that could be use for gathering data as well as for reporting data * Represents a form that could be use for gathering data as well as for reporting data
* returned from a search. * returned from a search.
@ -38,10 +38,10 @@ public class DataForm implements PacketExtension {
private String type; private String type;
private String title; private String title;
private List instructions = new ArrayList(); private List<String> instructions = new ArrayList<String>();
private ReportedData reportedData; private ReportedData reportedData;
private List items = new ArrayList(); private final List<Item> items = new ArrayList<Item>();
private List fields = new ArrayList(); private final List<FormField> fields = new ArrayList<FormField>();
public DataForm(String type) { public DataForm(String type) {
this.type = type; this.type = type;
@ -85,9 +85,9 @@ public class DataForm implements PacketExtension {
* *
* @return an Iterator for the list of instructions that explain how to fill out the form. * @return an Iterator for the list of instructions that explain how to fill out the form.
*/ */
public Iterator getInstructions() { public Iterator<String> getInstructions() {
synchronized (instructions) { synchronized (instructions) {
return Collections.unmodifiableList(new ArrayList(instructions)).iterator(); return Collections.unmodifiableList(new ArrayList<String>(instructions)).iterator();
} }
} }
@ -105,9 +105,9 @@ public class DataForm implements PacketExtension {
* *
* @return an Iterator for the items returned from a search. * @return an Iterator for the items returned from a search.
*/ */
public Iterator getItems() { public Iterator<Item> getItems() {
synchronized (items) { synchronized (items) {
return Collections.unmodifiableList(new ArrayList(items)).iterator(); return Collections.unmodifiableList(new ArrayList<Item>(items)).iterator();
} }
} }
@ -116,9 +116,9 @@ public class DataForm implements PacketExtension {
* *
* @return an Iterator for the fields that are part of the form. * @return an Iterator for the fields that are part of the form.
*/ */
public Iterator getFields() { public Iterator<FormField> getFields() {
synchronized (fields) { synchronized (fields) {
return Collections.unmodifiableList(new ArrayList(fields)).iterator(); return Collections.unmodifiableList(new ArrayList<FormField>(fields)).iterator();
} }
} }
@ -147,7 +147,7 @@ public class DataForm implements PacketExtension {
* *
* @param instructions list of instructions that explain how to fill out the form. * @param instructions list of instructions that explain how to fill out the form.
*/ */
public void setInstructions(List instructions) { public void setInstructions(List<String> instructions) {
this.instructions = instructions; this.instructions = instructions;
} }
@ -196,7 +196,7 @@ public class DataForm implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\" type=\"" + getType() +"\">"); "\" type=\"" + getType() +"\">");
if (getTitle() != null) { if (getTitle() != null) {
@ -231,9 +231,9 @@ public class DataForm implements PacketExtension {
* @author Gaston Dombiak * @author Gaston Dombiak
*/ */
public static class ReportedData { public static class ReportedData {
private List fields = new ArrayList(); private List<FormField> fields = new ArrayList<FormField>();
public ReportedData(List fields) { public ReportedData(List<FormField> fields) {
this.fields = fields; this.fields = fields;
} }
@ -242,12 +242,12 @@ public class DataForm implements PacketExtension {
* *
* @return the fields returned from a search. * @return the fields returned from a search.
*/ */
public Iterator getFields() { public Iterator<FormField> getFields() {
return Collections.unmodifiableList(new ArrayList(fields)).iterator(); return Collections.unmodifiableList(new ArrayList<FormField>(fields)).iterator();
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<reported>"); buf.append("<reported>");
// Loop through all the form items and append them to the string buffer // Loop through all the form items and append them to the string buffer
for (Iterator i = getFields(); i.hasNext();) { for (Iterator i = getFields(); i.hasNext();) {
@ -266,9 +266,9 @@ public class DataForm implements PacketExtension {
* @author Gaston Dombiak * @author Gaston Dombiak
*/ */
public static class Item { public static class Item {
private List fields = new ArrayList(); private List<FormField> fields = new ArrayList<FormField>();
public Item(List fields) { public Item(List<FormField> fields) {
this.fields = fields; this.fields = fields;
} }
@ -277,12 +277,12 @@ public class DataForm implements PacketExtension {
* *
* @return the fields that define the data that goes with the item. * @return the fields that define the data that goes with the item.
*/ */
public Iterator getFields() { public Iterator<FormField> getFields() {
return Collections.unmodifiableList(new ArrayList(fields)).iterator(); return Collections.unmodifiableList(new ArrayList<FormField>(fields)).iterator();
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item>"); buf.append("<item>");
// Loop through all the form items and append them to the string buffer // Loop through all the form items and append them to the string buffer
for (Iterator i = getFields(); i.hasNext();) { for (Iterator i = getFields(); i.hasNext();) {

View file

@ -20,10 +20,10 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.Map;
import java.util.Iterator;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/** /**
* Default implementation of the PrivateData interface. Unless a PrivateDataProvider * Default implementation of the PrivateData interface. Unless a PrivateDataProvider
@ -83,7 +83,7 @@ public class DefaultPrivateData implements PrivateData {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">"); buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">");
for (Iterator i=getNames(); i.hasNext(); ) { for (Iterator i=getNames(); i.hasNext(); ) {
String name = (String)i.next(); String name = (String)i.next();

View file

@ -20,12 +20,12 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import org.jivesoftware.smack.packet.PacketExtension;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.TimeZone; import java.util.TimeZone;
import org.jivesoftware.smack.packet.PacketExtension;
/** /**
* Represents timestamp information about data stored for later delivery. A DelayInformation will * Represents timestamp information about data stored for later delivery. A DelayInformation will
* always includes the timestamp when the packet was originally sent and may include more * always includes the timestamp when the packet was originally sent and may include more
@ -124,7 +124,7 @@ public class DelayInformation implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\""); "\"");
buf.append(" stamp=\""); buf.append(" stamp=\"");

View file

@ -20,10 +20,13 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* A DiscoverInfo IQ packet, which is used by XMPP clients to request and receive information * A DiscoverInfo IQ packet, which is used by XMPP clients to request and receive information
* to/from other XMPP entities.<p> * to/from other XMPP entities.<p>
@ -35,8 +38,8 @@ import org.jivesoftware.smack.packet.IQ;
*/ */
public class DiscoverInfo extends IQ { public class DiscoverInfo extends IQ {
private List features = new ArrayList(); private final List<Feature> features = new ArrayList<Feature>();
private List identities = new ArrayList(); private final List<Identity> identities = new ArrayList<Identity>();
private String node; private String node;
/** /**
@ -59,9 +62,9 @@ public class DiscoverInfo extends IQ {
* *
* @return an Iterator on the discovered features of an XMPP entity * @return an Iterator on the discovered features of an XMPP entity
*/ */
Iterator getFeatures() { Iterator<Feature> getFeatures() {
synchronized (features) { synchronized (features) {
return Collections.unmodifiableList(new ArrayList(features)).iterator(); return Collections.unmodifiableList(new ArrayList<Feature>(features)).iterator();
} }
} }
@ -81,9 +84,9 @@ public class DiscoverInfo extends IQ {
* *
* @return an Iterator on the discoveted identities * @return an Iterator on the discoveted identities
*/ */
public Iterator getIdentities() { public Iterator<Identity> getIdentities() {
synchronized (identities) { synchronized (identities) {
return Collections.unmodifiableList(new ArrayList(identities)).iterator(); return Collections.unmodifiableList(new ArrayList<Identity>(identities)).iterator();
} }
} }
@ -120,15 +123,15 @@ public class DiscoverInfo extends IQ {
* @return true if the requestes feature has been discovered * @return true if the requestes feature has been discovered
*/ */
public boolean containsFeature(String feature) { public boolean containsFeature(String feature) {
for (Iterator it = getFeatures(); it.hasNext();) { for (Iterator<Feature> it = getFeatures(); it.hasNext();) {
if (feature.equals(((DiscoverInfo.Feature) it.next()).getVar())) if (feature.equals(it.next().getVar()))
return true; return true;
} }
return false; return false;
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"http://jabber.org/protocol/disco#info\""); buf.append("<query xmlns=\"http://jabber.org/protocol/disco#info\"");
if (getNode() != null) { if (getNode() != null) {
buf.append(" node=\""); buf.append(" node=\"");
@ -137,14 +140,12 @@ public class DiscoverInfo extends IQ {
} }
buf.append(">"); buf.append(">");
synchronized (identities) { synchronized (identities) {
for (int i = 0; i < identities.size(); i++) { for (Identity identity : identities) {
Identity identity = (Identity) identities.get(i);
buf.append(identity.toXML()); buf.append(identity.toXML());
} }
} }
synchronized (features) { synchronized (features) {
for (int i = 0; i < features.size(); i++) { for (Feature feature : features) {
Feature feature = (Feature) features.get(i);
buf.append(feature.toXML()); buf.append(feature.toXML());
} }
} }
@ -220,7 +221,7 @@ public class DiscoverInfo extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<identity category=\"").append(category).append("\""); buf.append("<identity category=\"").append(category).append("\"");
buf.append(" name=\"").append(name).append("\""); buf.append(" name=\"").append(name).append("\"");
if (type != null) { if (type != null) {
@ -260,7 +261,7 @@ public class DiscoverInfo extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<feature var=\"").append(variable).append("\"/>"); buf.append("<feature var=\"").append(variable).append("\"/>");
return buf.toString(); return buf.toString();
} }

View file

@ -20,10 +20,13 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* A DiscoverItems IQ packet, which is used by XMPP clients to request and receive items * A DiscoverItems IQ packet, which is used by XMPP clients to request and receive items
* associated with XMPP entities.<p> * associated with XMPP entities.<p>
@ -35,7 +38,7 @@ import org.jivesoftware.smack.packet.IQ;
*/ */
public class DiscoverItems extends IQ { public class DiscoverItems extends IQ {
private List items = new ArrayList(); private final List<DiscoverItems.Item> items = new ArrayList<DiscoverItems.Item>();
private String node; private String node;
/** /**
@ -54,9 +57,10 @@ public class DiscoverItems extends IQ {
* *
* @return an Iterator on the discovered entity's items * @return an Iterator on the discovered entity's items
*/ */
public Iterator getItems() { public Iterator<DiscoverItems.Item> getItems() {
synchronized (items) { synchronized (items) {
return Collections.unmodifiableList(new ArrayList(items)).iterator(); return Collections.unmodifiableList(new ArrayList<DiscoverItems.Item>(items))
.iterator();
} }
} }
@ -87,7 +91,7 @@ public class DiscoverItems extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"http://jabber.org/protocol/disco#items\""); buf.append("<query xmlns=\"http://jabber.org/protocol/disco#items\"");
if (getNode() != null) { if (getNode() != null) {
buf.append(" node=\""); buf.append(" node=\"");
@ -97,7 +101,7 @@ public class DiscoverItems extends IQ {
buf.append(">"); buf.append(">");
synchronized (items) { synchronized (items) {
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
Item item = (Item) items.get(i); Item item = items.get(i);
buf.append(item.toXML()); buf.append(item.toXML());
} }
} }
@ -217,7 +221,7 @@ public class DiscoverItems extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item jid=\"").append(entityID).append("\""); buf.append("<item jid=\"").append(entityID).append("\"");
if (name != null) { if (name != null) {
buf.append(" name=\"").append(name).append("\""); buf.append(" name=\"").append(name).append("\"");

View file

@ -93,7 +93,7 @@ public class IBBExtensions {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append("\" "); buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append("\" ");
buf.append("sid=\"").append(getSessionID()).append("\" "); buf.append("sid=\"").append(getSessionID()).append("\" ");
buf.append("block-size=\"").append(getBlockSize()).append("\""); buf.append("block-size=\"").append(getBlockSize()).append("\"");
@ -193,7 +193,7 @@ public class IBBExtensions {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()) buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace())
.append("\" "); .append("\" ");
buf.append("sid=\"").append(getSessionID()).append("\" "); buf.append("sid=\"").append(getSessionID()).append("\" ");
@ -230,7 +230,7 @@ public class IBBExtensions {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append("\" "); buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append("\" ");
buf.append("sid=\"").append(getSessionID()).append("\""); buf.append("sid=\"").append(getSessionID()).append("\"");
buf.append("/>"); buf.append("/>");

View file

@ -25,10 +25,10 @@ import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider; import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smack.util.StringUtils;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
/** /**
@ -56,7 +56,7 @@ public class LastActivity extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:last\"></query>"); buf.append("<query xmlns=\"jabber:iq:last\"></query>");
return buf.toString(); return buf.toString();
} }

View file

@ -19,10 +19,13 @@
*/ */
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* IQ packet that serves for kicking users, granting and revoking voice, banning users, * IQ packet that serves for kicking users, granting and revoking voice, banning users,
* modifying the ban list, granting and revoking membership and granting and revoking * modifying the ban list, granting and revoking membership and granting and revoking
@ -60,7 +63,7 @@ public class MUCAdmin extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"http://jabber.org/protocol/muc#admin\">"); buf.append("<query xmlns=\"http://jabber.org/protocol/muc#admin\">");
synchronized (items) { synchronized (items) {
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
@ -201,7 +204,7 @@ public class MUCAdmin extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item"); buf.append("<item");
if (getAffiliation() != null) { if (getAffiliation() != null) {
buf.append(" affiliation=\"").append(getAffiliation()).append("\""); buf.append(" affiliation=\"").append(getAffiliation()).append("\"");

View file

@ -20,12 +20,12 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import org.jivesoftware.smack.packet.PacketExtension;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.TimeZone; import java.util.TimeZone;
import org.jivesoftware.smack.packet.PacketExtension;
/** /**
* Represents extended presence information whose sole purpose is to signal the ability of * Represents extended presence information whose sole purpose is to signal the ability of
* the occupant to speak the MUC protocol when joining a room. If the room requires a password * the occupant to speak the MUC protocol when joining a room. If the room requires a password
@ -52,7 +52,7 @@ public class MUCInitialPresence implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
if (getPassword() != null) { if (getPassword() != null) {
@ -200,7 +200,7 @@ public class MUCInitialPresence implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<history"); buf.append("<history");
if (getMaxChars() != -1) { if (getMaxChars() != -1) {
buf.append(" maxchars=\"").append(getMaxChars()).append("\""); buf.append(" maxchars=\"").append(getMaxChars()).append("\"");

View file

@ -19,10 +19,13 @@
*/ */
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* IQ packet that serves for granting and revoking ownership privileges, granting * IQ packet that serves for granting and revoking ownership privileges, granting
* and revoking administrative privileges and destroying a room. All these operations * and revoking administrative privileges and destroying a room. All these operations
@ -82,7 +85,7 @@ public class MUCOwner extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"http://jabber.org/protocol/muc#owner\">"); buf.append("<query xmlns=\"http://jabber.org/protocol/muc#owner\">");
synchronized (items) { synchronized (items) {
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
@ -237,7 +240,7 @@ public class MUCOwner extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item"); buf.append("<item");
if (getAffiliation() != null) { if (getAffiliation() != null) {
buf.append(" affiliation=\"").append(getAffiliation()).append("\""); buf.append(" affiliation=\"").append(getAffiliation()).append("\"");
@ -317,7 +320,7 @@ public class MUCOwner extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<destroy"); buf.append("<destroy");
if (getJid() != null) { if (getJid() != null) {
buf.append(" jid=\"").append(getJid()).append("\""); buf.append(" jid=\"").append(getJid()).append("\"");

View file

@ -46,7 +46,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
if (getInvite() != null) { if (getInvite() != null) {
@ -261,7 +261,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<invite "); buf.append("<invite ");
if (getTo() != null) { if (getTo() != null) {
buf.append(" to=\"").append(getTo()).append("\""); buf.append(" to=\"").append(getTo()).append("\"");
@ -346,7 +346,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<decline "); buf.append("<decline ");
if (getTo() != null) { if (getTo() != null) {
buf.append(" to=\"").append(getTo()).append("\""); buf.append(" to=\"").append(getTo()).append("\"");
@ -490,7 +490,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item"); buf.append("<item");
if (getAffiliation() != null) { if (getAffiliation() != null) {
buf.append(" affiliation=\"").append(getAffiliation()).append("\""); buf.append(" affiliation=\"").append(getAffiliation()).append("\"");
@ -550,7 +550,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<status code=\"").append(getCode()).append("\"/>"); buf.append("<status code=\"").append(getCode()).append("\"/>");
return buf.toString(); return buf.toString();
} }
@ -605,7 +605,7 @@ public class MUCUser implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<destroy"); buf.append("<destroy");
if (getJid() != null) { if (getJid() != null) {
buf.append(" jid=\"").append(getJid()).append("\""); buf.append(" jid=\"").append(getJid()).append("\"");

View file

@ -20,10 +20,11 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import java.util.ArrayList;
import java.util.Iterator;
/** /**
* Represents message events relating to the delivery, display, composition and cancellation of * Represents message events relating to the delivery, display, composition and cancellation of
* messages.<p> * messages.<p>
@ -303,7 +304,7 @@ public class MessageEvent implements PacketExtension {
* *
*/ */
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
// Note: Cancellation events don't specify any tag. They just send the packetID // Note: Cancellation events don't specify any tag. They just send the packetID

View file

@ -105,7 +105,7 @@ public class MultipleAddresses implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()); buf.append("<").append(getElementName());
buf.append(" xmlns=\"").append(getNamespace()).append("\">"); buf.append(" xmlns=\"").append(getNamespace()).append("\">");
// Loop through all the addresses and append them to the string buffer // Loop through all the addresses and append them to the string buffer
@ -175,7 +175,7 @@ public class MultipleAddresses implements PacketExtension {
} }
private String toXML() { private String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<address type=\""); buf.append("<address type=\"");
// Append the address type (e.g. TO/CC/BCC) // Append the address type (e.g. TO/CC/BCC)
buf.append(type).append("\""); buf.append(type).append("\"");

View file

@ -79,7 +79,7 @@ public class OfflineMessageInfo implements PacketExtension {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
if (getNode() != null) if (getNode() != null)

View file

@ -102,7 +102,7 @@ public class OfflineMessageRequest extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<offline xmlns=\"http://jabber.org/protocol/offline\">"); buf.append("<offline xmlns=\"http://jabber.org/protocol/offline\">");
synchronized (items) { synchronized (items) {
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
@ -175,7 +175,7 @@ public class OfflineMessageRequest extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<item"); buf.append("<item");
if (getAction() != null) { if (getAction() != null) {
buf.append(" action=\"").append(getAction()).append("\""); buf.append(" action=\"").append(getAction()).append("\"");

View file

@ -20,11 +20,16 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*; import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.*; import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.*; import org.jivesoftware.smackx.RemoteRosterEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* Represents XMPP Roster Item Exchange packets.<p> * Represents XMPP Roster Item Exchange packets.<p>
@ -161,7 +166,7 @@ public class RosterExchange implements PacketExtension {
* *
*/ */
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
// Loop through all roster entries and append them to the string buffer // Loop through all roster entries and append them to the string buffer

View file

@ -31,7 +31,7 @@ public class SharedGroupsInfo extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<sharedgroup xmlns=\"http://www.jivesoftware.org/protocol/sharedgroup\">"); buf.append("<sharedgroup xmlns=\"http://www.jivesoftware.org/protocol/sharedgroup\">");
for (Iterator it=groups.iterator(); it.hasNext();) { for (Iterator it=groups.iterator(); it.hasNext();) {
buf.append("<group>").append(it.next()).append("</group>"); buf.append("<group>").append(it.next()).append("</group>");

View file

@ -134,7 +134,7 @@ public class StreamInitiation extends IQ {
* @see org.jivesoftware.smack.packet.IQ#getChildElementXML() * @see org.jivesoftware.smack.packet.IQ#getChildElementXML()
*/ */
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
if (this.getType().equals(IQ.Type.SET)) { if (this.getType().equals(IQ.Type.SET)) {
buf.append("<si xmlns=\"http://jabber.org/protocol/si\" "); buf.append("<si xmlns=\"http://jabber.org/protocol/si\" ");
if (getSessionID() != null) { if (getSessionID() != null) {
@ -333,7 +333,7 @@ public class StreamInitiation extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buffer = new StringBuffer(); StringBuilder buffer = new StringBuilder();
buffer.append("<").append(getElementName()).append(" xmlns=\"") buffer.append("<").append(getElementName()).append(" xmlns=\"")
.append(getNamespace()).append("\" "); .append(getNamespace()).append("\" ");
@ -408,7 +408,7 @@ public class StreamInitiation extends IQ {
} }
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf buf
.append("<feature xmlns=\"http://jabber.org/protocol/feature-neg\">"); .append("<feature xmlns=\"http://jabber.org/protocol/feature-neg\">");
buf.append(data.toXML()); buf.append(data.toXML());

View file

@ -22,9 +22,11 @@ package org.jivesoftware.smackx.packet;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/** /**
* A Time IQ packet, which is used by XMPP clients to exchange their respective local * A Time IQ packet, which is used by XMPP clients to exchange their respective local
@ -179,7 +181,7 @@ public class Time extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:time\">"); buf.append("<query xmlns=\"jabber:iq:time\">");
if (utc != null) { if (utc != null) {
buf.append("<utc>").append(utc).append("</utc>"); buf.append("<utc>").append(utc).append("</utc>");

View file

@ -26,8 +26,8 @@ import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@ -89,8 +89,8 @@ public class VCard extends IQ {
* Phone types: * Phone types:
* VOICE?, FAX?, PAGER?, MSG?, CELL?, VIDEO?, BBS?, MODEM?, ISDN?, PCS?, PREF? * VOICE?, FAX?, PAGER?, MSG?, CELL?, VIDEO?, BBS?, MODEM?, ISDN?, PCS?, PREF?
*/ */
private Map homePhones = new HashMap(); private Map<String, String> homePhones = new HashMap<String, String>();
private Map workPhones = new HashMap(); private Map<String, String> workPhones = new HashMap<String, String>();
/** /**
@ -98,8 +98,8 @@ public class VCard extends IQ {
* POSTAL?, PARCEL?, (DOM | INTL)?, PREF?, POBOX?, EXTADR?, STREET?, LOCALITY?, * POSTAL?, PARCEL?, (DOM | INTL)?, PREF?, POBOX?, EXTADR?, STREET?, LOCALITY?,
* REGION?, PCODE?, CTRY? * REGION?, PCODE?, CTRY?
*/ */
private Map homeAddr = new HashMap(); private Map<String, String> homeAddr = new HashMap<String, String>();
private Map workAddr = new HashMap(); private Map<String, String> workAddr = new HashMap<String, String>();
private String firstName; private String firstName;
private String lastName; private String lastName;
@ -116,10 +116,10 @@ public class VCard extends IQ {
/** /**
* Such as DESC ROLE GEO etc.. see JEP-0054 * Such as DESC ROLE GEO etc.. see JEP-0054
*/ */
private Map otherSimpleFields = new HashMap(); private Map<String, String> otherSimpleFields = new HashMap<String, String>();
// fields that, as they are should not be escaped before forwarding to the server // fields that, as they are should not be escaped before forwarding to the server
private Map otherUnescapableFields = new HashMap(); private Map<String, String> otherUnescapableFields = new HashMap<String, String>();
public VCard() { public VCard() {
} }
@ -131,7 +131,7 @@ public class VCard extends IQ {
* GEO, TITLE, ROLE, LOGO, NOTE, PRODID, REV, SORT-STRING, SOUND, UID, URL, DESC. * GEO, TITLE, ROLE, LOGO, NOTE, PRODID, REV, SORT-STRING, SOUND, UID, URL, DESC.
*/ */
public String getField(String field) { public String getField(String field) {
return (String) otherSimpleFields.get(field); return otherSimpleFields.get(field);
} }
/** /**
@ -168,6 +168,8 @@ public class VCard extends IQ {
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
// Update FN field
updateFN();
} }
public String getLastName() { public String getLastName() {
@ -176,6 +178,8 @@ public class VCard extends IQ {
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
// Update FN field
updateFN();
} }
public String getMiddleName() { public String getMiddleName() {
@ -184,10 +188,12 @@ public class VCard extends IQ {
public void setMiddleName(String middleName) { public void setMiddleName(String middleName) {
this.middleName = middleName; this.middleName = middleName;
// Update FN field
updateFN();
} }
public String getNickName() { public String getNickName() {
return (String) otherSimpleFields.get("NICKNAME"); return otherSimpleFields.get("NICKNAME");
} }
public void setNickName(String nickName) { public void setNickName(String nickName) {
@ -211,7 +217,7 @@ public class VCard extends IQ {
} }
public String getJabberId() { public String getJabberId() {
return (String) otherSimpleFields.get("JABBERID"); return otherSimpleFields.get("JABBERID");
} }
public void setJabberId(String jabberId) { public void setJabberId(String jabberId) {
@ -241,7 +247,7 @@ public class VCard extends IQ {
* LOCALITY, REGION, PCODE, CTRY * LOCALITY, REGION, PCODE, CTRY
*/ */
public String getAddressFieldHome(String addrField) { public String getAddressFieldHome(String addrField) {
return (String) homeAddr.get(addrField); return homeAddr.get(addrField);
} }
/** /**
@ -261,7 +267,7 @@ public class VCard extends IQ {
* LOCALITY, REGION, PCODE, CTRY * LOCALITY, REGION, PCODE, CTRY
*/ */
public String getAddressFieldWork(String addrField) { public String getAddressFieldWork(String addrField) {
return (String) workAddr.get(addrField); return workAddr.get(addrField);
} }
/** /**
@ -291,7 +297,7 @@ public class VCard extends IQ {
* @param phoneType one of VOICE, FAX, PAGER, MSG, CELL, VIDEO, BBS, MODEM, ISDN, PCS, PREF * @param phoneType one of VOICE, FAX, PAGER, MSG, CELL, VIDEO, BBS, MODEM, ISDN, PCS, PREF
*/ */
public String getPhoneHome(String phoneType) { public String getPhoneHome(String phoneType) {
return (String) homePhones.get(phoneType); return homePhones.get(phoneType);
} }
/** /**
@ -310,7 +316,7 @@ public class VCard extends IQ {
* @param phoneType one of VOICE, FAX, PAGER, MSG, CELL, VIDEO, BBS, MODEM, ISDN, PCS, PREF * @param phoneType one of VOICE, FAX, PAGER, MSG, CELL, VIDEO, BBS, MODEM, ISDN, PCS, PREF
*/ */
public String getPhoneWork(String phoneType) { public String getPhoneWork(String phoneType) {
return (String) workPhones.get(phoneType); return workPhones.get(phoneType);
} }
/** /**
@ -442,6 +448,20 @@ public class VCard extends IQ {
return StringUtils.encodeHex(digest.digest()); return StringUtils.encodeHex(digest.digest());
} }
private void updateFN() {
StringBuilder sb = new StringBuilder();
if (firstName != null) {
sb.append(StringUtils.escapeForXML(firstName)).append(' ');
}
if (middleName != null) {
sb.append(StringUtils.escapeForXML(middleName)).append(' ');
}
if (lastName != null) {
sb.append(StringUtils.escapeForXML(lastName));
}
setField("FN", sb.toString());
}
/** /**
* Save this vCard for the user connected by 'connection'. Connection should be authenticated * Save this vCard for the user connected by 'connection'. Connection should be authenticated
* and not anonymous.<p> * and not anonymous.<p>
@ -516,7 +536,7 @@ public class VCard extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
new VCardWriter(sb).write(); new VCardWriter(sb).write();
return sb.toString(); return sb.toString();
} }
@ -525,8 +545,7 @@ public class VCard extends IQ {
if (result == null) result = new VCard(); if (result == null) result = new VCard();
Field[] fields = VCard.class.getDeclaredFields(); Field[] fields = VCard.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) { for (Field field : fields) {
Field field = fields[i];
if (field.getDeclaringClass() == VCard.class && if (field.getDeclaringClass() == VCard.class &&
!Modifier.isFinal(field.getModifiers())) { !Modifier.isFinal(field.getModifiers())) {
try { try {
@ -647,9 +666,9 @@ public class VCard extends IQ {
private class VCardWriter { private class VCardWriter {
private final StringBuffer sb; private final StringBuilder sb;
VCardWriter(StringBuffer sb) { VCardWriter(StringBuilder sb) {
this.sb = sb; this.sb = sb;
} }
@ -663,7 +682,6 @@ public class VCard extends IQ {
private void buildActualContent() { private void buildActualContent() {
if (hasNameField()) { if (hasNameField()) {
appendFN();
appendN(); appendN();
} }
@ -693,7 +711,7 @@ public class VCard extends IQ {
} }
} }
private void appendPhones(Map phones, final String code) { private void appendPhones(Map<String, String> phones, final String code) {
Iterator it = phones.entrySet().iterator(); Iterator it = phones.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
final Map.Entry entry = (Map.Entry) it.next(); final Map.Entry entry = (Map.Entry) it.next();
@ -707,7 +725,7 @@ public class VCard extends IQ {
} }
} }
private void appendAddress(final Map addr, final String code) { private void appendAddress(final Map<String, String> addr, final String code) {
if (addr.size() > 0) { if (addr.size() > 0) {
appendTag("ADR", true, new ContentBuilder() { appendTag("ADR", true, new ContentBuilder() {
public void addTagContent() { public void addTagContent() {
@ -753,23 +771,6 @@ public class VCard extends IQ {
} }
} }
private void appendFN() {
final ContentBuilder contentBuilder = new ContentBuilder() {
public void addTagContent() {
if (firstName != null) {
sb.append(StringUtils.escapeForXML(firstName)).append(' ');
}
if (middleName != null) {
sb.append(StringUtils.escapeForXML(middleName)).append(' ');
}
if (lastName != null) {
sb.append(StringUtils.escapeForXML(lastName));
}
}
};
appendTag("FN", true, contentBuilder);
}
private void appendN() { private void appendN() {
appendTag("N", true, new ContentBuilder() { appendTag("N", true, new ContentBuilder() {
public void addTagContent() { public void addTagContent() {

View file

@ -115,7 +115,7 @@ public class Version extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:version\">"); buf.append("<query xmlns=\"jabber:iq:version\">");
if (name != null) { if (name != null) {
buf.append("<name>").append(name).append("</name>"); buf.append("<name>").append(name).append("</name>");

View file

@ -20,10 +20,13 @@
package org.jivesoftware.smackx.packet; package org.jivesoftware.smackx.packet;
import java.util.*;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/** /**
* An XHTML sub-packet, which is used by XMPP clients to exchange formatted text. The XHTML * An XHTML sub-packet, which is used by XMPP clients to exchange formatted text. The XHTML
* extension is only a subset of XHTML 1.0.<p> * extension is only a subset of XHTML 1.0.<p>
@ -78,7 +81,7 @@ public class XHTMLExtension implements PacketExtension {
* *
*/ */
public String toXML() { public String toXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append( buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">"); "\">");
// Loop through all the bodies and append them to the string buffer // Loop through all the bodies and append them to the string buffer

View file

@ -47,7 +47,7 @@ public class BytestreamsProvider implements IQProvider {
* @see org.jivesoftware.smack.provider.IQProvider#parseIQ(org.xmlpull.v1.XmlPullParser) * @see org.jivesoftware.smack.provider.IQProvider#parseIQ(org.xmlpull.v1.XmlPullParser)
*/ */
public IQ parseIQ(XmlPullParser parser) throws Exception { public IQ parseIQ(XmlPullParser parser) throws Exception {
// StringBuffer buf = new StringBuffer(); // StringBuilder buf = new StringBuilder();
boolean done = false; boolean done = false;
Bytestream toReturn = new Bytestream(); Bytestream toReturn = new Bytestream();

View file

@ -20,15 +20,15 @@
package org.jivesoftware.smackx.provider; package org.jivesoftware.smackx.provider;
import java.util.ArrayList;
import java.util.List;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider; import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smackx.FormField; import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.packet.DataForm; import org.jivesoftware.smackx.packet.DataForm;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import java.util.List;
/** /**
* The DataFormProvider parses DataForm packets. * The DataFormProvider parses DataForm packets.
* *
@ -45,7 +45,7 @@ public class DataFormProvider implements PacketExtensionProvider {
public PacketExtension parseExtension(XmlPullParser parser) throws Exception { public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
boolean done = false; boolean done = false;
StringBuffer buffer = null; StringBuilder buffer = null;
DataForm dataForm = new DataForm(parser.getAttributeValue("", "type")); DataForm dataForm = new DataForm(parser.getAttributeValue("", "type"));
while (!done) { while (!done) {
int eventType = parser.next(); int eventType = parser.next();

View file

@ -32,8 +32,8 @@ import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
/** /**
* vCard provider. * vCard provider.
@ -45,7 +45,7 @@ public class VCardProvider implements IQProvider {
private final static String PREFERRED_ENCODING = "UTF-8"; private final static String PREFERRED_ENCODING = "UTF-8";
public IQ parseIQ(XmlPullParser parser) throws Exception { public IQ parseIQ(XmlPullParser parser) throws Exception {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
try { try {
int event = parser.getEventType(); int event = parser.getEventType();
// get the content // get the content
@ -229,12 +229,12 @@ public class VCardProvider implements IQProvider {
} }
private String getTextContent(Node node) { private String getTextContent(Node node) {
StringBuffer result = new StringBuffer(); StringBuilder result = new StringBuilder();
appendText(result, node); appendText(result, node);
return result.toString(); return result.toString();
} }
private void appendText(StringBuffer result, Node node) { private void appendText(StringBuilder result, Node node) {
NodeList childNodes = node.getChildNodes(); NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) { for (int i = 0; i < childNodes.getLength(); i++) {
Node nd = childNodes.item(i); Node nd = childNodes.item(i);

View file

@ -51,7 +51,7 @@ public class XHTMLExtensionProvider implements PacketExtensionProvider {
throws Exception { throws Exception {
XHTMLExtension xhtmlExtension = new XHTMLExtension(); XHTMLExtension xhtmlExtension = new XHTMLExtension();
boolean done = false; boolean done = false;
StringBuffer buffer = new StringBuffer(); StringBuilder buffer = new StringBuilder();
int startDepth = parser.getDepth(); int startDepth = parser.getDepth();
int depth = parser.getDepth(); int depth = parser.getDepth();
String lastTag = ""; String lastTag = "";
@ -59,7 +59,7 @@ public class XHTMLExtensionProvider implements PacketExtensionProvider {
int eventType = parser.next(); int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) { if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("body")) { if (parser.getName().equals("body")) {
buffer = new StringBuffer(); buffer = new StringBuilder();
depth = parser.getDepth(); depth = parser.getDepth();
} }
lastTag = parser.getText(); lastTag = parser.getText();

View file

@ -42,7 +42,7 @@ class SimpleUserSearch extends IQ {
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:search\">"); buf.append("<query xmlns=\"jabber:iq:search\">");
buf.append(getItemsToSearch()); buf.append(getItemsToSearch());
buf.append("</query>"); buf.append("</query>");
@ -50,7 +50,7 @@ class SimpleUserSearch extends IQ {
} }
private String getItemsToSearch() { private String getItemsToSearch() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
if (form == null) { if (form == null) {
form = Form.getFormFrom(this); form = Form.getFormFrom(this);
@ -60,9 +60,9 @@ class SimpleUserSearch extends IQ {
return ""; return "";
} }
Iterator fields = form.getFields(); Iterator<FormField> fields = form.getFields();
while (fields.hasNext()) { while (fields.hasNext()) {
FormField field = (FormField) fields.next(); FormField field = fields.next();
String name = field.getVariable(); String name = field.getVariable();
String value = getSingleValue(field); String value = getSingleValue(field);
if (value.trim().length() > 0) { if (value.trim().length() > 0) {
@ -74,9 +74,9 @@ class SimpleUserSearch extends IQ {
} }
private static String getSingleValue(FormField formField) { private static String getSingleValue(FormField formField) {
Iterator values = formField.getValues(); Iterator<String> values = formField.getValues();
while (values.hasNext()) { while (values.hasNext()) {
return (String) values.next(); return values.next();
} }
return ""; return "";
} }
@ -87,11 +87,11 @@ class SimpleUserSearch extends IQ {
boolean done = false; boolean done = false;
List fields = new ArrayList(); List<ReportedData.Field> fields = new ArrayList<ReportedData.Field>();
while (!done) { while (!done) {
if (parser.getAttributeCount() > 0) { if (parser.getAttributeCount() > 0) {
String jid = parser.getAttributeValue("", "jid"); String jid = parser.getAttributeValue("", "jid");
List valueList = new ArrayList(); List<String> valueList = new ArrayList<String>();
valueList.add(jid); valueList.add(jid);
ReportedData.Field field = new ReportedData.Field("jid", valueList); ReportedData.Field field = new ReportedData.Field("jid", valueList);
fields.add(field); fields.add(field);
@ -100,7 +100,7 @@ class SimpleUserSearch extends IQ {
int eventType = parser.next(); int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG && parser.getName().equals("item")) { if (eventType == XmlPullParser.START_TAG && parser.getName().equals("item")) {
fields = new ArrayList(); fields = new ArrayList<ReportedData.Field>();
} }
else if (eventType == XmlPullParser.END_TAG && parser.getName().equals("item")) { else if (eventType == XmlPullParser.END_TAG && parser.getName().equals("item")) {
ReportedData.Row row = new ReportedData.Row(fields); ReportedData.Row row = new ReportedData.Row(fields);
@ -110,7 +110,7 @@ class SimpleUserSearch extends IQ {
String name = parser.getName(); String name = parser.getName();
String value = parser.nextText(); String value = parser.nextText();
List valueList = new ArrayList(); List<String> valueList = new ArrayList<String>();
valueList.add(value); valueList.add(value);
ReportedData.Field field = new ReportedData.Field(name, valueList); ReportedData.Field field = new ReportedData.Field(name, valueList);
fields.add(field); fields.add(field);

View file

@ -43,7 +43,7 @@ public class UserSearch extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:search\">"); buf.append("<query xmlns=\"jabber:iq:search\">");
buf.append(getExtensionsXML()); buf.append(getExtensionsXML());
buf.append("</query>"); buf.append("</query>");

View file

@ -20,12 +20,12 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.test.SmackTestCase;
/** /**
* Ensure that the server is handling IQ packets correctly. * Ensure that the server is handling IQ packets correctly.
@ -45,7 +45,7 @@ public class IQTest extends SmackTestCase {
public void testInvalidNamespace() { public void testInvalidNamespace() {
IQ iq = new IQ() { IQ iq = new IQ() {
public String getChildElementXML() { public String getChildElementXML() {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
buf.append("<query xmlns=\"jabber:iq:anything\">"); buf.append("<query xmlns=\"jabber:iq:anything\">");
buf.append("</query>"); buf.append("</query>");
return buf.toString(); return buf.toString();

View file

@ -20,10 +20,10 @@
package org.jivesoftware.smack; package org.jivesoftware.smack;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.test.SmackTestCase;
/** /**
* Tests sending messages to other clients. * Tests sending messages to other clients.
@ -82,7 +82,7 @@ public class MessageTest extends SmackTestCase {
// Create message with a body of 4K characters // 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);
StringBuffer sb = new StringBuffer(5000); StringBuilder sb = new StringBuilder(5000);
for (int i=0; i<=4000; i++) { for (int i=0; i<=4000; i++) {
sb.append("X"); sb.append("X");
} }

View file

@ -89,8 +89,10 @@ public class RosterTest extends SmackTestCase {
// Wait until the server confirms the new entries // Wait until the server confirms the new entries
long initial = System.currentTimeMillis(); long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && roster.getEntryCount() != 2) { while (System.currentTimeMillis() - initial < 2000 && (
Thread.sleep(50); roster.getPresence(getBareJID(1)) == null ||
roster.getPresence(getBareJID(2)) == null)) {
Thread.sleep(100);
} }
for (RosterEntry entry : roster.getEntries()) { for (RosterEntry entry : roster.getEntries()) {
@ -210,11 +212,25 @@ public class RosterTest extends SmackTestCase {
roster.createEntry(getBareJID(1), "gato11", null); roster.createEntry(getBareJID(1), "gato11", null);
roster.createEntry(getBareJID(2), "gato12", null); roster.createEntry(getBareJID(2), "gato12", null);
// Wait up to 2 seconds to let the server process presence subscriptions
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
roster.getPresence(getBareJID(1)) == null ||
roster.getPresence(getBareJID(2)) == null)) {
Thread.sleep(100);
}
Thread.sleep(200); Thread.sleep(200);
for (RosterEntry entry : roster.getEntries()) { for (RosterEntry entry : roster.getEntries()) {
roster.removeEntry(entry); roster.removeEntry(entry);
Thread.sleep(250); Thread.sleep(100);
}
// Wait up to 2 seconds to receive roster removal notifications
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && roster.getEntryCount() != 0) {
Thread.sleep(100);
} }
assertEquals("Wrong number of entries in connection 0", 0, roster.getEntryCount()); assertEquals("Wrong number of entries in connection 0", 0, roster.getEntryCount());
@ -247,7 +263,12 @@ public class RosterTest extends SmackTestCase {
Roster roster = getConnection(0).getRoster(); Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), null, null); roster.createEntry(getBareJID(1), null, null);
Thread.sleep(200); // Wait up to 2 seconds to let the server process presence subscriptions
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
roster.getPresence(getBareJID(1)) == null) {
Thread.sleep(100);
}
// Change the roster entry name and check if the change was made // Change the roster entry name and check if the change was made
for (RosterEntry entry : roster.getEntries()) { for (RosterEntry entry : roster.getEntries()) {
@ -388,12 +409,18 @@ public class RosterTest extends SmackTestCase {
roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends" }); roster.createEntry(getBareJID(1), "gato11", new String[] { "Friends" });
roster.createEntry(getBareJID(2), "gato12", new String[] { "Friends" }); roster.createEntry(getBareJID(2), "gato12", new String[] { "Friends" });
Thread.sleep(200); // Wait up to 2 seconds to let the server process presence subscriptions
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && (
roster.getPresence(getBareJID(1)) == null ||
roster.getPresence(getBareJID(2)) == null)) {
Thread.sleep(100);
}
roster.getGroup("Friends").setName("Amigos"); roster.getGroup("Friends").setName("Amigos");
// Wait up to 2 seconds // Wait up to 2 seconds
long initial = System.currentTimeMillis(); initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && while (System.currentTimeMillis() - initial < 2000 &&
(roster.getGroup("Friends") != null)) { (roster.getGroup("Friends") != null)) {
Thread.sleep(100); Thread.sleep(100);
@ -440,77 +467,71 @@ public class RosterTest extends SmackTestCase {
/** /**
* Test presence management. * Test presence management.
*/ */
public void testRosterPresences() { public void testRosterPresences() throws Exception {
try { Thread.sleep(200);
Thread.sleep(200);
Presence presence; Presence presence;
// Create another connection for the same user of connection 1 // Create another connection for the same user of connection 1
XMPPConnection conn4 = new XMPPConnection(getServiceName()); XMPPConnection conn4 = new XMPPConnection(getServiceName());
conn4.login(getUsername(1), getUsername(1), "Home"); conn4.login(getUsername(1), getUsername(1), "Home");
// Add a new roster entry // Add a new roster entry
Roster roster = getConnection(0).getRoster(); Roster roster = getConnection(0).getRoster();
roster.createEntry(getBareJID(1), "gato11", null); roster.createEntry(getBareJID(1), "gato11", null);
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(roster.getPresence(getBareJID(1)) == null)) {
Thread.sleep(100);
}
// Check that a presence is returned for a user
presence = roster.getPresence(getBareJID(1));
assertNotNull("Returned a null Presence for an existing user", presence);
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getUsername(1) + "@" + conn4.getServiceName() + "/Home");
assertEquals(
"Returned the wrong Presence",
StringUtils.parseResource(presence.getFrom()),
"Home");
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getFullJID(1));
assertEquals(
"Returned the wrong Presence",
StringUtils.parseResource(presence.getFrom()),
"Smack");
// Check that the no presence is returned for a non-existent user+resource
presence = roster.getPresenceResource("noname@" + getServiceName() + "/Smack");
assertNull("Returned a Presence for a non-existing user", presence);
// Check that the returned presences are correct
Iterator presences = roster.getPresences(getBareJID(1));
int count = 0;
while (presences.hasNext()) {
count++;
presences.next();
}
assertEquals("Wrong number of returned presences", count, 2);
// Close the connection so one presence must go
conn4.close();
// Check that the returned presences are correct
presences = roster.getPresences(getBareJID(1));
count = 0;
while (presences.hasNext()) {
count++;
presences.next();
}
assertEquals("Wrong number of returned presences", count, 1);
Thread.sleep(200);
cleanUpRoster();
// Wait up to 2 seconds
long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
(roster.getPresence(getBareJID(1)) == null)) {
Thread.sleep(100);
} }
catch (Exception e) {
fail(e.getMessage()); // Check that a presence is returned for a user
presence = roster.getPresence(getBareJID(1));
assertNotNull("Returned a null Presence for an existing user", presence);
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getUsername(1) + "@" + conn4.getServiceName() + "/Home");
assertEquals(
"Returned the wrong Presence",
StringUtils.parseResource(presence.getFrom()),
"Home");
// Check that the right presence is returned for a user+resource
presence = roster.getPresenceResource(getFullJID(1));
assertEquals(
"Returned the wrong Presence",
StringUtils.parseResource(presence.getFrom()),
"Smack");
// Check that the no presence is returned for a non-existent user+resource
presence = roster.getPresenceResource("noname@" + getServiceName() + "/Smack");
assertNull("Returned a Presence for a non-existing user", presence);
// Check that the returned presences are correct
Iterator presences = roster.getPresences(getBareJID(1));
int count = 0;
while (presences.hasNext()) {
count++;
presences.next();
} }
assertEquals("Wrong number of returned presences", count, 2);
// Close the connection so one presence must go
conn4.close();
// Check that the returned presences are correct
presences = roster.getPresences(getBareJID(1));
count = 0;
while (presences.hasNext()) {
count++;
presences.next();
}
assertEquals("Wrong number of returned presences", count, 1);
Thread.sleep(200);
cleanUpRoster();
} }
/** /**
@ -586,34 +607,17 @@ public class RosterTest extends SmackTestCase {
fail(e.getMessage()); fail(e.getMessage());
} }
} }
// Wait up to 2 seconds to receive roster removal notifications // Wait up to 6 seconds to receive roster removal notifications
long initial = System.currentTimeMillis(); long initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 && while (System.currentTimeMillis() - initial < 6000 && (
getConnection(0).getRoster().getEntryCount() != 0) { getConnection(0).getRoster().getEntryCount() != 0 ||
getConnection(1).getRoster().getEntryCount() != 0 ||
getConnection(2).getRoster().getEntryCount() != 0)) {
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (InterruptedException e) {} } catch (InterruptedException e) {}
} }
// Wait up to 2 seconds to receive roster removal notifications
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
getConnection(1).getRoster().getEntryCount() != 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
// Wait up to 2 seconds to receive roster removal notifications
initial = System.currentTimeMillis();
while (System.currentTimeMillis() - initial < 2000 &&
getConnection(2).getRoster().getEntryCount() != 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
assertEquals( assertEquals(
"Wrong number of entries in connection 0", "Wrong number of entries in connection 0",
0, 0,

View file

@ -51,11 +51,14 @@
*/ */
package org.jivesoftware.smackx.muc; package org.jivesoftware.smackx.muc;
import java.util.*; import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.test.SmackTestCase; import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.*; import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/** /**
* Tests creating new MUC rooms. * Tests creating new MUC rooms.
@ -90,15 +93,15 @@ public class MultiUserChatCreationTest extends SmackTestCase {
// Create a new form to submit based on the original form // Create a new form to submit based on the original form
Form submitForm = form.createAnswerForm(); Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit // Add default answers to the form to submit
for (Iterator fields = form.getFields(); fields.hasNext();) { for (Iterator<FormField> fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next(); FormField field = fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType()) if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) { && field.getVariable() != null) {
// Sets the default value as the answer // Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable()); submitForm.setDefaultAnswer(field.getVariable());
} }
} }
List owners = new ArrayList(); List<String> owners = new ArrayList<String>();
owners.add(getBareJID(0)); owners.add(getBareJID(0));
submitForm.setAnswer("muc#roomconfig_roomowners", owners); submitForm.setAnswer("muc#roomconfig_roomowners", owners);