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

Move getRoster() to XMPPConnection

Also remove the Exceptions from the signature of getRoster().

Extend ConnectionListener with connected() and authenticated()
callbacks, required by Roster to be notified so that the Roster can be
loaded *after* login.
This commit is contained in:
Florian Schmaus 2014-03-14 01:48:33 +01:00
parent 4b56446e40
commit 64e7b8a868
15 changed files with 193 additions and 260 deletions

View file

@ -102,12 +102,6 @@ public class BOSHConnection extends XMPPConnection {
*/ */
private String user = null; private String user = null;
/**
* The roster maybe also called buddy list holds the list of the users contacts.
*/
private Roster roster = null;
/** /**
* Create a HTTP Binding connection to a XMPP server. * Create a HTTP Binding connection to a XMPP server.
* *
@ -202,6 +196,7 @@ public class BOSHConnection extends XMPPConnection {
+ getHost() + ":" + getPort() + "."; + getHost() + ":" + getPort() + ".";
throw new SmackException(errorMessage); throw new SmackException(errorMessage);
} }
callConnectionConnectedListener();
} }
public String getConnectionID() { public String getConnectionID() {
@ -214,42 +209,6 @@ public class BOSHConnection extends XMPPConnection {
} }
} }
public Roster getRoster() throws XMPPException, SmackException {
if (roster == null) {
return null;
}
if (!config.isRosterLoadedAtLogin()) {
roster.reload();
}
// If this is the first time the user has asked for the roster after calling
// login, we want to wait for the server to send back the user's roster.
// This behavior shields API users from having to worry about the fact that
// roster operations are asynchronous, although they'll still have to listen
// for changes to the roster. Note: because of this waiting logic, internal
// Smack code should be wary about calling the getRoster method, and may
// need to access the roster object directly.
if (!roster.rosterInitialized) {
try {
synchronized (roster) {
long waitTime = SmackConfiguration.getDefaultPacketReplyTimeout();
long start = System.currentTimeMillis();
while (!roster.rosterInitialized) {
if (waitTime <= 0) {
break;
}
roster.wait(waitTime);
long now = System.currentTimeMillis();
waitTime -= now - start;
start = now;
}
}
} catch (InterruptedException ie) {
// Ignore.
}
}
return roster;
}
public String getUser() { public String getUser() {
return user; return user;
} }
@ -311,14 +270,6 @@ public class BOSHConnection extends XMPPConnection {
} }
} }
// Create the roster if it is not a reconnection.
if (this.roster == null) {
this.roster = new Roster(this);
}
if (config.isRosterLoadedAtLogin()) {
this.roster.reload();
}
// Set presence to online. // Set presence to online.
if (config.isSendPresence()) { if (config.isSendPresence()) {
sendPacket(new Presence(Presence.Type.available)); sendPacket(new Presence(Presence.Type.available));
@ -337,6 +288,7 @@ public class BOSHConnection extends XMPPConnection {
if (config.isDebuggerEnabled() && debugger != null) { if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user); debugger.userHasLogged(user);
} }
callConnectionAuthenticatedListener();
} }
public void loginAnonymously() throws XMPPException, SmackException, IOException { public void loginAnonymously() throws XMPPException, SmackException, IOException {
@ -361,9 +313,6 @@ public class BOSHConnection extends XMPPConnection {
// Update the serviceName with the one returned by the server // Update the serviceName with the one returned by the server
config.setServiceName(StringUtils.parseServer(response)); config.setServiceName(StringUtils.parseServer(response));
// Anonymous users can't have a roster.
roster = null;
// Set presence to online. // Set presence to online.
if (config.isSendPresence()) { if (config.isSendPresence()) {
sendPacket(new Presence(Presence.Type.available)); sendPacket(new Presence(Presence.Type.available));
@ -380,6 +329,7 @@ public class BOSHConnection extends XMPPConnection {
if (config.isDebuggerEnabled() && debugger != null) { if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user); debugger.userHasLogged(user);
} }
callConnectionAuthenticatedListener();
} }
public void sendPacket(Packet packet) { public void sendPacket(Packet packet) {
@ -431,17 +381,7 @@ public class BOSHConnection extends XMPPConnection {
wasAuthenticated = false; wasAuthenticated = false;
isFirstInitialization = true; isFirstInitialization = true;
// Notify connection listeners of the connection closing if done hasn't already been set. callConnectionClosedListener();
for (ConnectionListener listener : getConnectionListeners()) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
e.printStackTrace();
}
}
} }
/** /**
@ -612,17 +552,7 @@ public class BOSHConnection extends XMPPConnection {
shutdown(new Presence(Presence.Type.unavailable)); shutdown(new Presence(Presence.Type.unavailable));
// 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. callConnectionClosedOnErrorListener(e);
for (ConnectionListener listener : getConnectionListeners()) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
e2.printStackTrace();
}
}
} }

View file

@ -25,25 +25,38 @@ package org.jivesoftware.smack;
* @author Henning Staib * @author Henning Staib
*/ */
public class AbstractConnectionListener implements ConnectionListener { public class AbstractConnectionListener implements ConnectionListener {
@Override
public void connected(XMPPConnection connection) {
// do nothing
}
@Override
public void authenticated(XMPPConnection connection) {
// do nothing
}
@Override
public void connectionClosed() { public void connectionClosed() {
// do nothing // do nothing
} }
@Override
public void connectionClosedOnError(Exception e) { public void connectionClosedOnError(Exception e) {
// do nothing // do nothing
} }
@Override
public void reconnectingIn(int seconds) { public void reconnectingIn(int seconds) {
// do nothing // do nothing
} }
@Override
public void reconnectionFailed(Exception e) { public void reconnectionFailed(Exception e) {
// do nothing // do nothing
} }
@Override
public void reconnectionSuccessful() { public void reconnectionSuccessful() {
// do nothing // do nothing
} }
} }

View file

@ -28,6 +28,18 @@ package org.jivesoftware.smack;
*/ */
public interface ConnectionListener { public interface ConnectionListener {
/**
* TODO
* @param connection
*/
public void connected(XMPPConnection connection);
/**
* TODO
* @param connection
*/
public void authenticated(XMPPConnection connection);
/** /**
* Notification that the connection was closed normally or that the reconnection * Notification that the connection was closed normally or that the reconnection
* process has been aborted. * process has been aborted.

View file

@ -35,7 +35,7 @@ import java.util.logging.Logger;
* *
* @author Francisco Vives * @author Francisco Vives
*/ */
public class ReconnectionManager implements ConnectionListener { public class ReconnectionManager extends AbstractConnectionListener {
private static final Logger LOGGER = Logger.getLogger(ReconnectionManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ReconnectionManager.class.getName());
// Holds the connection to the server // Holds the connection to the server
@ -187,10 +187,12 @@ public class ReconnectionManager implements ConnectionListener {
} }
} }
@Override
public void connectionClosed() { public void connectionClosed() {
done = true; done = true;
} }
@Override
public void connectionClosedOnError(Exception e) { public void connectionClosedOnError(Exception e) {
done = false; done = false;
if (e instanceof StreamErrorException) { if (e instanceof StreamErrorException) {
@ -207,20 +209,4 @@ public class ReconnectionManager implements ConnectionListener {
this.reconnect(); this.reconnect();
} }
} }
public void reconnectingIn(int seconds) {
// ignore
}
public void reconnectionFailed(Exception e) {
// ignore
}
/**
* The connection has successfull gotten connected.
*/
public void reconnectionSuccessful() {
// ignore
}
} }

View file

@ -29,6 +29,8 @@ import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotLoggedInException; import org.jivesoftware.smack.SmackException.NotLoggedInException;
@ -59,6 +61,7 @@ import org.jivesoftware.smack.util.StringUtils;
*/ */
public class Roster { public class Roster {
private static final Logger LOGGER = Logger.getLogger(Roster.class.getName());
/** /**
* 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.
@ -125,7 +128,7 @@ public class Roster {
connection.addPacketListener(presencePacketListener, presenceFilter); connection.addPacketListener(presencePacketListener, presenceFilter);
// Listen for connection events // Listen for connection events
final ConnectionListener connectionListener = new AbstractConnectionListener() { connection.addConnectionListener(new AbstractConnectionListener() {
public void connectionClosed() { public void connectionClosed() {
// Changes the presence available contacts to unavailable // Changes the presence available contacts to unavailable
@ -137,22 +140,34 @@ public class Roster {
setOfflinePresences(); setOfflinePresences();
} }
}; });
// If the connection is already established, call reload
// if not connected add listener after successful login if (connection.isAuthenticated()) {
if(!this.connection.isConnected()) { try {
XMPPConnection.addConnectionCreationListener(new ConnectionCreationListener() { reload();
}
public void connectionCreated(XMPPConnection connection) { catch (NotLoggedInException e) {
if(connection.equals(Roster.this.connection)) { LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
Roster.this.connection.addConnectionListener(connectionListener); }
}
connection.addConnectionListener(new AbstractConnectionListener() {
public void authenticated(XMPPConnection connection) {
// Anonymous users can't have a roster, but it iss possible that a Roster instance is
// retrieved if getRoster() is called *before* connect(). So we have to check here
// again if it's an anonymous connection.
if (connection.isAnonymous())
return;
if (!connection.getConfiguration().isRosterLoadedAtLogin())
return;
try {
Roster.this.reload();
}
catch (NotLoggedInException e) {
LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
return;
} }
} }
}); });
} else {
connection.addConnectionListener(connectionListener);
}
} }
/** /**
@ -189,11 +204,9 @@ public class Roster {
* Reloads the entire roster from the server. This is an asynchronous operation, * Reloads the entire roster from the server. This is an asynchronous operation,
* which means the method will return immediately, and the roster will be * which means the method will return immediately, and the roster will be
* reloaded at a later point when the server responds to the reload request. * reloaded at a later point when the server responds to the reload request.
* * @throws NotLoggedInException If not logged in.
* @throws SmackException If not logged in.
* @throws IllegalStateException if logged in anonymously
*/ */
public void reload() throws XMPPException, SmackException { public void reload() throws NotLoggedInException{
if (!connection.isAuthenticated()) { if (!connection.isAuthenticated()) {
throw new NotLoggedInException(); throw new NotLoggedInException();
} }

View file

@ -224,6 +224,8 @@ public abstract class XMPPConnection {
private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2); private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2);
private Roster roster;
/** /**
* Create an executor to deliver incoming packets to listeners. We'll use a single thread with an unbounded queue. * Create an executor to deliver incoming packets to listeners. We'll use a single thread with an unbounded queue.
*/ */
@ -482,11 +484,53 @@ public abstract class XMPPConnection {
* {@link RosterListener}s will throw an IllegalStateException. * {@link RosterListener}s will throw an IllegalStateException.
* *
* @return the user's roster. * @return the user's roster.
* @throws XMPPException if an error occurs on the XMPP protocol level. * @throws IllegalStateException if the connection is anonymous
* @throws SmackException if an error occurs somehwere else besides XMPP protocol level.
*/ */
public abstract Roster getRoster() throws XMPPException, SmackException; public Roster getRoster() {
if (isAnonymous()) {
throw new IllegalStateException("Anonymous users can't have a roster");
}
// synchronize against login()
synchronized(this) {
if (roster == null) {
roster = new Roster(this);
}
if (!isAuthenticated()) {
return roster;
}
}
// If this is the first time the user has asked for the roster after calling
// login, we want to wait for the server to send back the user's roster. This
// behavior shields API users from having to worry about the fact that roster
// operations are asynchronous, although they'll still have to listen for
// changes to the roster. Note: because of this waiting logic, internal
// Smack code should be wary about calling the getRoster method, and may need to
// access the roster object directly.
// Also only check for rosterInitalized is isRosterLoadedAtLogin is set, otherwise the user
// has to manually call Roster.reload() before he can expect a initialized roster.
if (!roster.rosterInitialized && config.isRosterLoadedAtLogin()) {
try {
synchronized (roster) {
long waitTime = SmackConfiguration.getDefaultPacketReplyTimeout();
long start = System.currentTimeMillis();
while (!roster.rosterInitialized) {
if (waitTime <= 0) {
break;
}
roster.wait(waitTime);
long now = System.currentTimeMillis();
waitTime -= now - start;
start = now;
}
}
}
catch (InterruptedException ie) {
// Ignore.
}
}
return roster;
}
/** /**
* Returns the SASLAuthentication manager that is responsible for authenticating with * Returns the SASLAuthentication manager that is responsible for authenticating with
* the server. * the server.
@ -944,6 +988,44 @@ public abstract class XMPPConnection {
} }
} }
void callConnectionConnectedListener() {
for (ConnectionListener listener : getConnectionListeners()) {
listener.connected(this);
}
}
void callConnectionAuthenticatedListener() {
for (ConnectionListener listener : getConnectionListeners()) {
listener.connected(this);
}
}
void callConnectionClosedListener() {
for (ConnectionListener listener : getConnectionListeners()) {
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
}
void callConnectionClosedOnErrorListener(Exception e) {
for (ConnectionListener listener : getConnectionListeners()) {
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
}
}
}
/** /**
* A wrapper class to associate a packet filter with a listener. * A wrapper class to associate a packet filter with a listener.
*/ */

View file

@ -109,6 +109,14 @@ public class ConsoleDebugger implements SmackDebugger {
}; };
connListener = new ConnectionListener() { connListener = new ConnectionListener() {
public void connected(XMPPConnection connection) {
System.out.println(dateFormatter.format(new Date()) + " XMPPConnection connected ("
+ connection.hashCode() + ")");
}
public void authenticated(XMPPConnection connection) {
System.out.println(dateFormatter.format(new Date())
+ " XMPPConnection authenticated (" + connection.hashCode() + ")");
}
public void connectionClosed() { public void connectionClosed() {
System.out.println( System.out.println(
dateFormatter.format(new Date()) + " XMPPConnection closed (" + dateFormatter.format(new Date()) + " XMPPConnection closed (" +

View file

@ -17,6 +17,7 @@
package org.jivesoftware.smackx.debugger; package org.jivesoftware.smackx.debugger;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
@ -199,7 +200,7 @@ public class EnhancedDebugger implements SmackDebugger {
}; };
// Create a thread that will listen for any connection closed event // Create a thread that will listen for any connection closed event
connListener = new ConnectionListener() { connListener = new AbstractConnectionListener() {
public void connectionClosed() { public void connectionClosed() {
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() {
public void run() { public void run() {

View file

@ -27,8 +27,8 @@ import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException.XMPPErrorException; import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
@ -215,26 +215,16 @@ public class FileTransferNegotiator {
} }
private void configureConnection(final XMPPConnection connection) { private void configureConnection(final XMPPConnection connection) {
connection.addConnectionListener(new ConnectionListener() { connection.addConnectionListener(new AbstractConnectionListener() {
@Override
public void connectionClosed() { public void connectionClosed() {
cleanup(connection); cleanup(connection);
} }
@Override
public void connectionClosedOnError(Exception e) { public void connectionClosedOnError(Exception e) {
cleanup(connection); cleanup(connection);
} }
public void reconnectionFailed(Exception e) {
// ignore
}
public void reconnectionSuccessful() {
// ignore
}
public void reconnectingIn(int seconds) {
// ignore
}
}); });
} }

View file

@ -32,9 +32,9 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionCreationListener; import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketInterceptor; import org.jivesoftware.smack.PacketInterceptor;
@ -2338,7 +2338,7 @@ public class MultiUserChat {
* *
* @author Gaston Dombiak * @author Gaston Dombiak
*/ */
private static class InvitationsMonitor implements ConnectionListener { private static class InvitationsMonitor extends AbstractConnectionListener {
// We use a WeakHashMap so that the GC can collect the monitor when the // We use a WeakHashMap so that the GC can collect the monitor when the
// connection is no longer referenced by any object. // connection is no longer referenced by any object.
// Note that when the InvitationsMonitor is used, i.e. when there are InvitationListeners, it will add a // Note that when the InvitationsMonitor is used, i.e. when there are InvitationListeners, it will add a
@ -2447,26 +2447,11 @@ public class MultiUserChat {
} }
} }
@Override
public void connectionClosed() { public void connectionClosed() {
cancel(); cancel();
} }
public void connectionClosedOnError(Exception e) {
// ignore
}
public void reconnectingIn(int seconds) {
// ignore
}
public void reconnectionSuccessful() {
// ignore
}
public void reconnectionFailed(Exception e) {
// ignore
}
/** /**
* Initializes the listeners to detect received room invitations and to detect when the * Initializes the listeners to detect received room invitations and to detect when the
* connection gets closed. As soon as a room invitation is received the invitations * connection gets closed. As soon as a room invitation is received the invitations

View file

@ -17,7 +17,7 @@
package org.jivesoftware.smackx.muc; package org.jivesoftware.smackx.muc;
import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketFilter;
@ -38,7 +38,7 @@ import java.util.concurrent.ConcurrentHashMap;
* *
* @author Larry Kirschner * @author Larry Kirschner
*/ */
class RoomListenerMultiplexor implements ConnectionListener { class RoomListenerMultiplexor extends AbstractConnectionListener {
// We use a WeakHashMap so that the GC can collect the monitor when the // We use a WeakHashMap so that the GC can collect the monitor when the
// connection is no longer referenced by any object. // connection is no longer referenced by any object.
@ -98,26 +98,16 @@ class RoomListenerMultiplexor implements ConnectionListener {
listener.addRoom(address, roomListener); listener.addRoom(address, roomListener);
} }
@Override
public void connectionClosed() { public void connectionClosed() {
cancel(); cancel();
} }
@Override
public void connectionClosedOnError(Exception e) { public void connectionClosedOnError(Exception e) {
cancel(); cancel();
} }
public void reconnectingIn(int seconds) {
// ignore
}
public void reconnectionSuccessful() {
// ignore
}
public void reconnectionFailed(Exception e) {
// ignore
}
/** /**
* Initializes the listeners to detect received room invitations and to detect when the * Initializes the listeners to detect received room invitations and to detect when the
* connection gets closed. As soon as a room invitation is received the invitations * connection gets closed. As soon as a room invitation is received the invitations

View file

@ -26,11 +26,11 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionCreationListener; import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.Manager; import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.XMPPException;
@ -134,7 +134,11 @@ public class PingManager extends Manager {
connection().sendPacket(pong); connection().sendPacket(pong);
} }
}, PING_PACKET_FILTER); }, PING_PACKET_FILTER);
connection.addConnectionListener(new ConnectionListener() { connection.addConnectionListener(new AbstractConnectionListener() {
@Override
public void authenticated(XMPPConnection connection) {
maybeSchedulePingServerTask();
}
@Override @Override
public void connectionClosed() { public void connectionClosed() {
maybeStopPingServerTask(); maybeStopPingServerTask();
@ -143,14 +147,6 @@ public class PingManager extends Manager {
public void connectionClosedOnError(Exception arg0) { public void connectionClosedOnError(Exception arg0) {
maybeStopPingServerTask(); maybeStopPingServerTask();
} }
@Override
public void reconnectionSuccessful() {
maybeSchedulePingServerTask();
}
@Override
public void reconnectingIn(int seconds) {}
@Override
public void reconnectionFailed(Exception e) {}
}); });
maybeSchedulePingServerTask(); maybeSchedulePingServerTask();
} }

View file

@ -23,6 +23,7 @@ import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.SmackException;
@ -625,23 +626,16 @@ public class JingleSession extends JingleNegotiator implements MediaReceivedList
*/ */
private void installConnectionListeners(final XMPPConnection connection) { private void installConnectionListeners(final XMPPConnection connection) {
if (connection != null) { if (connection != null) {
connectionListener = new ConnectionListener() { connectionListener = new AbstractConnectionListener() {
@Override
public void connectionClosed() { public void connectionClosed() {
unregisterInstanceFor(connection); unregisterInstanceFor(connection);
} }
@Override
public void connectionClosedOnError(java.lang.Exception e) { public void connectionClosedOnError(java.lang.Exception e) {
unregisterInstanceFor(connection); unregisterInstanceFor(connection);
} }
public void reconnectingIn(int i) {
}
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception exception) {
}
}; };
connection.addConnectionListener(connectionListener); connection.addConnectionListener(connectionListener);
} }

View file

@ -117,16 +117,7 @@ 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) {
for (ConnectionListener listener : connection.getConnectionListeners()) { connection.callConnectionClosedListener();
try {
listener.connectionClosed();
}
catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
}
}
} }
done = true; done = true;
} }

View file

@ -93,8 +93,6 @@ public class TCPConnection extends XMPPConnection {
PacketWriter packetWriter; PacketWriter packetWriter;
PacketReader packetReader; PacketReader packetReader;
Roster roster = null;
/** /**
* Collection of available stream compression methods offered by the server. * Collection of available stream compression methods offered by the server.
*/ */
@ -266,14 +264,6 @@ public class TCPConnection extends XMPPConnection {
authenticated = true; authenticated = true;
anonymous = false; anonymous = false;
// Create the roster if it is not a reconnection or roster already created by getRoster()
if (this.roster == null) {
this.roster = new Roster(this);
}
if (config.isRosterLoadedAtLogin()) {
this.roster.reload();
}
// Set presence to online. // Set presence to online.
if (config.isSendPresence()) { if (config.isSendPresence()) {
packetWriter.sendPacket(new Presence(Presence.Type.available)); packetWriter.sendPacket(new Presence(Presence.Type.available));
@ -289,6 +279,7 @@ public class TCPConnection extends XMPPConnection {
if (config.isDebuggerEnabled() && debugger != null) { if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user); debugger.userHasLogged(user);
} }
callConnectionAuthenticatedListener();
} }
@Override @Override
@ -332,52 +323,7 @@ public class TCPConnection extends XMPPConnection {
if (config.isDebuggerEnabled() && debugger != null) { if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user); debugger.userHasLogged(user);
} }
} callConnectionAuthenticatedListener();
public Roster getRoster() throws XMPPException, SmackException {
// synchronize against login()
synchronized(this) {
// if connection is authenticated the roster is already set by login()
// or a previous call to getRoster()
if (!isAuthenticated() || isAnonymous()) {
if (roster == null) {
roster = new Roster(this);
}
return roster;
}
}
if (!config.isRosterLoadedAtLogin()) {
roster.reload();
}
// If this is the first time the user has asked for the roster after calling
// login, we want to wait for the server to send back the user's roster. This
// behavior shields API users from having to worry about the fact that roster
// operations are asynchronous, although they'll still have to listen for
// changes to the roster. Note: because of this waiting logic, internal
// Smack code should be wary about calling the getRoster method, and may need to
// access the roster object directly.
if (!roster.rosterInitialized) {
try {
synchronized (roster) {
long waitTime = SmackConfiguration.getDefaultPacketReplyTimeout();
long start = System.currentTimeMillis();
while (!roster.rosterInitialized) {
if (waitTime <= 0) {
break;
}
roster.wait(waitTime);
long now = System.currentTimeMillis();
waitTime -= now - start;
start = now;
}
}
}
catch (InterruptedException ie) {
// Ignore.
}
}
return roster;
} }
public boolean isConnected() { public boolean isConnected() {
@ -919,6 +865,11 @@ public class TCPConnection extends XMPPConnection {
public void connect() throws SmackException, IOException, XMPPException { public void connect() throws SmackException, IOException, XMPPException {
// Establishes the connection, readers and writers // Establishes the connection, readers and writers
connectUsingConfiguration(config); connectUsingConfiguration(config);
// TODO is there a case where connectUsing.. does not throw an exception but connected is
// still false?
if (connected) {
callConnectionConnectedListener();
}
// Automatically makes the login if the user was previously connected successfully // Automatically makes the login if the user was previously connected successfully
// to the server and the connection was terminated abruptly // to the server and the connection was terminated abruptly
if (connected && wasAuthenticated) { if (connected && wasAuthenticated) {
@ -963,16 +914,7 @@ public class TCPConnection extends XMPPConnection {
// Closes the connection temporary. A reconnection is possible // Closes the connection temporary. A reconnection is possible
shutdown(new Presence(Presence.Type.unavailable)); shutdown(new Presence(Presence.Type.unavailable));
// Notify connection listeners of the error. // Notify connection listeners of the error.
for (ConnectionListener listener : getConnectionListeners()) { callConnectionClosedOnErrorListener(e);
try {
listener.connectionClosedOnError(e);
}
catch (Exception e2) {
// Catch and print any exception so we can recover
// from a faulty listener
e2.printStackTrace();
}
}
} }
/** /**