Optimized concurrency in packet writer, better job of cleanup on disconnect.
[Smack.git] / source / org / jivesoftware / smack / XMPPConnection.java
blob0b2b84ba0cf39ab7e2b426a5a8613be2abba3c4f
1 /**
2 * $RCSfile$
3 * $Revision$
4 * $Date$
6 * Copyright 2003-2007 Jive Software.
8 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 package org.jivesoftware.smack;
23 import org.jivesoftware.smack.debugger.SmackDebugger;
24 import org.jivesoftware.smack.filter.PacketFilter;
25 import org.jivesoftware.smack.packet.Packet;
26 import org.jivesoftware.smack.packet.Presence;
27 import org.jivesoftware.smack.packet.XMPPError;
28 import org.jivesoftware.smack.util.StringUtils;
30 import javax.net.ssl.SSLContext;
31 import javax.net.ssl.SSLSocket;
32 import java.io.*;
33 import java.lang.reflect.Constructor;
34 import java.lang.reflect.Method;
35 import java.net.Socket;
36 import java.net.UnknownHostException;
37 import java.util.Collection;
38 import java.util.Set;
39 import java.util.concurrent.CopyOnWriteArraySet;
40 import java.util.concurrent.atomic.AtomicInteger;
42 /**
43 * Creates a connection to a XMPP server. A simple use of this API might
44 * look like the following:
45 * <pre>
46 * // Create a connection to the igniterealtime.org XMPP server.
47 * XMPPConnection con = new XMPPConnection("igniterealtime.org");
48 * // Connect to the server
49 * con.connect();
50 * // Most servers require you to login before performing other tasks.
51 * con.login("jsmith", "mypass");
52 * // Start a new conversation with John Doe and send him a message.
53 * Chat chat = connection.getChatManager().createChat("jdoe@igniterealtime.org"</font>, new MessageListener() {
55 * public void processMessage(Chat chat, Message message) {
56 * // Print out any messages we get back to standard out.
57 * System.out.println(<font color="green">"Received message: "</font> + message);
58 * }
59 * });
60 * chat.sendMessage(<font color="green">"Howdy!"</font>);
61 * // Disconnect from the server
62 * con.disconnect();
63 * </pre>
65 * XMPPConnections can be reused between connections. This means that an XMPPConnection
66 * may be connected, disconnected and then connected again. Listeners of the XMPPConnection
67 * will be retained accross connections.<p>
69 * If a connected XMPPConnection gets disconnected abruptly then it will try to reconnect
70 * again. To stop the reconnection process, use {@link #disconnect()}. Once stopped
71 * you can use {@link #connect()} to manually connect to the server.
73 * @author Matt Tucker
75 public class XMPPConnection {
77 /**
78 * Value that indicates whether debugging is enabled. When enabled, a debug
79 * window will apear for each new connection that will contain the following
80 * information:<ul>
81 * <li> Client Traffic -- raw XML traffic generated by Smack and sent to the server.
82 * <li> Server Traffic -- raw XML traffic sent by the server to the client.
83 * <li> Interpreted Packets -- shows XML packets from the server as parsed by Smack.
84 * </ul>
86 * Debugging can be enabled by setting this field to true, or by setting the Java system
87 * property <tt>smack.debugEnabled</tt> to true. The system property can be set on the
88 * command line such as "java SomeApp -Dsmack.debugEnabled=true".
90 public static boolean DEBUG_ENABLED = false;
92 private final static Set<ConnectionCreationListener> connectionEstablishedListeners =
93 new CopyOnWriteArraySet<ConnectionCreationListener>();
95 // Counter to uniquely identify connections that are created. This is distinct from the
96 // connection ID, which is a value sent by the server once a connection is made.
97 private static AtomicInteger connectionCounter = new AtomicInteger(0);
99 static {
100 // Use try block since we may not have permission to get a system
101 // property (for example, when an applet).
102 try {
103 DEBUG_ENABLED = Boolean.getBoolean("smack.debugEnabled");
105 catch (Exception e) {
106 // Ignore.
108 // Ensure the SmackConfiguration class is loaded by calling a method in it.
109 SmackConfiguration.getVersion();
111 private SmackDebugger debugger = null;
114 * IP address or host name of the server. This information is only used when
115 * creating new socket connections to the server. If this information is not
116 * configured then it will be assumed that the host name matches the service name.
118 String host;
119 int port;
120 Socket socket;
123 * Hostname of the XMPP server. Usually servers use the same service name as the name
124 * of the server. However, there are some servers like google where host would be
125 * talk.google.com and the serviceName would be gmail.com.
127 String serviceName;
129 int connectionCounterValue = connectionCounter.getAndIncrement();
130 String connectionID = null;
131 private String user = null;
132 private boolean connected = false;
134 * Flag that indicates if the user is currently authenticated with the server.
136 private boolean authenticated = false;
138 * Flag that indicates if the user was authenticated with the server when the connection
139 * to the server was closed (abruptly or not).
141 private boolean wasAuthenticated = false;
142 private boolean anonymous = false;
143 private boolean usingTLS = false;
145 PacketWriter packetWriter;
146 PacketReader packetReader;
148 Roster roster = null;
149 private AccountManager accountManager = null;
150 protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);
152 Writer writer;
153 Reader reader;
156 * Collection of available stream compression methods offered by the server.
158 private Collection compressionMethods;
160 * Flag that indicates if stream compression is actually in use.
162 private boolean usingCompression;
164 * Holds the initial configuration used while creating the connection.
166 private ConnectionConfiguration configuration;
167 private ChatManager chatManager;
170 * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be
171 * performed to determine the IP address and port corresponding to the
172 * service name; if that lookup fails, it's assumed that server resides at
173 * <tt>serviceName</tt> with the default port of 5222. Encrypted connections (TLS)
174 * will be used if available, stream compression is disabled, and standard SASL
175 * mechanisms will be used for authentication.<p>
177 * This is the simplest constructor for connecting to an XMPP server. Alternatively,
178 * you can get fine-grained control over connection settings using the
179 * {@link #XMPPConnection(ConnectionConfiguration)} constructor.<p>
181 * Note that XMPPConnection constructors do not establish a connection to the server
182 * and you must call {@link #connect()}.
184 * @param serviceName the name of the XMPP server to connect to; e.g. <tt>example.com</tt>.
186 public XMPPConnection(String serviceName) {
187 // Create the configuration for this new connection
188 ConnectionConfiguration config = new ConnectionConfiguration(serviceName);
189 config.setCompressionEnabled(false);
190 config.setSASLAuthenticationEnabled(true);
191 config.setDebuggerEnabled(DEBUG_ENABLED);
192 this.configuration = config;
196 * Creates a new XMPP connection using the specified connection configuration.<p>
198 * Manually specifying connection configuration information is suitable for
199 * advanced users of the API. In many cases, using the
200 * {@link #XMPPConnection(String)} constructor is a better approach.<p>
202 * Note that XMPPConnection constructors do not establish a connection to the server
203 * and you must call {@link #connect()}.
205 * @param config the connection configuration.
207 public XMPPConnection(ConnectionConfiguration config) {
208 this.configuration = config;
212 * Returns the connection ID for this connection, which is the value set by the server
213 * when opening a XMPP stream. If the server does not set a connection ID, this value
214 * will be null. This value will be <tt>null</tt> if not connected to the server.
216 * @return the ID of this connection returned from the XMPP server or <tt>null</tt> if
217 * not connected to the server.
219 public String getConnectionID() {
220 if (!isConnected()) {
221 return null;
223 return connectionID;
227 * Returns the name of the service provided by the XMPP server for this connection. After
228 * authenticating with the server the returned value may be different.
230 * @return the name of the service provided by the XMPP server.
232 public String getServiceName() {
233 return serviceName;
237 * Returns the host name of the server where the XMPP server is running. This would be the
238 * IP address of the server or a name that may be resolved by a DNS server.
240 * @return the host name of the server where the XMPP server is running.
242 public String getHost() {
243 return host;
247 * Returns the port number of the XMPP server for this connection. The default port
248 * for normal connections is 5222. The default port for SSL connections is 5223.
250 * @return the port number of the XMPP server.
252 public int getPort() {
253 return port;
257 * Returns the full XMPP address of the user that is logged in to the connection or
258 * <tt>null</tt> if not logged in yet. An XMPP address is in the form
259 * username@server/resource.
261 * @return the full XMPP address of the user logged in.
263 public String getUser() {
264 if (!isAuthenticated()) {
265 return null;
267 return user;
271 * Logs in to the server using the strongest authentication mode supported by
272 * the server, then sets presence to available. If more than five seconds
273 * (default timeout) elapses in each step of the authentication process without
274 * a response from the server, or if an error occurs, a XMPPException will be thrown.
276 * @param username the username.
277 * @param password the password.
278 * @throws XMPPException if an error occurs.
280 public void login(String username, String password) throws XMPPException {
281 login(username, password, "Smack");
285 * Logs in to the server using the strongest authentication mode supported by
286 * the server, then sets presence to available. If more than five seconds
287 * (default timeout) elapses in each step of the authentication process without
288 * a response from the server, or if an error occurs, a XMPPException will be thrown.
290 * @param username the username.
291 * @param password the password.
292 * @param resource the resource.
293 * @throws XMPPException if an error occurs.
294 * @throws IllegalStateException if not connected to the server, or already logged in
295 * to the serrver.
297 public synchronized void login(String username, String password, String resource)
298 throws XMPPException
300 login(username, password, resource, true);
304 * Logs in to the server using the strongest authentication mode supported by
305 * the server. If the server supports SASL authentication then the user will be
306 * authenticated using SASL if not Non-SASL authentication will be tried. An available
307 * presence may optionally be sent. If <tt>sendPresence</tt>
308 * is false, a presence packet must be sent manually later. If more than five seconds
309 * (default timeout) elapses in each step of the authentication process without a
310 * response from the server, or if an error occurs, a XMPPException will be thrown.<p>
312 * Before logging in (i.e. authenticate) to the server the connection must be connected.
313 * For compatibility and easiness of use the connection will automatically connect to the
314 * server if not already connected.
316 * @param username the username.
317 * @param password the password.
318 * @param resource the resource.
319 * @param sendPresence if <tt>true</tt> an available presence will be sent automatically
320 * after login is completed.
321 * @throws XMPPException if an error occurs.
322 * @throws IllegalStateException if not connected to the server, or already logged in
323 * to the serrver.
325 public synchronized void login(String username, String password, String resource,
326 boolean sendPresence) throws XMPPException
328 if (!isConnected()) {
329 throw new IllegalStateException("Not connected to server.");
331 if (authenticated) {
332 throw new IllegalStateException("Already logged in to server.");
334 // Do partial version of nameprep on the username.
335 username = username.toLowerCase().trim();
337 String response;
338 if (configuration.isSASLAuthenticationEnabled() &&
339 saslAuthentication.hasNonAnonymousAuthentication()) {
340 // Authenticate using SASL
341 response = saslAuthentication.authenticate(username, password, resource);
343 else {
344 // Authenticate using Non-SASL
345 response = new NonSASLAuthentication(this).authenticate(username, password, resource);
348 // Set the user.
349 if (response != null) {
350 this.user = response;
351 // Update the serviceName with the one returned by the server
352 this.serviceName = StringUtils.parseServer(response);
354 else {
355 this.user = username + "@" + this.serviceName;
356 if (resource != null) {
357 this.user += "/" + resource;
361 // If compression is enabled then request the server to use stream compression
362 if (configuration.isCompressionEnabled()) {
363 useCompression();
366 // Create the roster if it is not a reconnection.
367 if (this.roster == null) {
368 this.roster = new Roster(this);
370 roster.reload();
372 // Set presence to online.
373 if (sendPresence) {
374 packetWriter.sendPacket(new Presence(Presence.Type.available));
377 // Indicate that we're now authenticated.
378 authenticated = true;
379 anonymous = false;
381 // Stores the autentication for future reconnection
382 this.getConfiguration().setLoginInfo(username, password, resource, sendPresence);
384 // If debugging is enabled, change the the debug window title to include the
385 // name we are now logged-in as.
386 // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
387 // will be null
388 if (configuration.isDebuggerEnabled() && debugger != null) {
389 debugger.userHasLogged(user);
394 * Logs in to the server anonymously. Very few servers are configured to support anonymous
395 * authentication, so it's fairly likely logging in anonymously will fail. If anonymous login
396 * does succeed, your XMPP address will likely be in the form "server/123ABC" (where "123ABC"
397 * is a random value generated by the server).
399 * @throws XMPPException if an error occurs or anonymous logins are not supported by the server.
400 * @throws IllegalStateException if not connected to the server, or already logged in
401 * to the serrver.
403 public synchronized void loginAnonymously() throws XMPPException {
404 if (!isConnected()) {
405 throw new IllegalStateException("Not connected to server.");
407 if (authenticated) {
408 throw new IllegalStateException("Already logged in to server.");
411 String response;
412 if (configuration.isSASLAuthenticationEnabled() &&
413 saslAuthentication.hasAnonymousAuthentication()) {
414 response = saslAuthentication.authenticateAnonymously();
416 else {
417 // Authenticate using Non-SASL
418 response = new NonSASLAuthentication(this).authenticateAnonymously();
421 // Set the user value.
422 this.user = response;
423 // Update the serviceName with the one returned by the server
424 this.serviceName = StringUtils.parseServer(response);
426 // If compression is enabled then request the server to use stream compression
427 if (configuration.isCompressionEnabled()) {
428 useCompression();
431 // Anonymous users can't have a roster.
432 roster = null;
434 // Set presence to online.
435 packetWriter.sendPacket(new Presence(Presence.Type.available));
437 // Indicate that we're now authenticated.
438 authenticated = true;
439 anonymous = true;
441 // If debugging is enabled, change the the debug window title to include the
442 // name we are now logged-in as.
443 // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
444 // will be null
445 if (configuration.isDebuggerEnabled() && debugger != null) {
446 debugger.userHasLogged(user);
451 * Returns the roster for the user logged into the server. If the user has not yet
452 * logged into the server (or if the user is logged in anonymously), this method will return
453 * <tt>null</tt>.
455 * @return the user's roster, or <tt>null</tt> if the user has not logged in yet.
457 public Roster getRoster() {
458 if (roster == null) {
459 return null;
461 // If this is the first time the user has asked for the roster after calling
462 // login, we want to wait for the server to send back the user's roster. This
463 // behavior shields API users from having to worry about the fact that roster
464 // operations are asynchronous, although they'll still have to listen for
465 // changes to the roster. Note: because of this waiting logic, internal
466 // Smack code should be wary about calling the getRoster method, and may need to
467 // access the roster object directly.
468 if (!roster.rosterInitialized) {
469 try {
470 synchronized (roster) {
471 long waitTime = SmackConfiguration.getPacketReplyTimeout();
472 long start = System.currentTimeMillis();
473 while (!roster.rosterInitialized) {
474 if (waitTime <= 0) {
475 break;
477 roster.wait(waitTime);
478 long now = System.currentTimeMillis();
479 waitTime -= now - start;
480 start = now;
484 catch (InterruptedException ie) {
485 // Ignore.
488 return roster;
492 * Returns an account manager instance for this connection.
494 * @return an account manager for this connection.
496 public synchronized AccountManager getAccountManager() {
497 if (accountManager == null) {
498 accountManager = new AccountManager(this);
500 return accountManager;
504 * Returns a chat manager instance for this connection. The ChatManager manages all incoming and
505 * outgoing chats on the current connection.
507 * @return a chat manager instance for this connection.
509 public synchronized ChatManager getChatManager() {
510 if(this.chatManager == null) {
511 this.chatManager = new ChatManager(this);
513 return this.chatManager;
517 * Returns true if currently connected to the XMPP server.
519 * @return true if connected.
521 public boolean isConnected() {
522 return connected;
526 * Returns true if the connection is a secured one, such as an SSL connection or
527 * if TLS was negotiated successfully.
529 * @return true if a secure connection to the server.
531 public boolean isSecureConnection() {
532 return isUsingTLS();
536 * Returns true if currently authenticated by successfully calling the login method.
538 * @return true if authenticated.
540 public boolean isAuthenticated() {
541 return authenticated;
545 * Returns true if currently authenticated anonymously.
547 * @return true if authenticated anonymously.
549 public boolean isAnonymous() {
550 return anonymous;
554 * Closes the connection by setting presence to unavailable then closing the stream to
555 * the XMPP server. The shutdown logic will be used during a planned disconnection or when
556 * dealing with an unexpected disconnection. Unlike {@link #disconnect()} the connection's
557 * packet reader, packet writer, and {@link Roster} will not be removed; thus
558 * connection's state is kept.
560 * @param unavailablePresence the presence packet to send during shutdown.
562 protected void shutdown(Presence unavailablePresence) {
563 // Set presence to offline.
564 packetWriter.sendPacket(unavailablePresence);
565 packetReader.shutdown();
566 packetWriter.shutdown();
567 // Wait 150 ms for processes to clean-up, then shutdown.
568 try {
569 Thread.sleep(150);
571 catch (Exception e) {
572 // Ignore.
575 // Close down the readers and writers.
576 if (reader != null)
578 try { reader.close(); } catch (Throwable ignore) { /* ignore */ }
579 reader = null;
581 if (writer != null)
583 try { writer.close(); } catch (Throwable ignore) { /* ignore */ }
584 writer = null;
587 try {
588 socket.close();
590 catch (Exception e) {
591 // Ignore.
594 this.setWasAuthenticated(authenticated);
595 authenticated = false;
596 connected = false;
598 saslAuthentication.init();
602 * Closes the connection by setting presence to unavailable then closing the stream to
603 * the XMPP server. The XMPPConnection can still be used for connecting to the server
604 * again.<p>
606 * This method cleans up all resources used by the connection. Therefore, the roster,
607 * listeners and other stateful objects cannot be re-used by simply calling connect()
608 * on this connection again. This is unlike the behavior during unexpected disconnects
609 * (and subsequent connections). In that case, all state is preserved to allow for
610 * more seamless error recovery.
612 public void disconnect() {
613 disconnect(new Presence(Presence.Type.unavailable));
617 * Closes the connection. A custom unavailable presence is sent to the server, followed
618 * by closing the stream. The XMPPConnection can still be used for connecting to the server
619 * again. A custom unavilable presence is useful for communicating offline presence
620 * information such as "On vacation". Typically, just the status text of the presence
621 * packet is set with online information, but most XMPP servers will deliver the full
622 * presence packet with whatever data is set.<p>
624 * This method cleans up all resources used by the connection. Therefore, the roster,
625 * listeners and other stateful objects cannot be re-used by simply calling connect()
626 * on this connection again. This is unlike the behavior during unexpected disconnects
627 * (and subsequent connections). In that case, all state is preserved to allow for
628 * more seamless error recovery.
630 * @param unavailablePresence the presence packet to send during shutdown.
632 public void disconnect(Presence unavailablePresence) {
633 this.shutdown(unavailablePresence);
635 this.roster = null;
637 this.wasAuthenticated = false;
639 packetWriter.cleanup();
640 packetWriter = null;
641 packetReader.cleanup();
642 packetReader = null;
646 * Sends the specified packet to the server.
648 * @param packet the packet to send.
650 public void sendPacket(Packet packet) {
651 if (!isConnected()) {
652 throw new IllegalStateException("Not connected to server.");
654 if (packet == null) {
655 throw new NullPointerException("Packet is null.");
657 packetWriter.sendPacket(packet);
661 * Registers a packet listener with this connection. A packet filter determines
662 * which packets will be delivered to the listener.
664 * @param packetListener the packet listener to notify of new packets.
665 * @param packetFilter the packet filter to use.
667 public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
668 if (!isConnected()) {
669 throw new IllegalStateException("Not connected to server.");
671 packetReader.addPacketListener(packetListener, packetFilter);
675 * Removes a packet listener from this connection.
677 * @param packetListener the packet listener to remove.
679 public void removePacketListener(PacketListener packetListener) {
680 packetReader.removePacketListener(packetListener);
684 * Registers a packet listener with this connection. The listener will be
685 * notified of every packet that this connection sends. A packet filter determines
686 * which packets will be delivered to the listener. Note that the thread
687 * that writes packets will be used to invoke the listeners. Therefore, each
688 * packet listener should complete all operations quickly or use a different
689 * thread for processing.
691 * @param packetListener the packet listener to notify of sent packets.
692 * @param packetFilter the packet filter to use.
694 public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) {
695 if (!isConnected()) {
696 throw new IllegalStateException("Not connected to server.");
698 packetWriter.addPacketListener(packetListener, packetFilter);
702 * Removes a packet listener from this connection.
704 * @param packetListener the packet listener to remove.
706 public void removePacketWriterListener(PacketListener packetListener) {
707 packetWriter.removePacketListener(packetListener);
711 * Registers a packet interceptor with this connection. The interceptor will be
712 * invoked every time a packet is about to be sent by this connection. Interceptors
713 * may modify the packet to be sent. A packet filter determines which packets
714 * will be delivered to the interceptor.
716 * @param packetInterceptor the packet interceptor to notify of packets about to be sent.
717 * @param packetFilter the packet filter to use.
719 public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor,
720 PacketFilter packetFilter) {
721 if (!isConnected()) {
722 throw new IllegalStateException("Not connected to server.");
724 packetWriter.addPacketInterceptor(packetInterceptor, packetFilter);
728 * Removes a packet interceptor.
730 * @param packetInterceptor the packet interceptor to remove.
732 public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) {
733 packetWriter.removePacketInterceptor(packetInterceptor);
737 * Creates a new packet collector for this connection. A packet filter determines
738 * which packets will be accumulated by the collector.
740 * @param packetFilter the packet filter to use.
741 * @return a new packet collector.
743 public PacketCollector createPacketCollector(PacketFilter packetFilter) {
744 return packetReader.createPacketCollector(packetFilter);
748 * Adds a connection listener to this connection that will be notified when
749 * the connection closes or fails. The connection needs to already be connected
750 * or otherwise an IllegalStateException will be thrown.
752 * @param connectionListener a connection listener.
754 public void addConnectionListener(ConnectionListener connectionListener) {
755 if (!isConnected()) {
756 throw new IllegalStateException("Not connected to server.");
758 if (connectionListener == null) {
759 return;
761 if (!packetReader.connectionListeners.contains(connectionListener)) {
762 packetReader.connectionListeners.add(connectionListener);
767 * Removes a connection listener from this connection.
769 * @param connectionListener a connection listener.
771 public void removeConnectionListener(ConnectionListener connectionListener) {
772 packetReader.connectionListeners.remove(connectionListener);
776 * Adds a new listener that will be notified when new XMPPConnections are created. Note
777 * that newly created connections will not be actually connected to the server.
779 * @param connectionCreationListener a listener interested on new connections.
781 public static void addConnectionCreationListener(
782 ConnectionCreationListener connectionCreationListener) {
783 connectionEstablishedListeners.add(connectionCreationListener);
787 * Removes a listener that was interested in connection creation events.
789 * @param connectionCreationListener a listener interested on new connections.
791 public static void removeConnectionCreationListener(
792 ConnectionCreationListener connectionCreationListener) {
793 connectionEstablishedListeners.remove(connectionCreationListener);
796 private void connectUsingConfiguration(ConnectionConfiguration config) throws XMPPException {
797 this.host = config.getHost();
798 this.port = config.getPort();
799 try {
800 if (config.getSocketFactory() == null) {
801 this.socket = new Socket(host, port);
803 else {
804 this.socket = config.getSocketFactory().createSocket(host, port);
807 catch (UnknownHostException uhe) {
808 String errorMessage = "Could not connect to " + host + ":" + port + ".";
809 throw new XMPPException(errorMessage, new XMPPError(
810 XMPPError.Condition.remote_server_timeout, errorMessage),
811 uhe);
813 catch (IOException ioe) {
814 String errorMessage = "XMPPError connecting to " + host + ":"
815 + port + ".";
816 throw new XMPPException(errorMessage, new XMPPError(
817 XMPPError.Condition.remote_server_error, errorMessage), ioe);
819 this.serviceName = config.getServiceName();
820 initConnection();
824 * Initializes the connection by creating a packet reader and writer and opening a
825 * XMPP stream to the server.
827 * @throws XMPPException if establishing a connection to the server fails.
829 private void initConnection() throws XMPPException {
830 boolean isFirstInitialization = packetReader == null || packetWriter == null;
831 if (!isFirstInitialization) {
832 usingCompression = false;
835 // Set the reader and writer instance variables
836 initReaderAndWriter();
838 try {
839 if (isFirstInitialization) {
840 packetWriter = new PacketWriter(this);
841 packetReader = new PacketReader(this);
843 // If debugging is enabled, we should start the thread that will listen for
844 // all packets and then log them.
845 if (configuration.isDebuggerEnabled()) {
846 packetReader.addPacketListener(debugger.getReaderListener(), null);
847 if (debugger.getWriterListener() != null) {
848 packetWriter.addPacketListener(debugger.getWriterListener(), null);
852 else {
853 packetWriter.init();
854 packetReader.init();
857 // Start the packet writer. This will open a XMPP stream to the server
858 packetWriter.startup();
859 // Start the packet reader. The startup() method will block until we
860 // get an opening stream packet back from server.
861 packetReader.startup();
863 // Make note of the fact that we're now connected.
864 connected = true;
866 // Start keep alive process (after TLS was negotiated - if available)
867 packetWriter.startKeepAliveProcess();
870 if (isFirstInitialization) {
871 // Notify listeners that a new connection has been established
872 for (ConnectionCreationListener listener : connectionEstablishedListeners) {
873 listener.connectionCreated(this);
876 else {
877 packetReader.notifyReconnection();
881 catch (XMPPException ex) {
882 // An exception occurred in setting up the connection. Make sure we shut down the
883 // readers and writers and close the socket.
885 if (packetWriter != null) {
886 try {
887 packetWriter.shutdown();
889 catch (Throwable ignore) { /* ignore */ }
890 packetWriter = null;
892 if (packetReader != null) {
893 try {
894 packetReader.shutdown();
896 catch (Throwable ignore) { /* ignore */ }
897 packetReader = null;
899 if (reader != null) {
900 try {
901 reader.close();
903 catch (Throwable ignore) { /* ignore */ }
904 reader = null;
906 if (writer != null) {
907 try {
908 writer.close();
910 catch (Throwable ignore) { /* ignore */}
911 writer = null;
913 if (socket != null) {
914 try {
915 socket.close();
917 catch (Exception e) { /* ignore */ }
918 socket = null;
920 this.setWasAuthenticated(authenticated);
921 authenticated = false;
922 connected = false;
924 throw ex; // Everything stoppped. Now throw the exception.
928 private void initReaderAndWriter() throws XMPPException {
929 try {
930 if (!usingCompression) {
931 reader =
932 new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
933 writer = new BufferedWriter(
934 new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
936 else {
937 try {
938 Class<?> zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream");
939 Constructor<?> constructor =
940 zoClass.getConstructor(OutputStream.class, Integer.TYPE);
941 Object out = constructor.newInstance(socket.getOutputStream(), 9);
942 Method method = zoClass.getMethod("setFlushMode", Integer.TYPE);
943 method.invoke(out, 1);
944 writer =
945 new BufferedWriter(new OutputStreamWriter((OutputStream) out, "UTF-8"));
947 Class<?> ziClass = Class.forName("com.jcraft.jzlib.ZInputStream");
948 constructor = ziClass.getConstructor(InputStream.class);
949 Object in = constructor.newInstance(socket.getInputStream());
950 method = ziClass.getMethod("setFlushMode", Integer.TYPE);
951 method.invoke(in, 1);
952 reader = new BufferedReader(new InputStreamReader((InputStream) in, "UTF-8"));
954 catch (Exception e) {
955 e.printStackTrace();
956 reader = new BufferedReader(
957 new InputStreamReader(socket.getInputStream(), "UTF-8"));
958 writer = new BufferedWriter(
959 new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
963 catch (IOException ioe) {
964 throw new XMPPException(
965 "XMPPError establishing connection with server.",
966 new XMPPError(XMPPError.Condition.remote_server_error,
967 "XMPPError establishing connection with server."),
968 ioe);
971 // If debugging is enabled, we open a window and write out all network traffic.
972 if (configuration.isDebuggerEnabled()) {
973 if (debugger == null) {
974 // Detect the debugger class to use.
975 String className = null;
976 // Use try block since we may not have permission to get a system
977 // property (for example, when an applet).
978 try {
979 className = System.getProperty("smack.debuggerClass");
981 catch (Throwable t) {
982 // Ignore.
984 Class<?> debuggerClass = null;
985 if (className != null) {
986 try {
987 debuggerClass = Class.forName(className);
989 catch (Exception e) {
990 e.printStackTrace();
993 if (debuggerClass == null) {
994 try {
995 debuggerClass =
996 Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger");
998 catch (Exception ex) {
999 try {
1000 debuggerClass =
1001 Class.forName("org.jivesoftware.smack.debugger.LiteDebugger");
1003 catch (Exception ex2) {
1004 ex2.printStackTrace();
1008 // Create a new debugger instance. If an exception occurs then disable the debugging
1009 // option
1010 try {
1011 Constructor<?> constructor = debuggerClass
1012 .getConstructor(XMPPConnection.class, Writer.class, Reader.class);
1013 debugger = (SmackDebugger) constructor.newInstance(this, writer, reader);
1014 reader = debugger.getReader();
1015 writer = debugger.getWriter();
1017 catch (Exception e) {
1018 e.printStackTrace();
1019 DEBUG_ENABLED = false;
1022 else {
1023 // Obtain new reader and writer from the existing debugger
1024 reader = debugger.newConnectionReader(reader);
1025 writer = debugger.newConnectionWriter(writer);
1030 /***********************************************
1031 * TLS code below
1032 **********************************************/
1035 * Returns true if the connection to the server has successfully negotiated TLS. Once TLS
1036 * has been negotiatied the connection has been secured.
1038 * @return true if the connection to the server has successfully negotiated TLS.
1040 public boolean isUsingTLS() {
1041 return usingTLS;
1045 * Returns the SASLAuthentication manager that is responsible for authenticating with
1046 * the server.
1048 * @return the SASLAuthentication manager that is responsible for authenticating with
1049 * the server.
1051 public SASLAuthentication getSASLAuthentication() {
1052 return saslAuthentication;
1056 * Returns the configuration used to connect to the server.
1058 * @return the configuration used to connect to the server.
1060 protected ConnectionConfiguration getConfiguration() {
1061 return configuration;
1065 * Notification message saying that the server supports TLS so confirm the server that we
1066 * want to secure the connection.
1068 * @param required true when the server indicates that TLS is required.
1070 void startTLSReceived(boolean required) {
1071 if (required && configuration.getSecurityMode() ==
1072 ConnectionConfiguration.SecurityMode.disabled)
1074 packetReader.notifyConnectionError(new IllegalStateException(
1075 "TLS required by server but not allowed by connection configuration"));
1076 return;
1079 if (configuration.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) {
1080 // Do not secure the connection using TLS since TLS was disabled
1081 return;
1083 try {
1084 writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
1085 writer.flush();
1087 catch (IOException e) {
1088 packetReader.notifyConnectionError(e);
1093 * The server has indicated that TLS negotiation can start. We now need to secure the
1094 * existing plain connection and perform a handshake. This method won't return until the
1095 * connection has finished the handshake or an error occured while securing the connection.
1097 * @throws Exception if an exception occurs.
1099 void proceedTLSReceived() throws Exception {
1100 SSLContext context = SSLContext.getInstance("TLS");
1101 // Verify certificate presented by the server
1102 context.init(null, // KeyManager not required
1103 new javax.net.ssl.TrustManager[]{new ServerTrustManager(serviceName, configuration)},
1104 new java.security.SecureRandom());
1105 Socket plain = socket;
1106 // Secure the plain connection
1107 socket = context.getSocketFactory().createSocket(plain,
1108 plain.getInetAddress().getHostName(), plain.getPort(), true);
1109 socket.setSoTimeout(0);
1110 socket.setKeepAlive(true);
1111 // Initialize the reader and writer with the new secured version
1112 initReaderAndWriter();
1113 // Proceed to do the handshake
1114 ((SSLSocket) socket).startHandshake();
1116 // Set that TLS was successful
1117 usingTLS = true;
1119 // Set the new writer to use
1120 packetWriter.setWriter(writer);
1121 // Send a new opening stream to the server
1122 packetWriter.openStream();
1126 * Sets the available stream compression methods offered by the server.
1128 * @param methods compression methods offered by the server.
1130 void setAvailableCompressionMethods(Collection methods) {
1131 compressionMethods = methods;
1135 * Returns true if the specified compression method was offered by the server.
1137 * @param method the method to check.
1138 * @return true if the specified compression method was offered by the server.
1140 private boolean hasAvailableCompressionMethod(String method) {
1141 return compressionMethods != null && compressionMethods.contains(method);
1145 * Returns true if network traffic is being compressed. When using stream compression network
1146 * traffic can be reduced up to 90%. Therefore, stream compression is ideal when using a slow
1147 * speed network connection. However, the server will need to use more CPU time in order to
1148 * un/compress network data so under high load the server performance might be affected.<p>
1150 * Note: to use stream compression the smackx.jar file has to be present in the classpath.
1152 * @return true if network traffic is being compressed.
1154 public boolean isUsingCompression() {
1155 return usingCompression;
1159 * Starts using stream compression that will compress network traffic. Traffic can be
1160 * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
1161 * connection. However, the server and the client will need to use more CPU time in order to
1162 * un/compress network data so under high load the server performance might be affected.<p>
1164 * Stream compression has to have been previously offered by the server. Currently only the
1165 * zlib method is supported by the client. Stream compression negotiation has to be done
1166 * before authentication took place.<p>
1168 * Note: to use stream compression the smackx.jar file has to be present in the classpath.
1170 * @return true if stream compression negotiation was successful.
1172 private boolean useCompression() {
1173 // If stream compression was offered by the server and we want to use
1174 // compression then send compression request to the server
1175 if (authenticated) {
1176 throw new IllegalStateException("Compression should be negotiated before authentication.");
1178 try {
1179 Class.forName("com.jcraft.jzlib.ZOutputStream");
1181 catch (ClassNotFoundException e) {
1182 throw new IllegalStateException("Cannot use compression. Add smackx.jar to the classpath");
1184 if (hasAvailableCompressionMethod("zlib")) {
1185 requestStreamCompression();
1186 // Wait until compression is being used or a timeout happened
1187 synchronized (this) {
1188 try {
1189 this.wait(SmackConfiguration.getPacketReplyTimeout() * 5);
1191 catch (InterruptedException e) {
1192 // Ignore.
1195 return usingCompression;
1197 return false;
1201 * Request the server that we want to start using stream compression. When using TLS
1202 * then negotiation of stream compression can only happen after TLS was negotiated. If TLS
1203 * compression is being used the stream compression should not be used.
1205 private void requestStreamCompression() {
1206 try {
1207 writer.write("<compress xmlns='http://jabber.org/protocol/compress'>");
1208 writer.write("<method>zlib</method></compress>");
1209 writer.flush();
1211 catch (IOException e) {
1212 packetReader.notifyConnectionError(e);
1217 * Start using stream compression since the server has acknowledged stream compression.
1219 * @throws Exception if there is an exception starting stream compression.
1221 void startStreamCompression() throws Exception {
1222 // Secure the plain connection
1223 usingCompression = true;
1224 // Initialize the reader and writer with the new secured version
1225 initReaderAndWriter();
1227 // Set the new writer to use
1228 packetWriter.setWriter(writer);
1229 // Send a new opening stream to the server
1230 packetWriter.openStream();
1231 // Notify that compression is being used
1232 synchronized (this) {
1233 this.notify();
1238 * Notifies the XMPP connection that stream compression was denied so that
1239 * the connection process can proceed.
1241 void streamCompressionDenied() {
1242 synchronized (this) {
1243 this.notify();
1247 * Establishes a connection to the XMPP server and performs an automatic login
1248 * only if the previous connection state was logged (authenticated). It basically
1249 * creates and maintains a socket connection to the server.<p>
1251 * Listeners will be preserved from a previous connection if the reconnection
1252 * occurs after an abrupt termination.
1254 * @throws XMPPException if an error occurs while trying to establish the connection.
1255 * Two possible errors can occur which will be wrapped by an XMPPException --
1256 * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
1257 * 502). The error codes and wrapped exceptions can be used to present more
1258 * appropiate error messages to end-users.
1260 public void connect() throws XMPPException {
1261 // Stablishes the connection, readers and writers
1262 connectUsingConfiguration(configuration);
1263 // Automatically makes the login if the user was previouslly connected successfully
1264 // to the server and the connection was terminated abruptly
1265 if (connected && wasAuthenticated) {
1266 // Make the login
1267 try {
1268 if (isAnonymous()) {
1269 // Make the anonymous login
1270 loginAnonymously();
1271 } else {
1272 login(getConfiguration().getUsername(), getConfiguration().getPassword(),
1273 getConfiguration().getResource(), getConfiguration().isSendPresence());
1275 } catch (XMPPException e) {
1276 e.printStackTrace();
1282 * Sets whether the connection has already logged in the server.
1284 * @param wasAuthenticated true if the connection has already been authenticated.
1286 private void setWasAuthenticated(boolean wasAuthenticated) {
1287 if (!this.wasAuthenticated) {
1288 this.wasAuthenticated = wasAuthenticated;