Smack

org.jivesoftware.smack
Class XMPPConnection

java.lang.Object
  extended by org.jivesoftware.smack.XMPPConnection

public class XMPPConnection
extends Object

Creates a connection to a XMPP server. A simple use of this API might look like the following:

 // Create a connection to the igniterealtime.org XMPP server.
 XMPPConnection 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();

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

If a connected XMPPConnection 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

Field Summary
static boolean DEBUG_ENABLED
          Value that indicates whether debugging is enabled.
 
Constructor Summary
XMPPConnection(ConnectionConfiguration config)
          Creates a new XMPP connection using the specified connection configuration.
XMPPConnection(String serviceName)
          Creates a new connection to the specified XMPP server.
 
Method Summary
static void addConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
          Adds a new listener that will be notified when new XMPPConnections are created.
 void addConnectionListener(ConnectionListener connectionListener)
          Adds a connection listener to this connection that will be notified when the connection closes or fails.
 void addPacketListener(PacketListener packetListener, PacketFilter packetFilter)
          Registers a packet listener with this connection.
 void addPacketWriterInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter)
          Registers a packet interceptor with this connection.
 void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter)
          Registers a packet listener with this connection.
 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 stream to the XMPP server.
 void disconnect(Presence unavailablePresence)
          Closes the connection.
 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.
 String getConnectionID()
          Returns the connection ID for this connection, which is the value set by the server when opening a XMPP stream.
 String getHost()
          Returns the host name of the server where the XMPP server is running.
 int getPort()
          Returns the port number of the XMPP server for this connection.
 Roster getRoster()
          Returns the roster for the user logged into the server.
 SASLAuthentication getSASLAuthentication()
          Returns the SASLAuthentication manager that is responsible for authenticating with the server.
 String getServiceName()
          Returns the name of the service provided by the XMPP server for this connection.
 String getUser()
          Returns the full XMPP address of the user that is logged in to the connection or null if not logged in yet.
 boolean isAnonymous()
          Returns true if currently authenticated anonymously.
 boolean isAuthenticated()
          Returns true if currently authenticated by successfully calling the login method.
 boolean isConnected()
          Returns true if currently connected to the XMPP server.
 boolean isSecureConnection()
          Returns true if the connection is a secured one, such as an SSL connection or if TLS was negotiated successfully.
 boolean isUsingCompression()
          Returns true if network traffic is being compressed.
 boolean isUsingTLS()
          Returns true if the connection to the server has successfully negotiated TLS.
 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.
 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.
 void login(String username, String password, String resource, boolean sendPresence)
          Logs in to the server using the strongest authentication mode supported by the server.
 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.
 void removePacketListener(PacketListener packetListener)
          Removes a packet listener from this connection.
 void removePacketWriterInterceptor(PacketInterceptor packetInterceptor)
          Removes a packet interceptor.
 void removePacketWriterListener(PacketListener packetListener)
          Removes a packet listener from this connection.
 void sendPacket(Packet packet)
          Sends the specified packet to the server.
protected  void shutdown(Presence unavailablePresence)
          Closes the connection by setting presence to unavailable then closing the stream to the XMPP server.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

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".

Constructor Detail

XMPPConnection

public XMPPConnection(String serviceName)
Creates a new connection to the specified XMPP server. A DNS SRV lookup will be performed to determine the IP address and port corresponding to the service name; if that lookup fails, it's assumed that server resides at serviceName with the default port of 5222. Encrypted connections (TLS) will be used if available, stream compression is disabled, and standard SASL mechanisms will be used for authentication.

This is the simplest constructor for connecting to an XMPP server. Alternatively, you can get fine-grained control over connection settings using the XMPPConnection(ConnectionConfiguration) constructor.

Note that XMPPConnection constructors do not establish a connection to the server and you must call connect().

Parameters:
serviceName - the name of the XMPP server to connect to; e.g. example.com.

XMPPConnection

public XMPPConnection(ConnectionConfiguration config)
Creates a new XMPP connection using the specified connection configuration.

