1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-10 09:39:39 +02:00

SMACK-279: The XMPPConnection extends the new abstract Connection class

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@11613 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Günther Niess 2010-02-09 11:55:56 +00:00 committed by niess
parent 11a41e79ca
commit 127319a821
102 changed files with 1420 additions and 1194 deletions

View file

@ -20,7 +20,6 @@
package org.jivesoftware.smack;
import org.jivesoftware.smack.debugger.SmackDebugger;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
@ -43,102 +42,21 @@ import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Creates a connection to a XMPP server. A simple use of this API might
* look like the following:
* <pre>
* // 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"</font>, new MessageListener() {
* <p/>
* public void processMessage(Chat chat, Message message) {
* // Print out any messages we get back to standard out.
* System.out.println(<font color="green">"Received message: "</font> + message);
* }
* });
* chat.sendMessage(<font color="green">"Howdy!"</font>);
* // Disconnect from the server
* con.disconnect();
* </pre>
* <p/>
* 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.<p>
* <p/>
* If a connected XMPPConnection 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.
*
* Creates a socket connection to a XMPP server. This is the default connection
* to a Jabber server and is specified in the XMPP Core (RFC 3920).
*
* @see Connection
* @author Matt Tucker
*/
public class XMPPConnection {
public class XMPPConnection extends Connection {
/**
* Value that indicates whether debugging is enabled. When enabled, a debug
* window will apear for each new connection that will contain the following
* information:<ul>
* <li> Client Traffic -- raw XML traffic generated by Smack and sent to the server.
* <li> Server Traffic -- raw XML traffic sent by the server to the client.
* <li> Interpreted Packets -- shows XML packets from the server as parsed by Smack.
* </ul>
* <p/>
* Debugging can be enabled by setting this field to true, or by setting the Java system
* property <tt>smack.debugEnabled</tt> to true. The system property can be set on the
* command line such as "java SomeApp -Dsmack.debugEnabled=true".
* The socket which is used for this connection.
*/
public static boolean DEBUG_ENABLED = false;
private final static Set<ConnectionCreationListener> connectionEstablishedListeners =
new CopyOnWriteArraySet<ConnectionCreationListener>();
// Counter 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.
private static AtomicInteger connectionCounter = new AtomicInteger(0);
// CallbackHandler to handle prompting for theh keystore password.
private CallbackHandler callbackHandler = null;
static {
// Use try block since we may not have permission to get a system
// property (for example, when an applet).
try {
DEBUG_ENABLED = Boolean.getBoolean("smack.debugEnabled");
}
catch (Exception e) {
// Ignore.
}
// Ensure the SmackConfiguration class is loaded by calling a method in it.
SmackConfiguration.getVersion();
}
private SmackDebugger debugger = null;
/**
* IP address or host name of the server. This information is only used when
* creating new socket connections to the server. If this information is not
* configured then it will be assumed that the host name matches the service name.
*/
String host;
int port;
Socket socket;
/**
* Hostname of the XMPP server. Usually servers use the same service name as the name
* of the server. However, there are some servers like google where host would be
* talk.google.com and the serviceName would be gmail.com.
*/
String serviceName;
int connectionCounterValue = connectionCounter.getAndIncrement();
String connectionID = null;
private String user = null;
private boolean connected = false;
@ -158,25 +76,15 @@ public class XMPPConnection {
PacketReader packetReader;
Roster roster = null;
private AccountManager accountManager = null;
private SASLAuthentication saslAuthentication = new SASLAuthentication(this);
Writer writer;
Reader reader;
/**
* Collection of available stream compression methods offered by the server.
*/
private Collection compressionMethods;
private Collection<String> compressionMethods;
/**
* Flag that indicates if stream compression is actually in use.
*/
private boolean usingCompression;
/**
* Holds the initial configuration used while creating the connection.
*/
private ConnectionConfiguration configuration;
private ChatManager chatManager;
/**
@ -203,12 +111,11 @@ public class XMPPConnection {
*/
public XMPPConnection(String serviceName, CallbackHandler callbackHandler) {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(serviceName);
super(new ConnectionConfiguration(serviceName));
config.setCompressionEnabled(false);
config.setSASLAuthenticationEnabled(true);
config.setDebuggerEnabled(DEBUG_ENABLED);
this.configuration = config;
this.callbackHandler = callbackHandler;
config.setCallbackHandler(callbackHandler);
}
/**
@ -221,12 +128,10 @@ public class XMPPConnection {
*/
public XMPPConnection(String serviceName) {
// Create the configuration for this new connection
ConnectionConfiguration config = new ConnectionConfiguration(serviceName);
super(new ConnectionConfiguration(serviceName));
config.setCompressionEnabled(false);
config.setSASLAuthenticationEnabled(true);
config.setDebuggerEnabled(DEBUG_ENABLED);
this.configuration = config;
this.callbackHandler = config.getCallbackHandler();
}
/**
@ -239,8 +144,7 @@ public class XMPPConnection {
* @param config the connection configuration.
*/
public XMPPConnection(ConnectionConfiguration config) {
this.configuration = config;
this.callbackHandler = config.getCallbackHandler();
super(config);
}
/**
@ -262,19 +166,10 @@ public class XMPPConnection {
* @param callbackHandler the CallbackHandler used to prompt for the password to the keystore.
*/
public XMPPConnection(ConnectionConfiguration config, CallbackHandler callbackHandler) {
this.configuration = config;
this.callbackHandler = callbackHandler;
super(config);
config.setCallbackHandler(callbackHandler);
}
/**
* 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 <tt>null</tt> if not connected to the server.
*
* @return the ID of this connection returned from the XMPP server or <tt>null</tt> if
* not connected to the server.
*/
public String getConnectionID() {
if (!isConnected()) {
return null;
@ -282,43 +177,6 @@ public class XMPPConnection {
return connectionID;
}
/**
* 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.
*
* @return the name of the service provided by the XMPP server.
*/
public String getServiceName() {
return serviceName;
}
/**
* 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.
*
* @return the host name of the server where the XMPP server is running.
*/
public String getHost() {
return host;
}
/**
* 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.
*
* @return the port number of the XMPP server.
*/
public int getPort() {
return port;
}
/**
* Returns the full XMPP address of the user that is logged in to the connection or
* <tt>null</tt> if not logged in yet. An XMPP address is in the form
* username@server/resource.
*
* @return the full XMPP address of the user logged in.
*/
public String getUser() {
if (!isAuthenticated()) {
return null;
@ -326,29 +184,6 @@ public class XMPPConnection {
return user;
}
/**
* 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.<p>
*
* 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 <tt>null</tt> 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. If the server supports SASL authentication then the user will be
@ -388,7 +223,7 @@ public class XMPPConnection {
username = username.toLowerCase().trim();
String response;
if (configuration.isSASLAuthenticationEnabled() &&
if (config.isSASLAuthenticationEnabled() &&
saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL
if (password != null) {
@ -396,7 +231,7 @@ public class XMPPConnection {
}
else {
response = saslAuthentication
.authenticate(username, resource, configuration.getCallbackHandler());
.authenticate(username, resource, config.getCallbackHandler());
}
}
else {
@ -408,17 +243,17 @@ public class XMPPConnection {
if (response != null) {
this.user = response;
// Update the serviceName with the one returned by the server
this.serviceName = StringUtils.parseServer(response);
config.setServiceName(StringUtils.parseServer(response));
}
else {
this.user = username + "@" + this.serviceName;
this.user = username + "@" + getServiceName();
if (resource != null) {
this.user += "/" + resource;
}
}
// If compression is enabled then request the server to use stream compression
if (configuration.isCompressionEnabled()) {
if (config.isCompressionEnabled()) {
useCompression();
}
@ -426,12 +261,12 @@ public class XMPPConnection {
if (this.roster == null) {
this.roster = new Roster(this);
}
if (configuration.isRosterLoadedAtLogin()) {
roster.reload();
if (config.isRosterLoadedAtLogin()) {
this.roster.reload();
}
// Set presence to online.
if (configuration.isSendPresence()) {
if (config.isSendPresence()) {
packetWriter.sendPacket(new Presence(Presence.Type.available));
}
@ -440,13 +275,13 @@ public class XMPPConnection {
anonymous = false;
// Stores the autentication for future reconnection
this.getConfiguration().setLoginInfo(username, password, resource);
config.setLoginInfo(username, password, resource);
// If debugging is enabled, change the the debug window title to include the
// name we are now logged-in as.
// If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
// will be null
if (configuration.isDebuggerEnabled() && debugger != null) {
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
}
@ -470,7 +305,7 @@ public class XMPPConnection {
}
String response;
if (configuration.isSASLAuthenticationEnabled() &&
if (config.isSASLAuthenticationEnabled() &&
saslAuthentication.hasAnonymousAuthentication()) {
response = saslAuthentication.authenticateAnonymously();
}
@ -482,10 +317,10 @@ public class XMPPConnection {
// Set the user value.
this.user = response;
// Update the serviceName with the one returned by the server
this.serviceName = StringUtils.parseServer(response);
config.setServiceName(StringUtils.parseServer(response));
// If compression is enabled then request the server to use stream compression
if (configuration.isCompressionEnabled()) {
if (config.isCompressionEnabled()) {
useCompression();
}
@ -503,25 +338,18 @@ public class XMPPConnection {
// name we are now logged-in as.
// If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
// will be null
if (configuration.isDebuggerEnabled() && debugger != null) {
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
}
/**
* 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
* <tt>null</tt>.
*
* @return the user's roster, or <tt>null</tt> if the user has not logged in yet.
*/
public Roster getRoster() {
if (!configuration.isRosterLoadedAtLogin()) {
roster.reload();
}
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
@ -552,64 +380,18 @@ public class XMPPConnection {
return roster;
}
/**
* 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 true if currently connected to the XMPP server.
*
* @return true if connected.
*/
public boolean isConnected() {
return connected;
}
/**
* Returns true if the connection to the server has successfully negotiated TLS. Once TLS
* has been negotiatied the connection has been secured. @see #isUsingTLS.
*
* @return true if a secure connection to the server.
*/
public boolean isSecureConnection() {
return isUsingTLS();
}
/**
* Returns true if currently authenticated by successfully calling the login method.
*
* @return true if authenticated.
*/
public boolean isAuthenticated() {
return authenticated;
}
/**
* Returns true if currently authenticated anonymously.
*
* @return true if authenticated anonymously.
*/
public boolean isAnonymous() {
return anonymous;
}
@ -667,37 +449,6 @@ public class XMPPConnection {
saslAuthentication.init();
}
/**
* 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.<p>
* <p/>
* 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 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.<p>
* <p/>
* 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 void disconnect(Presence unavailablePresence) {
// If not connected, ignore this request.
if (packetReader == null || packetWriter == null) {
@ -719,11 +470,6 @@ public class XMPPConnection {
packetReader = null;
}
/**
* Sends the specified packet to the server.
*
* @param packet the packet to send.
*/
public void sendPacket(Packet packet) {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
@ -735,29 +481,28 @@ public class XMPPConnection {
}
/**
* 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.
* 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.
*
* @param packetListener the packet listener to notify of new packets.
* @param packetFilter the packet filter to use.
* @param packetInterceptor the packet interceptor to notify of packets about to be sent.
* @param packetFilter the packet filter to use.
* @deprecated replaced by {@link Connection#addPacketInterceptor(PacketInterceptor, PacketFilter)}.
*/
public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
packetReader.addPacketListener(packetListener, packetFilter);
public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor,
PacketFilter packetFilter) {
addPacketInterceptor(packetInterceptor, packetFilter);
}
/**
* Removes a packet listener from this connection.
* Removes a packet interceptor.
*
* @param packetListener the packet listener to remove.
* @param packetInterceptor the packet interceptor to remove.
* @deprecated replaced by {@link Connection#removePacketInterceptor(PacketInterceptor)}.
*/
public void removePacketListener(PacketListener packetListener) {
if (packetReader != null) {
packetReader.removePacketListener(packetListener);
}
public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) {
removePacketInterceptor(packetInterceptor);
}
/**
@ -770,116 +515,25 @@ public class XMPPConnection {
*
* @param packetListener the packet listener to notify of sent packets.
* @param packetFilter the packet filter to use.
* @deprecated replaced by {@link #addPacketSendingListener(PacketListener, PacketFilter)}.
*/
public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
packetWriter.addPacketListener(packetListener, packetFilter);
addPacketSendingListener(packetListener, packetFilter);
}
/**
* Removes a packet listener from this connection.
* Removes a packet listener for sending packets from this connection.
*
* @param packetListener the packet listener to remove.
* @deprecated replaced by {@link #removePacketSendingListener(PacketListener)}.
*/
public void removePacketWriterListener(PacketListener packetListener) {
if (packetWriter != null) {
packetWriter.removePacketListener(packetListener);
}
}
/**
* 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.
*
* @param packetInterceptor the packet interceptor to notify of packets about to be sent.
* @param packetFilter the packet filter to use.
*/
public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor,
PacketFilter packetFilter) {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
packetWriter.addPacketInterceptor(packetInterceptor, packetFilter);
}
/**
* Removes a packet interceptor.
*
* @param packetInterceptor the packet interceptor to remove.
*/
public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) {
packetWriter.removePacketInterceptor(packetInterceptor);
}
/**
* Creates a new packet collector for this connection. A packet filter determines
* which packets will be accumulated by the collector.
*
* @param packetFilter the packet filter to use.
* @return a new packet collector.
*/
public PacketCollector createPacketCollector(PacketFilter packetFilter) {
return packetReader.createPacketCollector(packetFilter);
}
/**
* 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.
*
* @param connectionListener a connection listener.
*/
public void addConnectionListener(ConnectionListener connectionListener) {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
if (connectionListener == null) {
return;
}
if (!packetReader.connectionListeners.contains(connectionListener)) {
packetReader.connectionListeners.add(connectionListener);
}
}
/**
* Removes a connection listener from this connection.
*
* @param connectionListener a connection listener.
*/
public void removeConnectionListener(ConnectionListener connectionListener) {
if (packetReader != null) {
packetReader.connectionListeners.remove(connectionListener);
}
}
/**
* 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.
*
* @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);
removePacketSendingListener(packetListener);
}
private void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException {
this.host = config.getHost();
this.port = config.getPort();
String host = config.getHost();
int port = config.getPort();
try {
if (config.getSocketFactory() == null) {
this.socket = new Socket(host, port);
@ -900,7 +554,6 @@ public class XMPPConnection {
throw new XMPPException(errorMessage, new XMPPError(
XMPPError.Condition.remote_server_error, errorMessage), ioe);
}
this.serviceName = config.getServiceName();
initConnection();
}
@ -926,10 +579,10 @@ public class XMPPConnection {
// If debugging is enabled, we should start the thread that will listen for
// all packets and then log them.
if (configuration.isDebuggerEnabled()) {
packetReader.addPacketListener(debugger.getReaderListener(), null);
if (config.isDebuggerEnabled()) {
addPacketListener(debugger.getReaderListener(), null);
if (debugger.getWriterListener() != null) {
packetWriter.addPacketListener(debugger.getWriterListener(), null);
addPacketSendingListener(debugger.getWriterListener(), null);
}
}
}
@ -953,7 +606,7 @@ public class XMPPConnection {
if (isFirstInitialization) {
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : connectionEstablishedListeners) {
for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
listener.connectionCreated(this);
}
}
@ -1053,62 +706,7 @@ public class XMPPConnection {
}
// If debugging is enabled, we open a window and write out all network traffic.
if (configuration.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(XMPPConnection.class, Writer.class, Reader.class);
debugger = (SmackDebugger) constructor.newInstance(this, writer, reader);
reader = debugger.getReader();
writer = debugger.getWriter();
}
catch (Exception e) {
e.printStackTrace();
DEBUG_ENABLED = false;
}
}
else {
// Obtain new reader and writer from the existing debugger
reader = debugger.newConnectionReader(reader);
writer = debugger.newConnectionWriter(writer);
}
}
initDebugger();
}
/***********************************************
@ -1125,26 +723,6 @@ public class XMPPConnection {
return usingTLS;
}
/**
* 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;
}
/**
* Returns the configuration used to connect to the server.
*
* @return the configuration used to connect to the server.
*/
protected ConnectionConfiguration getConfiguration() {
return configuration;
}
/**
* Notification message saying that the server supports TLS so confirm the server that we
* want to secure the connection.
@ -1152,14 +730,14 @@ public class XMPPConnection {
* @param required true when the server indicates that TLS is required.
*/
void startTLSReceived(boolean required) {
if (required && configuration.getSecurityMode() ==
if (required && config.getSecurityMode() ==
ConnectionConfiguration.SecurityMode.disabled) {
packetReader.notifyConnectionError(new IllegalStateException(
"TLS required by server but not allowed by connection configuration"));
return;
}
if (configuration.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) {
if (config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) {
// Do not secure the connection using TLS since TLS was disabled
return;
}
@ -1185,24 +763,24 @@ public class XMPPConnection {
KeyManager[] kms = null;
PasswordCallback pcb = null;
if(callbackHandler == null) {
if(config.getCallbackHandler() == null) {
ks = null;
} else {
//System.out.println("Keystore type: "+configuration.getKeystoreType());
if(configuration.getKeystoreType().equals("NONE")) {
if(config.getKeystoreType().equals("NONE")) {
ks = null;
pcb = null;
}
else if(configuration.getKeystoreType().equals("PKCS11")) {
else if(config.getKeystoreType().equals("PKCS11")) {
try {
Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = "+configuration.getPKCS11Library();
String pkcs11Config = "name = SmartCard\nlibrary = "+config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
Provider p = (Provider)c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11",p);
pcb = new PasswordCallback("PKCS11 Password: ",false);
callbackHandler.handle(new Callback[]{pcb});
this.config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(null,pcb.getPassword());
}
catch (Exception e) {
@ -1210,18 +788,18 @@ public class XMPPConnection {
pcb = null;
}
}
else if(configuration.getKeystoreType().equals("Apple")) {
else if(config.getKeystoreType().equals("Apple")) {
ks = KeyStore.getInstance("KeychainStore","Apple");
ks.load(null,null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
}
else {
ks = KeyStore.getInstance(configuration.getKeystoreType());
ks = KeyStore.getInstance(config.getKeystoreType());
try {
pcb = new PasswordCallback("Keystore Password: ",false);
callbackHandler.handle(new Callback[]{pcb});
ks.load(new FileInputStream(configuration.getKeystorePath()), pcb.getPassword());
config.getCallbackHandler().handle(new Callback[]{pcb});
ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
}
catch(Exception e) {
ks = null;
@ -1244,7 +822,8 @@ public class XMPPConnection {
// Verify certificate presented by the server
context.init(kms,
new javax.net.ssl.TrustManager[]{new ServerTrustManager(serviceName, configuration)},
new javax.net.ssl.TrustManager[]{new ServerTrustManager(getServiceName(), config)},
//new javax.net.ssl.TrustManager[]{new OpenTrustManager()},
new java.security.SecureRandom());
Socket plain = socket;
// Secure the plain connection
@ -1279,7 +858,7 @@ public class XMPPConnection {
*
* @param methods compression methods offered by the server.
*/
void setAvailableCompressionMethods(Collection methods) {
void setAvailableCompressionMethods(Collection<String> methods) {
compressionMethods = methods;
}
@ -1293,16 +872,6 @@ public class XMPPConnection {
return compressionMethods != null && compressionMethods.contains(method);
}
/**
* 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.<p>
* <p/>
* Note: to use stream compression the smackx.jar file has to be present in the classpath.
*
* @return true if network traffic is being compressed.
*/
public boolean isUsingCompression() {
return usingCompression;
}
@ -1412,7 +981,7 @@ public class XMPPConnection {
*/
public void connect() throws XMPPException {
// Stablishes the connection, readers and writers
connectUsingConfiguration(configuration);
connectUsingConfiguration(config);
// Automatically makes the login if the user was previouslly connected successfully
// to the server and the connection was terminated abruptly
if (connected && wasAuthenticated) {
@ -1423,8 +992,8 @@ public class XMPPConnection {
loginAnonymously();
}
else {
login(getConfiguration().getUsername(), getConfiguration().getPassword(),
getConfiguration().getResource());
login(config.getUsername(), config.getPassword(),
config.getResource());
}
}
catch (XMPPException e) {