Smack

org.jivesoftware.smack
Class Connection

java.lang.Object
  extended by org.jivesoftware.smack.Connection
Direct Known Subclasses:
XMPPConnection

public abstract class Connection
extends Object

The abstract Connection class provides an interface for connections to a XMPP server and implements shared methods which are used by the different types of connections (e.g. XMPPConnection or BoshConnection). To create a connection to a XMPP server a simple usage of this API might look like the following:

 // Create a connection to the igniterealtime.org XMPP server.
 Connection con = new XMPPConnection("igniterealtime.org");
 // Connect to the server
 con.connect();
 // Most servers require you to login before performing other tasks.
 con.login("jsmith", "mypass");
 // Start a new conversation with John Doe and send him a message.
 Chat chat = connection.getChatManager().createChat("jdoe@igniterealtime.org", new MessageListener() {
 

public void processMessage(Chat chat, Message message) { // Print out any messages we get back to standard out. System.out.println("Received message: " + message); } }); chat.sendMessage("Howdy!"); // Disconnect from the server con.disconnect();

Connections can be reused between connections. This means that an Connection may be connected, disconnected and then connected again. Listeners of the Connection will be retained accross connections.

If a connected Connection gets disconnected abruptly then it will try to reconnect again. To stop the reconnection process, use disconnect(). Once stopped you can use connect() to manually connect to the server.

Author:
Matt Tucker, Guenther Niess
See Also:
XMPPConnection

Nested Class Summary
protected static class Connection.InterceptorWrapper
          A wrapper class to associate a packet filter with an interceptor.
protected static class Connection.ListenerWrapper
          A wrapper class to associate a packet filter with a listener.
 
Field Summary
protected  Collection<PacketCollector> collectors
          A collection of PacketCollectors which collects packets for a specified filter and perform blocking and polling operations on the result queue.
protected  XMPPInputOutputStream compressionHandler
           
protected static List<XMPPInputOutputStream> compressionHandlers
           
protected  ConnectionConfiguration config
          Holds the initial configuration used while creating the connection.
protected  int connectionCounterValue
          A number to uniquely identify connections that are created.
protected  Collection<ConnectionListener> connectionListeners
          A collection of ConnectionListeners which listen for connection closing and reconnection events.
static boolean DEBUG_ENABLED
          Value that indicates whether debugging is enabled.
protected  SmackDebugger debugger
          The SmackDebugger allows to log and debug XML traffic.
protected  Map<PacketInterceptor,Connection.InterceptorWrapper> interceptors
          List of PacketInterceptors that will be notified when a new packet is about to be sent to the server.
protected  Reader reader
          The Reader which is used for the debugger.
protected  Map<PacketListener,Connection.ListenerWrapper> recvListeners
          List of PacketListeners that will be notified when a new packet was received.
protected  SASLAuthentication saslAuthentication
          The SASLAuthentication manager that is responsible for authenticating with the server.
protected  Map<PacketListener,Connection.ListenerWrapper> sendListeners
          List of PacketListeners that will be notified when a new packet was sent.
protected  Writer writer
          The Writer which is used for the debugger.
 
Constructor Summary
protected Connection(ConnectionConfiguration configuration)
          Create a new Connection to a XMPP server.
 
Method Summary
static void addConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
          Adds a new listener that will be notified when new Connections are created.
 void addConnectionListener(ConnectionListener connectionListener)
          Adds a connection listener to this connection that will be notified when the connection closes or fails.
 void addPacketInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter)
          Registers a packet interceptor with this connection.
 void addPacketListener(PacketListener packetListener, PacketFilter packetFilter)
          Registers a packet listener with this connection.
 void addPacketSendingListener(PacketListener packetListener, PacketFilter packetFilter)
          Registers a packet listener with this connection.
abstract  void connect()
          Establishes a connection to the XMPP server and performs an automatic login only if the previous connection state was logged (authenticated).
 PacketCollector createPacketCollector(PacketFilter packetFilter)
          Creates a new packet collector for this connection.
 void disconnect()
          Closes the connection by setting presence to unavailable then closing the connection to the XMPP server.
abstract  void disconnect(Presence unavailablePresence)
          Closes the connection.
protected  void firePacketInterceptors(Packet packet)
          Process interceptors.
protected  void firePacketSendingListeners(Packet packet)
          Process all packet listeners for sending packets.
 AccountManager getAccountManager()
          Returns an account manager instance for this connection.
 ChatManager getChatManager()
          Returns a chat manager instance for this connection.
protected  ConnectionConfiguration getConfiguration()
          Returns the configuration used to connect to the server.
protected static Collection<ConnectionCreationListener> getConnectionCreationListeners()
          Get the collection of listeners that are interested in connection creation events.
abstract  String getConnectionID()
          Returns the connection ID for this connection, which is the value set by the server when opening a XMPP stream.
protected  Collection<ConnectionListener> getConnectionListeners()
          Get the collection of listeners that are interested in connection events.
 String getHost()
          Returns the host name of the server where the XMPP server is running.
protected  Collection<PacketCollector> getPacketCollectors()
          Get the collection of all packet collectors for this connection.
protected  Map<PacketInterceptor,Connection.InterceptorWrapper> getPacketInterceptors()
          Get a map of all packet interceptors for sending packets of this connection.
protected  Map<PacketListener,Connection.ListenerWrapper> getPacketListeners()
          Get a map of all packet listeners for received packets of this connection.
protected  Map<PacketListener,Connection.ListenerWrapper> getPacketSendingListeners()
          Get a map of all packet listeners for sending packets of this connection.
 int getPort()
          Returns the port number of the XMPP server for this connection.
abstract  Roster getRoster()
          Returns the roster for the user.
 SASLAuthentication getSASLAuthentication()
          Returns the SASLAuthentication manager that is responsible for authenticating with the server.
 String getServiceCapsNode()
          Retrieve the servers Entity Caps node Connection holds this information in order to avoid a dependency to smackx where EntityCapsManager lives from smack.
 String getServiceName()
          Returns the name of the service provided by the XMPP server for this connection.
abstract  String getUser()
          Returns the full XMPP address of the user that is logged in to the connection or null if not logged in yet.
protected  void initDebugger()
          Initialize the debugger.
abstract  boolean isAnonymous()
          Returns true if currently authenticated anonymously.
abstract  boolean isAuthenticated()
          Returns true if currently authenticated by successfully calling the login method.
abstract  boolean isConnected()
          Returns true if currently connected to the XMPP server.
protected  boolean isReconnectionAllowed()
          Returns if the reconnection mechanism is allowed to be used.
abstract  boolean isSecureConnection()
          Returns true if the connection to the server has successfully negotiated encryption.
abstract  boolean isUsingCompression()
          Returns true if network traffic is being compressed.
 void login(String username, String password)
          Logs in to the server using the strongest authentication mode supported by the server, then sets presence to available.
abstract  void login(String username, String password, String resource)
          Logs in to the server using the strongest authentication mode supported by the server, then sets presence to available.
abstract  void loginAnonymously()
          Logs in to the server anonymously.
static void removeConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
          Removes a listener that was interested in connection creation events.
 void removeConnectionListener(ConnectionListener connectionListener)
          Removes a connection listener from this connection.
protected  void removePacketCollector(PacketCollector collector)
          Remove a packet collector of this connection.
 void removePacketInterceptor(PacketInterceptor packetInterceptor)
          Removes a packet interceptor.
 void removePacketListener(PacketListener packetListener)
          Removes a packet listener for received packets from this connection.
 void removePacketSendingListener(PacketListener packetListener)
          Removes a packet listener for sending packets from this connection.
abstract  void sendPacket(Packet packet)
          Sends the specified packet to the server.
protected  void setServiceCapsNode(String node)
          Set the servers Entity Caps node Connection holds this information in order to avoid a dependency to smackx where EntityCapsManager lives from smack.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

compressionHandlers

protected static final List<XMPPInputOutputStream> compressionHandlers

DEBUG_ENABLED

public static boolean DEBUG_ENABLED
Value that indicates whether debugging is enabled. When enabled, a debug window will apear for each new connection that will contain the following information:

Debugging can be enabled by setting this field to true, or by setting the Java system property smack.debugEnabled to true. The system property can be set on the command line such as "java SomeApp -Dsmack.debugEnabled=true".


connectionListeners

protected final Collection<ConnectionListener> connectionListeners
A collection of ConnectionListeners which listen for connection closing and reconnection events.


collectors

protected final Collection<PacketCollector> collectors
A collection of PacketCollectors which collects packets for a specified filter and perform blocking and polling operations on the result queue.


recvListeners

protected final Map<PacketListener,Connection.ListenerWrapper> recvListeners
List of PacketListeners that will be notified when a new packet was received.


sendListeners

protected final Map<PacketListener,Connection.ListenerWrapper> sendListeners
List of PacketListeners that will be notified when a new packet was sent.


interceptors

protected final Map<PacketInterceptor,Connection.InterceptorWrapper> interceptors
List of PacketInterceptors that will be notified when a new packet is about to be sent to the server. These interceptors may modify the packet before it is being actually sent to the server.


debugger

protected SmackDebugger debugger
The SmackDebugger allows to log and debug XML traffic.


reader

protected Reader reader
The Reader which is used for the debugger.


writer

protected Writer writer
The Writer which is used for the debugger.


saslAuthentication

protected SASLAuthentication saslAuthentication
The SASLAuthentication manager that is responsible for authenticating with the server.


connectionCounterValue

protected final int connectionCounterValue
A number to uniquely identify connections that are created. This is distinct from the connection ID, which is a value sent by the server once a connection is made.


config

protected final ConnectionConfiguration config
Holds the initial configuration used while creating the connection.


compressionHandler

protected XMPPInputOutputStream compressionHandler
Constructor Detail

Connection

protected Connection(ConnectionConfiguration configuration)
Create a new Connection to a XMPP server.

Parameters:
configuration - The configuration which is used to establish the connection.
Method Detail

getConfiguration

protected ConnectionConfiguration getConfiguration()
Returns the configuration used to connect to the server.

Returns:
the configuration used to connect to the server.

getServiceName

public String getServiceName()
Returns the name of the service provided by the XMPP server for this connection. This is also called XMPP domain of the connected server. After authenticating with the server the returned value may be different.

Returns:
the name of the service provided by the XMPP server.

getHost

public String getHost()
Returns the host name of the server where the XMPP server is running. This would be the IP address of the server or a name that may be resolved by a DNS server.

Returns:
the host name of the server where the XMPP server is running.

getPort

public int getPort()
Returns the port number of the XMPP server for this connection. The default port for normal connections is 5222. The default port for SSL connections is 5223.

Returns:
the port number of the XMPP server.

getUser

public abstract String getUser()
Returns the full XMPP address of the user that is logged in to the connection or null if not logged in yet. An XMPP address is in the form username@server/resource.

Returns:
the full XMPP address of the user logged in.

getConnectionID

public abstract String getConnectionID()
Returns the connection ID for this connection, which is the value set by the server when opening a XMPP stream. If the server does not set a connection ID, this value will be null. This value will be null if not connected to the server.

Returns:
the ID of this connection returned from the XMPP server or null if not connected to the server.

isConnected

public abstract boolean isConnected()
Returns true if currently connected to the XMPP server.

Returns:
true if connected.

isAuthenticated

public abstract boolean isAuthenticated()
Returns true if currently authenticated by successfully calling the login method.

Returns:
true if authenticated.

isAnonymous

public abstract boolean isAnonymous()
Returns true if currently authenticated anonymously.

Returns:
true if authenticated anonymously.

isSecureConnection

public abstract boolean isSecureConnection()
Returns true if the connection to the server has successfully negotiated encryption.

Returns:
true if a secure connection to the server.

isReconnectionAllowed

protected boolean isReconnectionAllowed()
Returns if the reconnection mechanism is allowed to be used. By default reconnection is allowed.

Returns:
true if the reconnection mechanism is allowed to be used.

isUsingCompression

public abstract boolean isUsingCompression()
Returns true if network traffic is being compressed. When using stream compression network traffic can be reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network connection. However, the server will need to use more CPU time in order to un/compress network data so under high load the server performance might be affected.

Returns:
true if network traffic is being compressed.

connect

public abstract void connect()
                      throws XMPPException
Establishes a connection to the XMPP server and performs an automatic login only if the previous connection state was logged (authenticated). It basically creates and maintains a connection to the server.

Listeners will be preserved from a previous connection if the reconnection occurs after an abrupt termination.

Throws:
XMPPException - if an error occurs while trying to establish the connection.

login

public void login(String username,
                  String password)
           throws XMPPException
Logs in to the server using the strongest authentication mode supported by the server, then sets presence to available. If the server supports SASL authentication then the user will be authenticated using SASL if not Non-SASL authentication will be tried. If more than five seconds (default timeout) elapses in each step of the authentication process without a response from the server, or if an error occurs, a XMPPException will be thrown.

Before logging in (i.e. authenticate) to the server the connection must be connected. It is possible to log in without sending an initial available presence by using ConnectionConfiguration.setSendPresence(boolean). If this connection is not interested in loading its roster upon login then use ConnectionConfiguration.setRosterLoadedAtLogin(boolean). Finally, if you want to not pass a password and instead use a more advanced mechanism while using SASL then you may be interested in using ConnectionConfiguration.setCallbackHandler(javax.security.auth.callback.CallbackHandler). For more advanced login settings see ConnectionConfiguration.

Parameters:
username - the username.
password - the password or null if using a CallbackHandler.
Throws:
XMPPException - if an error occurs.

login

public abstract void login(String username,
                           String password,
                           String resource)
                    throws XMPPException
Logs in to the server using the strongest authentication mode supported by the server, then sets presence to available. If the server supports SASL authentication then the user will be authenticated using SASL if not Non-SASL authentication will be tried. If more than five seconds (default timeout) elapses in each step of the authentication process without a response from the server, or if an error occurs, a XMPPException will be thrown.

Before logging in (i.e. authenticate) to the server the connection must be connected. It is possible to log in without sending an initial available presence by using ConnectionConfiguration.setSendPresence(boolean). If this connection is not interested in loading its roster upon login then use ConnectionConfiguration.setRosterLoadedAtLogin(boolean). Finally, if you want to not pass a password and instead use a more advanced mechanism while using SASL then you may be interested in using ConnectionConfiguration.setCallbackHandler(javax.security.auth.callback.CallbackHandler). For more advanced login settings see ConnectionConfiguration.

Parameters:
username - the username.
password - the password or null if using a CallbackHandler.
resource - the resource.
Throws:
XMPPException - if an error occurs.
IllegalStateException - if not connected to the server, or already logged in to the serrver.

loginAnonymously

public abstract void loginAnonymously()
                               throws XMPPException
Logs in to the server anonymously. Very few servers are configured to support anonymous authentication, so it's fairly likely logging in anonymously will fail. If anonymous login does succeed, your XMPP address will likely be in the form "123ABC@server/789XYZ" or "server/123ABC" (where "123ABC" and "789XYZ" is a random value generated by the server).

Throws:
XMPPException - if an error occurs or anonymous logins are not supported by the server.
IllegalStateException - if not connected to the server, or already logged in to the serrver.

sendPacket

public abstract void sendPacket(Packet packet)
Sends the specified packet to the server.

Parameters:
packet - the packet to send.

getAccountManager

public AccountManager getAccountManager()
Returns an account manager instance for this connection.

Returns:
an account manager for this connection.

getChatManager

public ChatManager getChatManager()
Returns a chat manager instance for this connection. The ChatManager manages all incoming and outgoing chats on the current connection.

Returns:
a chat manager instance for this connection.

getRoster

public abstract Roster getRoster()
Returns the roster for the user.

This method will never return null, instead if the user has not yet logged into the server or is logged in anonymously all modifying methods of the returned roster object like Roster.createEntry(String, String, String[]), Roster.removeEntry(RosterEntry) , etc. except adding or removing RosterListeners will throw an IllegalStateException.

Returns:
the user's roster.

getSASLAuthentication

public SASLAuthentication getSASLAuthentication()
Returns the SASLAuthentication manager that is responsible for authenticating with the server.

Returns:
the SASLAuthentication manager that is responsible for authenticating with the server.

disconnect

public void disconnect()
Closes the connection by setting presence to unavailable then closing the connection to the XMPP server. The Connection can still be used for connecting to the server again.

This method cleans up all resources used by the connection. Therefore, the roster, listeners and other stateful objects cannot be re-used by simply calling connect() on this connection again. This is unlike the behavior during unexpected disconnects (and subsequent connections). In that case, all state is preserved to allow for more seamless error recovery.


disconnect

public abstract void disconnect(Presence unavailablePresence)
Closes the connection. A custom unavailable presence is sent to the server, followed by closing the stream. The Connection can still be used for connecting to the server again. A custom unavilable presence is useful for communicating offline presence information such as "On vacation". Typically, just the status text of the presence packet is set with online information, but most XMPP servers will deliver the full presence packet with whatever data is set.

This method cleans up all resources used by the connection. Therefore, the roster, listeners and other stateful objects cannot be re-used by simply calling connect() on this connection again. This is unlike the behavior during unexpected disconnects (and subsequent connections). In that case, all state is preserved to allow for more seamless error recovery.

Parameters:
unavailablePresence - the presence packet to send during shutdown.

addConnectionCreationListener

public static void addConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
Adds a new listener that will be notified when new Connections are created. Note that newly created connections will not be actually connected to the server.

Parameters:
connectionCreationListener - a listener interested on new connections.

removeConnectionCreationListener

public static void removeConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
Removes a listener that was interested in connection creation events.

Parameters:
connectionCreationListener - a listener interested on new connections.

getConnectionCreationListeners

protected static Collection<ConnectionCreationListener> getConnectionCreationListeners()
Get the collection of listeners that are interested in connection creation events.

Returns:
a collection of listeners interested on new connections.

addConnectionListener

public void addConnectionListener(ConnectionListener connectionListener)
Adds a connection listener to this connection that will be notified when the connection closes or fails. The connection needs to already be connected or otherwise an IllegalStateException will be thrown.

Parameters:
connectionListener - a connection listener.

removeConnectionListener

public void removeConnectionListener(ConnectionListener connectionListener)
Removes a connection listener from this connection.

Parameters:
connectionListener - a connection listener.

getConnectionListeners

protected Collection<ConnectionListener> getConnectionListeners()
Get the collection of listeners that are interested in connection events.

Returns:
a collection of listeners interested on connection events.

createPacketCollector

public PacketCollector createPacketCollector(PacketFilter packetFilter)
Creates a new packet collector for this connection. A packet filter determines which packets will be accumulated by the collector. A PacketCollector is more suitable to use than a PacketListener when you need to wait for a specific result.

Parameters:
packetFilter - the packet filter to use.
Returns:
a new packet collector.

removePacketCollector

protected void removePacketCollector(PacketCollector collector)
Remove a packet collector of this connection.

Parameters:
collector - a packet collectors which was created for this connection.

getPacketCollectors

protected Collection<PacketCollector> getPacketCollectors()
Get the collection of all packet collectors for this connection.

Returns:
a collection of packet collectors for this connection.

addPacketListener

public void addPacketListener(PacketListener packetListener,
                              PacketFilter packetFilter)
Registers a packet listener with this connection. A packet filter determines which packets will be delivered to the listener. If the same packet listener is added again with a different filter, only the new filter will be used.

Parameters:
packetListener - the packet listener to notify of new received packets.
packetFilter - the packet filter to use.

removePacketListener

public void removePacketListener(PacketListener packetListener)
Removes a packet listener for received packets from this connection.

Parameters:
packetListener - the packet listener to remove.

getPacketListeners

protected Map<PacketListener,Connection.ListenerWrapper> getPacketListeners()
Get a map of all packet listeners for received packets of this connection.

Returns:
a map of all packet listeners for received packets.

addPacketSendingListener

public void addPacketSendingListener(PacketListener packetListener,
                                     PacketFilter packetFilter)
Registers a packet listener with this connection. The listener will be notified of every packet that this connection sends. A packet filter determines which packets will be delivered to the listener. Note that the thread that writes packets will be used to invoke the listeners. Therefore, each packet listener should complete all operations quickly or use a different thread for processing.

Parameters:
packetListener - the packet listener to notify of sent packets.
packetFilter - the packet filter to use.

removePacketSendingListener

public void removePacketSendingListener(PacketListener packetListener)
Removes a packet listener for sending packets from this connection.

Parameters:
packetListener - the packet listener to remove.

getPacketSendingListeners

protected Map<PacketListener,Connection.ListenerWrapper> getPacketSendingListeners()
Get a map of all packet listeners for sending packets of this connection.

Returns:
a map of all packet listeners for sent packets.

firePacketSendingListeners

protected void firePacketSendingListeners(Packet packet)
Process all packet listeners for sending packets.

Parameters:
packet - the packet to process.

addPacketInterceptor

public void addPacketInterceptor(PacketInterceptor packetInterceptor,
                                 PacketFilter packetFilter)
Registers a packet interceptor with this connection. The interceptor will be invoked every time a packet is about to be sent by this connection. Interceptors may modify the packet to be sent. A packet filter determines which packets will be delivered to the interceptor.

Parameters:
packetInterceptor - the packet interceptor to notify of packets about to be sent.
packetFilter - the packet filter to use.

removePacketInterceptor

public void removePacketInterceptor(PacketInterceptor packetInterceptor)
Removes a packet interceptor.

Parameters:
packetInterceptor - the packet interceptor to remove.

getPacketInterceptors

protected Map<PacketInterceptor,Connection.InterceptorWrapper> getPacketInterceptors()
Get a map of all packet interceptors for sending packets of this connection.

Returns:
a map of all packet interceptors for sending packets.

firePacketInterceptors

protected void firePacketInterceptors(Packet packet)
Process interceptors. Interceptors may modify the packet that is about to be sent. Since the thread that requested to send the packet will invoke all interceptors, it is important that interceptors perform their work as soon as possible so that the thread does not remain blocked for a long period.

Parameters:
packet - the packet that is going to be sent to the server

initDebugger

protected void initDebugger()
Initialize the debugger. You can specify a customized SmackDebugger by setup the system property smack.debuggerClass to the implementation.

Throws:
IllegalStateException - if the reader or writer isn't yet initialized.
IllegalArgumentException - if the SmackDebugger can't be loaded.

setServiceCapsNode

protected void setServiceCapsNode(String node)
Set the servers Entity Caps node Connection holds this information in order to avoid a dependency to smackx where EntityCapsManager lives from smack.

Parameters:
node -

getServiceCapsNode

public String getServiceCapsNode()
Retrieve the servers Entity Caps node Connection holds this information in order to avoid a dependency to smackx where EntityCapsManager lives from smack.

Returns:

Smack

Copyright © 2003-2007 Jive Software.