/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2009 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; import org.jivesoftware.smack.compression.JzlibInputOutputStream; import org.jivesoftware.smack.compression.XMPPInputOutputStream; import org.jivesoftware.smack.compression.Java7ZlibInputOutputStream; import org.jivesoftware.smack.debugger.SmackDebugger; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; /** * 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 {@link #disconnect()}. Once stopped * you can use {@link #connect()} to manually connect to the server. * * @see XMPPConnection * @author Matt Tucker * @author Guenther Niess */ public abstract class Connection { /** * Counter to uniquely identify connections that are created. */ private final static AtomicInteger connectionCounter = new AtomicInteger(0); /** * A set of listeners which will be invoked if a new connection is created. */ private final static Set*
* 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. */ public abstract void connect() 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 * {@link ConnectionConfiguration#setSendPresence(boolean)}. If this connection is * not interested in loading its roster upon login then use * {@link 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 * {@link ConnectionConfiguration#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}. * For more advanced login settings see {@link ConnectionConfiguration}. * * @param username the username. * @param password the password or null if using a CallbackHandler. * @throws XMPPException if an error occurs. */ public void login(String username, String password) throws XMPPException { login(username, password, "Smack"); } /** * 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 * {@link ConnectionConfiguration#setSendPresence(boolean)}. If this connection is * not interested in loading its roster upon login then use * {@link 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 * {@link ConnectionConfiguration#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}. * For more advanced login settings see {@link ConnectionConfiguration}. * * @param username the username. * @param password the password or null if using a CallbackHandler. * @param resource the resource. * @throws XMPPException if an error occurs. * @throws IllegalStateException if not connected to the server, or already logged in * to the serrver. */ public abstract void login(String username, String password, String resource) 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. * @throws IllegalStateException if not connected to the server, or already logged in * to the serrver. */ public abstract void loginAnonymously() throws XMPPException; /** * Sends the specified packet to the server. * * @param packet the packet to send. */ public abstract void sendPacket(Packet packet); /** * Returns an account manager instance for this connection. * * @return an account manager for this connection. */ public AccountManager getAccountManager() { if (accountManager == null) { accountManager = new AccountManager(this); } return accountManager; } /** * Returns a chat manager instance for this connection. The ChatManager manages all incoming and * outgoing chats on the current connection. * * @return a chat manager instance for this connection. */ public synchronized ChatManager getChatManager() { if (this.chatManager == null) { this.chatManager = new ChatManager(this); } return this.chatManager; } /** * 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 {@link Roster#createEntry(String, String, String[])},
* {@link Roster#removeEntry(RosterEntry)} , etc. except adding or removing
* {@link RosterListener}s will throw an IllegalStateException.
*
* @return the user's roster.
*/
public abstract Roster getRoster();
/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
public SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}
/**
* 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. */ public void disconnect() { disconnect(new Presence(Presence.Type.unavailable)); } /** * 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. * * @param unavailablePresence the presence packet to send during shutdown. */ public abstract void disconnect(Presence unavailablePresence); /** * 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. * * @param connectionCreationListener a listener interested on new connections. */ public static void addConnectionCreationListener( ConnectionCreationListener connectionCreationListener) { connectionEstablishedListeners.add(connectionCreationListener); } /** * Removes a listener that was interested in connection creation events. * * @param connectionCreationListener a listener interested on new connections. */ public static void removeConnectionCreationListener( ConnectionCreationListener connectionCreationListener) { connectionEstablishedListeners.remove(connectionCreationListener); } /** * Get the collection of listeners that are interested in connection creation events. * * @return a collection of listeners interested on new connections. */ protected static Collectionsmack.debuggerClass
to the implementation.
*
* @throws IllegalStateException if the reader or writer isn't yet initialized.
* @throws IllegalArgumentException if the SmackDebugger can't be loaded.
*/
protected void initDebugger() {
if (reader == null || writer == null) {
throw new NullPointerException("Reader or writer isn't initialized.");
}
// If debugging is enabled, we open a window and write out all network traffic.
if (config.isDebuggerEnabled()) {
if (debugger == null) {
// Detect the debugger class to use.
String className = null;
// Use try block since we may not have permission to get a system
// property (for example, when an applet).
try {
className = System.getProperty("smack.debuggerClass");
}
catch (Throwable t) {
// Ignore.
}
Class> debuggerClass = null;
if (className != null) {
try {
debuggerClass = Class.forName(className);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (debuggerClass == null) {
try {
debuggerClass =
Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger");
}
catch (Exception ex) {
try {
debuggerClass =
Class.forName("org.jivesoftware.smack.debugger.LiteDebugger");
}
catch (Exception ex2) {
ex2.printStackTrace();
}
}
}
// Create a new debugger instance. If an exception occurs then disable the debugging
// option
try {
Constructor> constructor = debuggerClass
.getConstructor(Connection.class, Writer.class, Reader.class);
debugger = (SmackDebugger) constructor.newInstance(this, writer, reader);
reader = debugger.getReader();
writer = debugger.getWriter();
}
catch (Exception e) {
throw new IllegalArgumentException("Can't initialize the configured debugger!", e);
}
}
else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
}
/**
* Set the servers Entity Caps node
*
* Connection holds this information in order to avoid a dependency to
* smackx where EntityCapsManager lives from smack.
*
* @param node
*/
protected void setServiceCapsNode(String node) {
serviceCapsNode = node;
}
/**
* Retrieve the servers Entity Caps node
*
* Connection holds this information in order to avoid a dependency to
* smackx where EntityCapsManager lives from smack.
*
* @return
*/
public String getServiceCapsNode() {
return serviceCapsNode;
}
/**
* A wrapper class to associate a packet filter with a listener.
*/
protected static class ListenerWrapper {
private PacketListener packetListener;
private PacketFilter packetFilter;
/**
* Create a class which associates a packet filter with a listener.
*
* @param packetListener the packet listener.
* @param packetFilter the associated filter or null if it listen for all packets.
*/
public ListenerWrapper(PacketListener packetListener, PacketFilter packetFilter) {
this.packetListener = packetListener;
this.packetFilter = packetFilter;
}
/**
* Notify and process the packet listener if the filter matches the packet.
*
* @param packet the packet which was sent or received.
*/
public void notifyListener(Packet packet) {
if (packetFilter == null || packetFilter.accept(packet)) {
packetListener.processPacket(packet);
}
}
}
/**
* A wrapper class to associate a packet filter with an interceptor.
*/
protected static class InterceptorWrapper {
private PacketInterceptor packetInterceptor;
private PacketFilter packetFilter;
/**
* Create a class which associates a packet filter with an interceptor.
*
* @param packetInterceptor the interceptor.
* @param packetFilter the associated filter or null if it intercepts all packets.
*/
public InterceptorWrapper(PacketInterceptor packetInterceptor, PacketFilter packetFilter) {
this.packetInterceptor = packetInterceptor;
this.packetFilter = packetFilter;
}
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object instanceof InterceptorWrapper) {
return ((InterceptorWrapper) object).packetInterceptor
.equals(this.packetInterceptor);
}
else if (object instanceof PacketInterceptor) {
return object.equals(this.packetInterceptor);
}
return false;
}
/**
* Notify and process the packet interceptor if the filter matches the packet.
*
* @param packet the packet which will be sent.
*/
public void notifyListener(Packet packet) {
if (packetFilter == null || packetFilter.accept(packet)) {
packetInterceptor.interceptPacket(packet);
}
}
}
}