public abstract class XMPPConnection
extends java.lang.Object
XMPPTCPConnection
or XMPPBOSHConnection
). 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. XMPPConnection con = new XMPPTCPConnection("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 = ChatManager.getInstanceFor(con).createChat("[email protected]", 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 XMPPConnection gets disconnected abruptly and automatic reconnection is enabled (
ConnectionConfiguration.isReconnectionAllowed()
, the default), 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.
Modifier and Type | Class and Description |
---|---|
static class |
XMPPConnection.FromMode |
protected static class |
XMPPConnection.InterceptorWrapper
A wrapper class to associate a packet filter with an interceptor.
|
protected static class |
XMPPConnection.ListenerWrapper
A wrapper class to associate a packet filter with a listener.
|
Modifier and Type | Field and Description |
---|---|
protected boolean |
authenticated
Flag that indicates if the user is currently authenticated with the server.
|
protected java.util.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 ConnectionConfiguration |
config
Holds the initial configuration used while creating the connection.
|
protected int |
connectionCounterValue
A number to uniquely identify connections that are created.
|
protected java.util.Collection<ConnectionListener> |
connectionListeners
A collection of ConnectionListeners which listen for connection closing
and reconnection events.
|
protected SmackDebugger |
debugger
The SmackDebugger allows to log and debug XML traffic.
|
protected java.util.Map<PacketInterceptor,XMPPConnection.InterceptorWrapper> |
interceptors
List of PacketInterceptors that will be notified when a new packet is about to be
sent to the server.
|
protected java.io.Reader |
reader
The Reader which is used for the debugger.
|
protected java.util.Map<PacketListener,XMPPConnection.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 java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> |
sendListeners
List of PacketListeners that will be notified when a new packet was sent.
|
protected boolean |
wasAuthenticated
Flag that indicates if the user was authenticated with the server when the connection
to the server was closed (abruptly or not).
|
protected java.io.Writer |
writer
The Writer which is used for the debugger.
|
Modifier | Constructor and Description |
---|---|
protected |
XMPPConnection(ConnectionConfiguration configuration)
Create a new XMPPConnection to a XMPP server.
|
Modifier and Type | Method and Description |
---|---|
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.
|
protected java.lang.String |
bindResourceAndEstablishSession(java.lang.String resource) |
protected void |
callConnectionAuthenticatedListener() |
protected void |
callConnectionClosedOnErrorListener(java.lang.Exception e) |
protected void |
callConnectionConnectedListener() |
void |
connect()
Establishes a connection to the XMPP server and performs an automatic login
only if the previous connection state was logged (authenticated).
|
protected abstract void |
connectInternal()
Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
way of XMPP connection establishment.
|
PacketCollector |
createPacketCollector(PacketFilter packetFilter)
Creates a new packet collector for this connection.
|
PacketCollector |
createPacketCollectorAndSend(IQ packet)
Creates a new packet collector collecting packets that are replies to
packet . |
void |
disconnect()
Closes the connection by setting presence to unavailable then closing the connection to
the XMPP server.
|
void |
disconnect(Presence unavailablePresence)
Closes the connection.
|
protected void |
finalize() |
protected ConnectionConfiguration |
getConfiguration()
Returns the configuration used to connect to the server.
|
int |
getConnectionCounter()
Get the connection counter of this XMPPConnection instance.
|
protected static java.util.Collection<ConnectionCreationListener> |
getConnectionCreationListeners()
Get the collection of listeners that are interested in connection creation events.
|
abstract java.lang.String |
getConnectionID()
Returns the connection ID for this connection, which is the value set by the server
when opening a XMPP stream.
|
protected java.util.Collection<ConnectionListener> |
getConnectionListeners()
Get the collection of listeners that are interested in connection events.
|
XMPPConnection.FromMode |
getFromMode()
Get the currently active FromMode.
|
java.lang.String |
getHost()
Returns the host name of the server where the XMPP server is running.
|
protected java.util.Collection<PacketCollector> |
getPacketCollectors()
Get the collection of all packet collectors for this connection.
|
protected java.util.Map<PacketInterceptor,XMPPConnection.InterceptorWrapper> |
getPacketInterceptors()
Get a map of all packet interceptors for sending packets of this connection.
|
protected java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> |
getPacketListeners()
Get a map of all packet listeners for received packets of this connection.
|
long |
getPacketReplyTimeout()
Returns the current value of the reply timeout in milliseconds for request for this
XMPPConnection instance.
|
protected java.util.Map<PacketListener,XMPPConnection.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.
|
protected java.io.Reader |
getReader() |
Roster |
getRoster()
Returns the roster for the user.
|
protected SASLAuthentication |
getSASLAuthentication()
Returns the SASLAuthentication manager that is responsible for authenticating with
the server.
|
java.lang.String |
getServiceCapsNode()
Retrieve the servers Entity Caps node
XMPPConnection holds this information in order to avoid a dependency to
smackx where EntityCapsManager lives from smack.
|
java.lang.String |
getServiceName()
Returns the name of the service provided by the XMPP server for this connection.
|
abstract java.lang.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 java.io.Writer |
getWriter() |
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.
|
boolean |
isRosterVersioningSupported()
Returns true if the server supports roster versioning as defined in XEP-0237.
|
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(java.lang.String username,
java.lang.String password)
Logs in to the server using the strongest authentication mode supported by
the server, then sets presence to available.
|
abstract void |
login(java.lang.String username,
java.lang.String password,
java.lang.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.
|
protected void |
maybeResolveDns() |
protected void |
processPacket(Packet packet)
Processes a packet after it's been fully parsed by looping through the installed
packet collectors and listeners and letting them examine the packet to see if
they are a match with the filter.
|
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.
|
protected java.util.concurrent.ScheduledFuture<?> |
schedule(java.lang.Runnable command,
long delay,
java.util.concurrent.TimeUnit unit) |
void |
sendPacket(Packet packet)
Sends the specified packet to the server.
|
protected abstract void |
sendPacketInternal(Packet packet) |
protected void |
serverRequiresBinding()
Notification message saying that the server requires the client to bind a
resource to the stream.
|
protected void |
serverSupportsAccountCreation() |
protected void |
serverSupportsSession()
Notification message saying that the server supports sessions.
|
protected void |
setConnectionException(java.io.IOException exception) |
void |
setFromMode(XMPPConnection.FromMode fromMode)
Set the FromMode for this connection instance.
|
protected void |
setLoginInfo(java.lang.String username,
java.lang.String password,
java.lang.String resource) |
void |
setPacketReplyTimeout(long timeout)
Set the packet reply timeout in milliseconds.
|
protected void |
setRosterVersioningSupported()
Indicates that the server supports roster versioning as defined in XEP-0237.
|
protected void |
setServiceCapsNode(java.lang.String node)
Set the servers Entity Caps node
XMPPConnection holds this information in order to avoid a dependency to
smackx where EntityCapsManager lives from smack.
|
protected void |
setServiceName(java.lang.String serviceName) |
protected void |
setWasAuthenticated(boolean authenticated)
Sets whether the connection has already logged in the server.
|
protected abstract void |
shutdown()
Shuts the current connection down.
|
protected void |
throwConnectionExceptionOrNoResponse() |
protected final java.util.Collection<ConnectionListener> connectionListeners
protected final java.util.Collection<PacketCollector> collectors
protected final java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> recvListeners
protected final java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> sendListeners
protected final java.util.Map<PacketInterceptor,XMPPConnection.InterceptorWrapper> interceptors
protected SmackDebugger debugger
protected java.io.Reader reader
protected java.io.Writer writer
protected SASLAuthentication saslAuthentication
protected final int connectionCounterValue
protected final ConnectionConfiguration config
protected XMPPInputOutputStream compressionHandler
protected boolean authenticated
protected boolean wasAuthenticated
protected XMPPConnection(ConnectionConfiguration configuration)
configuration
- The configuration which is used to establish the connection.protected ConnectionConfiguration getConfiguration()
public java.lang.String getServiceName()
public java.lang.String getHost()
public int getPort()
public abstract java.lang.String getUser()
public abstract java.lang.String getConnectionID()
public abstract boolean isConnected()
public abstract boolean isAuthenticated()
public abstract boolean isAnonymous()
public abstract boolean isSecureConnection()
protected abstract void sendPacketInternal(Packet packet) throws SmackException.NotConnectedException
public abstract boolean isUsingCompression()
public void connect() throws SmackException, java.io.IOException, XMPPException
Listeners will be preserved from a previous connection.
XMPPException
- if an error occurs on the XMPP protocol level.SmackException
- if an error occurs somewhere else besides XMPP protocol level.java.io.IOException
SmackException.ConnectionException
- with detailed information about the failed connection.protected abstract void connectInternal() throws SmackException, java.io.IOException, XMPPException
serverRequiresBinding()
and such).
Also implementations are required to perform an automatic login if the previous connection state was logged (authenticated).
SmackException
java.io.IOException
XMPPException
public void login(java.lang.String username, java.lang.String password) throws XMPPException, SmackException, javax.security.sasl.SaslException, java.io.IOException
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
.
username
- the username.password
- the password or null if using a CallbackHandler.XMPPException
- if an error occurs on the XMPP protocol level.SmackException
- if an error occurs somehwere else besides XMPP protocol level.java.io.IOException
javax.security.sasl.SaslException
public abstract void login(java.lang.String username, java.lang.String password, java.lang.String resource) throws XMPPException, SmackException, javax.security.sasl.SaslException, java.io.IOException
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
.
username
- the username.password
- the password or null if using a CallbackHandler.resource
- the resource.XMPPException
- if an error occurs on the XMPP protocol level.SmackException
- if an error occurs somehwere else besides XMPP protocol level.java.io.IOException
javax.security.sasl.SaslException
public abstract void loginAnonymously() throws XMPPException, SmackException, javax.security.sasl.SaslException, java.io.IOException
XMPPException
- if an error occurs on the XMPP protocol level.SmackException
- if an error occurs somehwere else besides XMPP protocol level.java.io.IOException
javax.security.sasl.SaslException
protected void serverRequiresBinding()
protected void serverSupportsSession()
protected java.lang.String bindResourceAndEstablishSession(java.lang.String resource) throws XMPPException.XMPPErrorException, SmackException.ResourceBindingNotOfferedException, SmackException.NoResponseException, SmackException.NotConnectedException
protected void setConnectionException(java.io.IOException exception)
protected void throwConnectionExceptionOrNoResponse() throws java.io.IOException, SmackException.NoResponseException
java.io.IOException
SmackException.NoResponseException
protected java.io.Reader getReader()
protected java.io.Writer getWriter()
protected void setServiceName(java.lang.String serviceName)
protected void setLoginInfo(java.lang.String username, java.lang.String password, java.lang.String resource)
protected void serverSupportsAccountCreation()
protected void maybeResolveDns() throws java.lang.Exception
java.lang.Exception
public void sendPacket(Packet packet) throws SmackException.NotConnectedException
packet
- the packet to send.SmackException.NotConnectedException
public Roster getRoster()
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
RosterListener
s will throw an IllegalStateException.
java.lang.IllegalStateException
- if the connection is anonymousprotected SASLAuthentication getSASLAuthentication()
public void disconnect() throws SmackException.NotConnectedException
public void disconnect(Presence unavailablePresence) throws SmackException.NotConnectedException
unavailablePresence
- the presence packet to send during shutdown.SmackException.NotConnectedException
protected abstract void shutdown()
public static void addConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
connectionCreationListener
- a listener interested on new connections.public static void removeConnectionCreationListener(ConnectionCreationListener connectionCreationListener)
connectionCreationListener
- a listener interested on new connections.protected static java.util.Collection<ConnectionCreationListener> getConnectionCreationListeners()
public void addConnectionListener(ConnectionListener connectionListener)
connectionListener
- a connection listener.public void removeConnectionListener(ConnectionListener connectionListener)
connectionListener
- a connection listener.protected java.util.Collection<ConnectionListener> getConnectionListeners()
public PacketCollector createPacketCollectorAndSend(IQ packet) throws SmackException.NotConnectedException
packet
.
Does also send packet
. The packet filter for the collector is an
IQReplyFilter
, guaranteeing that packet id and JID in the 'from' address have
expected values.packet
- the packet to filter responses fromSmackException.NotConnectedException
public PacketCollector createPacketCollector(PacketFilter packetFilter)
PacketListener
when you need to wait for
a specific result.packetFilter
- the packet filter to use.protected void removePacketCollector(PacketCollector collector)
collector
- a packet collectors which was created for this connection.protected java.util.Collection<PacketCollector> getPacketCollectors()
public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter)
NOTE: If you want get a similar callback for outgoing packets, see addPacketInterceptor(PacketInterceptor, PacketFilter)
.
packetListener
- the packet listener to notify of new received packets.packetFilter
- the packet filter to use.public void removePacketListener(PacketListener packetListener)
packetListener
- the packet listener to remove.protected java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> getPacketListeners()
public void addPacketSendingListener(PacketListener packetListener, PacketFilter packetFilter)
packetListener
- the packet listener to notify of sent packets.packetFilter
- the packet filter to use.public void removePacketSendingListener(PacketListener packetListener)
packetListener
- the packet listener to remove.protected java.util.Map<PacketListener,XMPPConnection.ListenerWrapper> getPacketSendingListeners()
public void addPacketInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter)
NOTE: For a similar functionality on incoming packets, see addPacketListener(PacketListener, PacketFilter)
.
packetInterceptor
- the packet interceptor to notify of packets about to be sent.packetFilter
- the packet filter to use.public void removePacketInterceptor(PacketInterceptor packetInterceptor)
packetInterceptor
- the packet interceptor to remove.protected java.util.Map<PacketInterceptor,XMPPConnection.InterceptorWrapper> getPacketInterceptors()
protected void initDebugger()
debugger
. You can specify a customized SmackDebugger
by setup the system property smack.debuggerClass
to the implementation.java.lang.IllegalStateException
- if the reader or writer isn't yet initialized.java.lang.IllegalArgumentException
- if the SmackDebugger can't be loaded.protected void setServiceCapsNode(java.lang.String node)
node
- public java.lang.String getServiceCapsNode()
public boolean isRosterVersioningSupported()
protected void setRosterVersioningSupported()
public long getPacketReplyTimeout()
public void setPacketReplyTimeout(long timeout)
SmackException.NoResponseException
if no reply to a request was received within the timeout period.timeout
- the packet reply timeout in millisecondsprotected void processPacket(Packet packet)
packet
- the packet to process.protected void setWasAuthenticated(boolean authenticated)
wasAuthenticated
flag is never reset once it has ever been set.authenticated
- true if the connection has already been authenticated.protected void callConnectionConnectedListener()
protected void callConnectionAuthenticatedListener()
protected void callConnectionClosedOnErrorListener(java.lang.Exception e)
protected java.util.concurrent.ScheduledFuture<?> schedule(java.lang.Runnable command, long delay, java.util.concurrent.TimeUnit unit)
public int getConnectionCounter()
public void setFromMode(XMPPConnection.FromMode fromMode)
fromMode
- public XMPPConnection.FromMode getFromMode()
XMPPConnection.FromMode
protected void finalize() throws java.lang.Throwable
finalize
in class java.lang.Object
java.lang.Throwable