Manually specifying connection configuration information is suitable for advanced users of the API. In many cases, using the XMPPConnection(String) constructor is a better approach.

Note that XMPPConnection constructors do not establish a connection to the server and you must call connect().

Parameters:
config - the connection configuration.
Method Detail

getConnectionID

public 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.

getServiceName

public String getServiceName()
Returns the name of the service provided by the XMPP server for this connection. 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 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.

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 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.

Parameters:
username - the username.
password - the password.
Throws:
XMPPException - if an error occurs.

login

public 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 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.

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

login

public void login(String username,
                  String password,
                  String resource,
                  boolean sendPresence)
           throws XMPPException
Logs in to the server using the strongest authentication mode supported by the server. If the server supports SASL authentication then the user will be authenticated using SASL if not Non-SASL authentication will be tried. An available presence may optionally be sent. If sendPresence is false, a presence packet must be sent manually later. 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. For compatibility and easiness of use the connection will automatically connect to the server if not already connected.

Parameters:
username - the username.
password - the password.
resource - the resource.
sendPresence - if true an available presence will be sent automatically after login is completed.
Throws:
XMPPException - if an error occurs.
IllegalStateException - if not connected to the server, or already logged in to the serrver.

loginAnonymously

public 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 "server/123ABC" (where "123ABC" 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.

getRoster

public Roster getRoster()
Returns the roster for the user logged into the server. If the user has not yet logged into the server (or if the user is logged in anonymously), this method will return null.

Returns:
the user's roster, or null if the user has not logged in yet.

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.

isConnected

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

Returns:
true if connected.

isSecureConnection

public boolean isSecureConnection()
Returns true if the connection is a secured one, such as an SSL connection or if TLS was negotiated successfully.

Returns:
true if a secure connection to the server.

isAuthenticated

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

Returns:
true if authenticated.

isAnonymous

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

Returns:
true if authenticated anonymously.

shutdown

protected void shutdown(Presence unavailablePresence)
Closes the connection by setting presence to unavailable then closing the stream to the XMPP server. The shutdown logic will be used during a planned disconnection or when dealing with an unexpected disconnection. Unlike disconnect() the connection's packet reader, packet writer, and Roster will not be removed; thus connection's state is kept.

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

disconnect

public void disconnect()
Closes the connection by setting presence to unavailable then closing the stream to the XMPP server. The XMPPConnection 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 void disconnect(Presence unavailablePresence)
Closes the connection. A custom unavailable presence is sent to the server, followed by closing the stream. The XMPPConnection 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.

sendPacket

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

Parameters:
packet - the packet to send.

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 packets.
packetFilter - the packet filter to use.

removePacketListener

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

Parameters:
packetListener - the packet listener to remove.

addPacketWriterListener

public void addPacketWriterListener(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.

removePacketWriterListener

public void removePacketWriterListener(PacketListener packetListener)
Removes a packet listener from this connection.

Parameters:
packetListener - the packet listener to remove.

addPacketWriterInterceptor

public void addPacketWriterInterceptor(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.

removePacketWriterInterceptor

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

Parameters:
packetInterceptor - the packet interceptor to remove.

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.

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

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.

addConnectionCreationListener

public static void addConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
Adds a new listener that will be notified when new XMPPConnections 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.

isUsingTLS

public boolean isUsingTLS()
Returns true if the connection to the server has successfully negotiated TLS. Once TLS has been negotiatied the connection has been secured.

Returns:
true if the connection to the server has successfully negotiated TLS.

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.

getConfiguration

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

Returns:
the configuration used to connect to the server.

isUsingCompression

public 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.

Note: to use stream compression the smackx.jar file has to be present in the classpath.

Returns:
true if network traffic is being compressed.

connect

public 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 socket 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. Two possible errors can occur which will be wrapped by an XMPPException -- UnknownHostException (XMPP error code 504), and IOException (XMPP error code 502). The error codes and wrapped exceptions can be used to present more appropiate error messages to end-users.

Smack

Copyright © 2003-2007 Jive Software.