Removed thread from packet writer (SMACK-123).
[Smack.git] / source / org / jivesoftware / smack / XMPPConnection.java
blob3999097e372c1dd50e5cffd4c921255f58745dff
1 /**
2 * $RCSfile$
3 * $Revision$
4 * $Date$
6 * Copyright 2003-2004 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.filter.PacketTypeFilter;
26 import org.jivesoftware.smack.packet.Message;
27 import org.jivesoftware.smack.packet.Packet;
28 import org.jivesoftware.smack.packet.Presence;
29 import org.jivesoftware.smack.packet.XMPPError;
30 import org.jivesoftware.smack.util.DNSUtil;
31 import org.jivesoftware.smack.util.StringUtils;
33 import javax.net.SocketFactory;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.SSLSocket;
36 import java.io.*;
37 import java.lang.ref.WeakReference;
38 import java.lang.reflect.Constructor;
39 import java.lang.reflect.Method;
40 import java.net.Socket;
41 import java.net.UnknownHostException;
42 import java.util.*;
44 /**
45 * Creates a connection to a XMPP server. A simple use of this API might
46 * look like the following:
47 * <pre>
48 * // Create a connection to the jivesoftware.com XMPP server.
49 * XMPPConnection con = new XMPPConnection("jivesoftware.com");
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 = con.createChat("jdoe@jabber.org");
54 * chat.sendMessage("Hey, how's it going?");
55 * </pre>
57 * @author Matt Tucker
59 public class XMPPConnection {
61 /**
62 * Value that indicates whether debugging is enabled. When enabled, a debug
63 * window will apear for each new connection that will contain the following
64 * information:<ul>
65 * <li> Client Traffic -- raw XML traffic generated by Smack and sent to the server.
66 * <li> Server Traffic -- raw XML traffic sent by the server to the client.
67 * <li> Interpreted Packets -- shows XML packets from the server as parsed by Smack.
68 * </ul>
70 * Debugging can be enabled by setting this field to true, or by setting the Java system
71 * property <tt>smack.debugEnabled</tt> to true. The system property can be set on the
72 * command line such as "java SomeApp -Dsmack.debugEnabled=true".
74 public static boolean DEBUG_ENABLED = false;
76 private static List connectionEstablishedListeners = new ArrayList();
78 static {
79 // Use try block since we may not have permission to get a system
80 // property (for example, when an applet).
81 try {
82 DEBUG_ENABLED = Boolean.getBoolean("smack.debugEnabled");
84 catch (Exception e) {
85 // Ignore.
87 // Ensure the SmackConfiguration class is loaded by calling a method in it.
88 SmackConfiguration.getVersion();
90 private SmackDebugger debugger = null;
92 /**
93 * IP address or host name of the server. This information is only used when
94 * creating new socket connections to the server. If this information is not
95 * configured then it will be assumed that the host name matches the service name.
97 String host;
98 int port;
99 Socket socket;
102 * Hostname of the XMPP server. Usually servers use the same service name as the name
103 * of the server. However, there are some servers like google where host would be
104 * talk.google.com and the serviceName would be gmail.com.
106 String serviceName;
108 String connectionID;
109 private String user = null;
110 private boolean connected = false;
111 private boolean authenticated = false;
112 private boolean anonymous = false;
113 private boolean usingTLS = false;
115 PacketWriter packetWriter;
116 PacketReader packetReader;
118 Roster roster = null;
119 private AccountManager accountManager = null;
120 private SASLAuthentication saslAuthentication = new SASLAuthentication(this);
122 Writer writer;
123 Reader reader;
126 * A map between JIDs and the most recently created Chat object with that JID.
127 * Reference to the Chat is stored via a WeakReference so that the map
128 * does not interfere with garbage collection. The map of chats must be stored
129 * with each connection.
131 Map chats = Collections.synchronizedMap(new HashMap());
134 * Collection of available stream compression methods offered by the server.
136 private Collection compressionMethods;
138 * Flag that indicates if stream compression is actually in use.
140 private boolean usingCompression;
142 * Holds the initial configuration used while creating the connection.
144 private ConnectionConfiguration configuration;
147 * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be
148 * performed to try to determine the IP address and port corresponding to the
149 * serviceName; if that lookup fails, it's assumed that server resides at serviceName
150 * with the default port of 5222. This is the preferred constructor for connecting
151 * to an XMPP server.
153 * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
154 * @throws XMPPException if an error occurs while trying to establish the connection.
155 * Two possible errors can occur which will be wrapped by an XMPPException --
156 * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
157 * 502). The error codes and wrapped exceptions can be used to present more
158 * appropiate error messages to end-users.
160 public XMPPConnection(String serviceName) throws XMPPException {
161 // Perform DNS lookup to get host and port to use
162 DNSUtil.HostAddress address = DNSUtil.resolveXMPPDomain(serviceName);
163 // Create the configuration for this new connection
164 ConnectionConfiguration config =
165 new ConnectionConfiguration(address.getHost(), address.getPort(), serviceName);
166 config.setTLSEnabled(true);
167 config.setCompressionEnabled(false);
168 config.setSASLAuthenticationEnabled(true);
169 config.setDebuggerEnabled(DEBUG_ENABLED);
170 // Set the new connection configuration
171 connectUsingConfiguration(config, null);
175 * Creates a new connection to the XMPP server at the specifiec host and port.
177 * @param host the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
178 * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
179 * @throws XMPPException if an error occurs while trying to establish the connection.
180 * Two possible errors can occur which will be wrapped by an XMPPException --
181 * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
182 * 502). The error codes and wrapped exceptions can be used to present more
183 * appropiate error messages to end-users.
185 public XMPPConnection(String host, int port) throws XMPPException {
186 // Create the configuration for this new connection
187 ConnectionConfiguration config = new ConnectionConfiguration(host, port);
188 config.setTLSEnabled(true);
189 config.setCompressionEnabled(false);
190 config.setSASLAuthenticationEnabled(true);
191 config.setDebuggerEnabled(DEBUG_ENABLED);
192 // Set the new connection configuration
193 connectUsingConfiguration(config, null);
197 * Creates a new connection to the specified XMPP server on the given host and port.
199 * @param host the host name, or null for the loopback address.
200 * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
201 * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
202 * @throws XMPPException if an error occurs while trying to establish the connection.
203 * Two possible errors can occur which will be wrapped by an XMPPException --
204 * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
205 * 502). The error codes and wrapped exceptions can be used to present more
206 * appropiate error messages to end-users.
208 public XMPPConnection(String host, int port, String serviceName) throws XMPPException {
209 // Create the configuration for this new connection
210 ConnectionConfiguration config = new ConnectionConfiguration(host, port, serviceName);
211 config.setTLSEnabled(true);
212 config.setCompressionEnabled(false);
213 config.setSASLAuthenticationEnabled(true);
214 config.setDebuggerEnabled(DEBUG_ENABLED);
215 // Set the new connection configuration
216 connectUsingConfiguration(config, null);
220 * Creates a new connection to the specified XMPP server on the given port using the
221 * specified SocketFactory.<p>
223 * A custom SocketFactory allows fine-grained control of the actual connection to the
224 * XMPP server. A typical use for a custom SocketFactory is when connecting through a
225 * SOCKS proxy.
227 * @param host the host name, or null for the loopback address.
228 * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
229 * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
230 * @param socketFactory a SocketFactory that will be used to create the socket to the XMPP
231 * server.
232 * @throws XMPPException if an error occurs while trying to establish the connection.
233 * Two possible errors can occur which will be wrapped by an XMPPException --
234 * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
235 * 502). The error codes and wrapped exceptions can be used to present more
236 * appropiate error messages to end-users.
238 public XMPPConnection(String host, int port, String serviceName, SocketFactory socketFactory)
239 throws XMPPException
241 // Create the configuration for this new connection
242 ConnectionConfiguration config = new ConnectionConfiguration(host, port, serviceName);
243 config.setTLSEnabled(true);
244 config.setCompressionEnabled(false);
245 config.setSASLAuthenticationEnabled(true);
246 config.setDebuggerEnabled(DEBUG_ENABLED);
247 // Set the new connection configuration
248 connectUsingConfiguration(config, socketFactory);
251 public XMPPConnection(ConnectionConfiguration config) throws XMPPException {
252 // Set the new connection configuration
253 connectUsingConfiguration(config, null);
256 public XMPPConnection(ConnectionConfiguration config, SocketFactory socketFactory)
257 throws XMPPException {
258 // Set the new connection configuration
259 connectUsingConfiguration(config, socketFactory);
262 private void connectUsingConfiguration(ConnectionConfiguration config,
263 SocketFactory socketFactory) throws XMPPException {
264 this.host = config.getHost();
265 this.port = config.getPort();
266 try {
267 if (socketFactory == null) {
268 this.socket = new Socket(host, port);
270 else {
271 this.socket = socketFactory.createSocket(host, port);
274 catch (UnknownHostException uhe) {
275 throw new XMPPException(
276 "Could not connect to " + host + ":" + port + ".",
277 new XMPPError(504),
278 uhe);
280 catch (IOException ioe) {
281 throw new XMPPException(
282 "XMPPError connecting to " + host + ":" + port + ".",
283 new XMPPError(502),
284 ioe);
286 this.serviceName = config.getServiceName();
287 try {
288 // Keep a copy to be sure that once the configuration has been passed to the
289 // constructor it cannot be modified
290 this.configuration = (ConnectionConfiguration) config.clone();
292 catch (CloneNotSupportedException e) {}
293 init();
297 * Package-private default constructor. This constructor is only intended
298 * for unit testing. Normal classes extending XMPPConnection should override
299 * one of the other constructors.
301 XMPPConnection() {
305 * Returns the connection ID for this connection, which is the value set by the server
306 * when opening a XMPP stream. If the server does not set a connection ID, this value
307 * will be null.
309 * @return the ID of this connection returned from the XMPP server.
311 public String getConnectionID() {
312 return connectionID;
316 * Returns the name of the service provided by the XMPP server for this connection. After
317 * authenticating with the server the returned value may be different.
319 * @return the name of the service provided by the XMPP server.
321 public String getServiceName() {
322 return serviceName;
326 * Returns the host name of the server where the XMPP server is running. This would be the
327 * IP address of the server or a name that may be resolved by a DNS server.
329 * @return the host name of the server where the XMPP server is running.
331 public String getHost() {
332 return host;
336 * Returns the port number of the XMPP server for this connection. The default port
337 * for normal connections is 5222. The default port for SSL connections is 5223.
339 * @return the port number of the XMPP server.
341 public int getPort() {
342 return port;
346 * Returns the full XMPP address of the user that is logged in to the connection or
347 * <tt>null</tt> if not logged in yet. An XMPP address is in the form
348 * username@server/resource.
350 * @return the full XMPP address of the user logged in.
352 public String getUser() {
353 if (!isAuthenticated()) {
354 return null;
356 return user;
360 * Logs in to the server using the strongest authentication mode supported by
361 * the server, then set our presence to available. If more than five seconds
362 * (default timeout) elapses in each step of the authentication process without
363 * a response from the server, or if an error occurs, a XMPPException will be thrown.
365 * @param username the username.
366 * @param password the password.
367 * @throws XMPPException if an error occurs.
369 public void login(String username, String password) throws XMPPException {
370 login(username, password, "Smack");
374 * Logs in to the server using the strongest authentication mode supported by
375 * the server, then sets presence to available. If more than five seconds
376 * (default timeout) elapses in each step of the authentication process without
377 * a response from the server, or if an error occurs, a XMPPException will be thrown.
379 * @param username the username.
380 * @param password the password.
381 * @param resource the resource.
382 * @throws XMPPException if an error occurs.
383 * @throws IllegalStateException if not connected to the server, or already logged in
384 * to the serrver.
386 public synchronized void login(String username, String password, String resource)
387 throws XMPPException
389 login(username, password, resource, true);
393 * Logs in to the server using the strongest authentication mode supported by
394 * the server. If the server supports SASL authentication then the user will be
395 * authenticated using SASL if not Non-SASL authentication will be tried. An available
396 * presence may optionally be sent. If <tt>sendPresence</tt>
397 * is false, a presence packet must be sent manually later. If more than five seconds
398 * (default timeout) elapses in each step of the authentication process without a
399 * response from the server, or if an error occurs, a XMPPException will be thrown.
401 * @param username the username.
402 * @param password the password.
403 * @param resource the resource.
404 * @param sendPresence if <tt>true</tt> an available presence will be sent automatically
405 * after login is completed.
406 * @throws XMPPException if an error occurs.
407 * @throws IllegalStateException if not connected to the server, or already logged in
408 * to the serrver.
410 public synchronized void login(String username, String password, String resource,
411 boolean sendPresence) throws XMPPException
413 if (!isConnected()) {
414 throw new IllegalStateException("Not connected to server.");
416 if (authenticated) {
417 throw new IllegalStateException("Already logged in to server.");
419 // Do partial version of nameprep on the username.
420 username = username.toLowerCase().trim();
422 String response = null;
423 if (configuration.isSASLAuthenticationEnabled() &&
424 saslAuthentication.hasNonAnonymousAuthentication()) {
425 // Authenticate using SASL
426 response = saslAuthentication.authenticate(username, password, resource);
428 else {
429 // Authenticate using Non-SASL
430 response = new NonSASLAuthentication(this).authenticate(username, password, resource);
433 // Set the user.
434 if (response != null) {
435 this.user = response;
436 // Update the serviceName with the one returned by the server
437 this.serviceName = StringUtils.parseServer(response);
439 else {
440 this.user = username + "@" + this.serviceName;
441 if (resource != null) {
442 this.user += "/" + resource;
446 // If compression is enabled then request the server to use stream compression
447 if (configuration.isCompressionEnabled()) {
448 useCompression();
451 // Create the roster.
452 this.roster = new Roster(this);
453 roster.reload();
455 // Set presence to online.
456 if (sendPresence) {
457 packetWriter.sendPacket(new Presence(Presence.Type.AVAILABLE));
460 // Indicate that we're now authenticated.
461 authenticated = true;
462 anonymous = false;
464 // If debugging is enabled, change the the debug window title to include the
465 // name we are now logged-in as.
466 // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
467 // will be null
468 if (configuration.isDebuggerEnabled() && debugger != null) {
469 debugger.userHasLogged(user);
474 * Logs in to the server anonymously. Very few servers are configured to support anonymous
475 * authentication, so it's fairly likely logging in anonymously will fail. If anonymous login
476 * does succeed, your XMPP address will likely be in the form "server/123ABC" (where "123ABC"
477 * is a random value generated by the server).
479 * @throws XMPPException if an error occurs or anonymous logins are not supported by the server.
480 * @throws IllegalStateException if not connected to the server, or already logged in
481 * to the serrver.
483 public synchronized void loginAnonymously() throws XMPPException {
484 if (!isConnected()) {
485 throw new IllegalStateException("Not connected to server.");
487 if (authenticated) {
488 throw new IllegalStateException("Already logged in to server.");
491 String response = null;
492 if (configuration.isSASLAuthenticationEnabled() &&
493 saslAuthentication.hasAnonymousAuthentication()) {
494 response = saslAuthentication.authenticateAnonymously();
496 else {
497 // Authenticate using Non-SASL
498 response = new NonSASLAuthentication(this).authenticateAnonymously();
501 // Set the user value.
502 this.user = response;
503 // Update the serviceName with the one returned by the server
504 this.serviceName = StringUtils.parseServer(response);
506 // If compression is enabled then request the server to use stream compression
507 if (configuration.isCompressionEnabled()) {
508 useCompression();
511 // Anonymous users can't have a roster.
512 roster = null;
514 // Set presence to online.
515 packetWriter.sendPacket(new Presence(Presence.Type.AVAILABLE));
517 // Indicate that we're now authenticated.
518 authenticated = true;
519 anonymous = true;
521 // If debugging is enabled, change the the debug window title to include the
522 // name we are now logged-in as.
523 // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
524 // will be null
525 if (configuration.isDebuggerEnabled() && debugger != null) {
526 debugger.userHasLogged(user);
531 * Returns the roster for the user logged into the server. If the user has not yet
532 * logged into the server (or if the user is logged in anonymously), this method will return
533 * <tt>null</tt>.
535 * @return the user's roster, or <tt>null</tt> if the user has not logged in yet.
537 public Roster getRoster() {
538 if (roster == null) {
539 return null;
541 // If this is the first time the user has asked for the roster after calling
542 // login, we want to wait for the server to send back the user's roster. This
543 // behavior shields API users from having to worry about the fact that roster
544 // operations are asynchronous, although they'll still have to listen for
545 // changes to the roster. Note: because of this waiting logic, internal
546 // Smack code should be wary about calling the getRoster method, and may need to
547 // access the roster object directly.
548 if (!roster.rosterInitialized) {
549 try {
550 synchronized (roster) {
551 long waitTime = SmackConfiguration.getPacketReplyTimeout();
552 long start = System.currentTimeMillis();
553 while (!roster.rosterInitialized) {
554 if (waitTime <= 0) {
555 break;
557 roster.wait(waitTime);
558 long now = System.currentTimeMillis();
559 waitTime -= now - start;
560 start = now;
564 catch (InterruptedException ie) {
565 // Ignore.
568 return roster;
572 * Returns an account manager instance for this connection.
574 * @return an account manager for this connection.
576 public synchronized AccountManager getAccountManager() {
577 if (accountManager == null) {
578 accountManager = new AccountManager(this);
580 return accountManager;
584 * Creates a new chat with the specified participant. The participant should
585 * be a valid XMPP user such as <tt>jdoe@jivesoftware.com</tt> or
586 * <tt>jdoe@jivesoftware.com/work</tt>.
588 * @param participant the person to start the conversation with.
589 * @return a new Chat object.
591 public Chat createChat(String participant) {
592 if (!isConnected()) {
593 throw new IllegalStateException("Not connected to server.");
595 return new Chat(this, participant);
599 * Creates a new group chat connected to the specified room. The room name
600 * should be full address, such as <tt>room@chat.example.com</tt>.
601 * <p>
602 * Most XMPP servers use a sub-domain for the chat service (eg chat.example.com
603 * for the XMPP server example.com). You must ensure that the room address you're
604 * trying to connect to includes the proper chat sub-domain.
606 * @param room the fully qualifed name of the room.
607 * @return a new GroupChat object.
609 public GroupChat createGroupChat(String room) {
610 if (!isConnected()) {
611 throw new IllegalStateException("Not connected to server.");
613 return new GroupChat(this, room);
617 * Returns true if currently connected to the XMPP server.
619 * @return true if connected.
621 public boolean isConnected() {
622 return connected;
626 * Returns true if the connection is a secured one, such as an SSL connection or
627 * if TLS was negotiated successfully.
629 * @return true if a secure connection to the server.
631 public boolean isSecureConnection() {
632 return isUsingTLS();
636 * Returns true if currently authenticated by successfully calling the login method.
638 * @return true if authenticated.
640 public boolean isAuthenticated() {
641 return authenticated;
645 * Returns true if currently authenticated anonymously.
647 * @return true if authenticated anonymously.
649 public boolean isAnonymous() {
650 return anonymous;
654 * Closes the connection by setting presence to unavailable then closing the stream to
655 * the XMPP server. Once a connection has been closed, it cannot be re-opened.
657 public void close() {
658 // Set presence to offline.
659 packetWriter.sendPacket(new Presence(Presence.Type.UNAVAILABLE));
660 packetReader.shutdown();
661 packetWriter.shutdown();
662 // Wait 150 ms for processes to clean-up, then shutdown.
663 try {
664 Thread.sleep(150);
666 catch (Exception e) {
667 // Ignore.
670 // Close down the readers and writers.
671 if (reader != null)
673 try { reader.close(); } catch (Throwable ignore) { /* ignore */ }
674 reader = null;
676 if (writer != null)
678 try { writer.close(); } catch (Throwable ignore) { /* ignore */ }
679 writer = null;
682 try {
683 socket.close();
685 catch (Exception e) {
686 // Ignore.
688 authenticated = false;
689 connected = false;
693 * Sends the specified packet to the server.
695 * @param packet the packet to send.
697 public void sendPacket(Packet packet) {
698 if (!isConnected()) {
699 throw new IllegalStateException("Not connected to server.");
701 if (packet == null) {
702 throw new NullPointerException("Packet is null.");
704 packetWriter.sendPacket(packet);
708 * Registers a packet listener with this connection. A packet filter determines
709 * which packets will be delivered to the listener.
711 * @param packetListener the packet listener to notify of new packets.
712 * @param packetFilter the packet filter to use.
714 public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
715 if (!isConnected()) {
716 throw new IllegalStateException("Not connected to server.");
718 packetReader.addPacketListener(packetListener, packetFilter);
722 * Removes a packet listener from this connection.
724 * @param packetListener the packet listener to remove.
726 public void removePacketListener(PacketListener packetListener) {
727 packetReader.removePacketListener(packetListener);
731 * Registers a packet listener with this connection. The listener will be
732 * notified of every packet that this connection sends. A packet filter determines
733 * which packets will be delivered to the listener. Note that the thread
734 * that writes packets will be used to invoke the listeners. Therefore, each
735 * packet listener should complete all operations quickly or use a different
736 * thread for processing.
738 * @param packetListener the packet listener to notify of sent packets.
739 * @param packetFilter the packet filter to use.
741 public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) {
742 if (!isConnected()) {
743 throw new IllegalStateException("Not connected to server.");
745 packetWriter.addPacketListener(packetListener, packetFilter);
749 * Removes a packet listener from this connection.
751 * @param packetListener the packet listener to remove.
753 public void removePacketWriterListener(PacketListener packetListener) {
754 packetWriter.removePacketListener(packetListener);
758 * Registers a packet interceptor with this connection. The interceptor will be
759 * invoked every time a packet is about to be sent by this connection. Interceptors
760 * may modify the packet to be sent. A packet filter determines which packets
761 * will be delivered to the interceptor.
763 * @param packetInterceptor the packet interceptor to notify of packets about to be sent.
764 * @param packetFilter the packet filter to use.
766 public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor,
767 PacketFilter packetFilter) {
768 if (!isConnected()) {
769 throw new IllegalStateException("Not connected to server.");
771 packetWriter.addPacketInterceptor(packetInterceptor, packetFilter);
775 * Removes a packet interceptor.
777 * @param packetInterceptor the packet interceptor to remove.
779 public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) {
780 packetWriter.removePacketInterceptor(packetInterceptor);
784 * Creates a new packet collector for this connection. A packet filter determines
785 * which packets will be accumulated by the collector.
787 * @param packetFilter the packet filter to use.
788 * @return a new packet collector.
790 public PacketCollector createPacketCollector(PacketFilter packetFilter) {
791 return packetReader.createPacketCollector(packetFilter);
795 * Adds a connection listener to this connection that will be notified when
796 * the connection closes or fails.
798 * @param connectionListener a connection listener.
800 public void addConnectionListener(ConnectionListener connectionListener) {
801 if (connectionListener == null) {
802 return;
804 synchronized (packetReader.connectionListeners) {
805 if (!packetReader.connectionListeners.contains(connectionListener)) {
806 packetReader.connectionListeners.add(connectionListener);
812 * Removes a connection listener from this connection.
814 * @param connectionListener a connection listener.
816 public void removeConnectionListener(ConnectionListener connectionListener) {
817 synchronized (packetReader.connectionListeners) {
818 packetReader.connectionListeners.remove(connectionListener);
823 * Adds a connection established listener that will be notified when a new connection
824 * is established.
826 * @param connectionEstablishedListener a listener interested on connection established events.
828 public static void addConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) {
829 synchronized (connectionEstablishedListeners) {
830 if (!connectionEstablishedListeners.contains(connectionEstablishedListener)) {
831 connectionEstablishedListeners.add(connectionEstablishedListener);
837 * Removes a listener on new established connections.
839 * @param connectionEstablishedListener a listener interested on connection established events.
841 public static void removeConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) {
842 synchronized (connectionEstablishedListeners) {
843 connectionEstablishedListeners.remove(connectionEstablishedListener);
848 * Initializes the connection by creating a packet reader and writer and opening a
849 * XMPP stream to the server.
851 * @throws XMPPException if establishing a connection to the server fails.
853 private void init() throws XMPPException {
854 // Set the reader and writer instance variables
855 initReaderAndWriter();
859 packetWriter = new PacketWriter(this);
860 packetReader = new PacketReader(this);
862 // If debugging is enabled, we should start the thread that will listen for
863 // all packets and then log them.
864 if (configuration.isDebuggerEnabled()) {
865 packetReader.addPacketListener(debugger.getReaderListener(), null);
866 if (debugger.getWriterListener() != null) {
867 packetWriter.addPacketListener(debugger.getWriterListener(), null);
870 // Start the packet writer. This will open a XMPP stream to the server
871 packetWriter.startup();
872 // Start the packet reader. The startup() method will block until we
873 // get an opening stream packet back from server.
874 packetReader.startup();
876 // Make note of the fact that we're now connected.
877 connected = true;
879 // Notify that a new connection has been established
880 connectionEstablished(this);
882 // Add a listener for all message packets so that we can deliver errant
883 // messages to the best Chat instance available.
884 addPacketListener(new PacketListener() {
885 public void processPacket(Packet packet) {
886 Message message = (Message)packet;
887 // Ignore any messages with a thread ID, as they will likely
888 // already be associated with a Chat. This will miss messages
889 // with new thread ID values, but we can only assume that a
890 // listener is registered to deal with this case.
891 if (message.getThread() == null &&
892 message.getType() != Message.Type.GROUP_CHAT &&
893 message.getType() != Message.Type.HEADLINE) {
894 WeakReference chatRef = (WeakReference)chats.get(
895 StringUtils.parseBareAddress(message.getFrom()));
896 if (chatRef != null) {
897 // Do some extra clean-up if the reference was cleared.
898 Chat chat;
899 if ((chat = (Chat)chatRef.get()) == null) {
900 chats.remove(message.getFrom());
902 else {
903 chat.deliver(message);
908 }, new PacketTypeFilter(Message.class));
910 catch (XMPPException ex) {
911 // An exception occurred in setting up the connection. Make sure we shut down the
912 // readers and writers and close the socket.
914 if (packetWriter != null) {
915 try { packetWriter.shutdown(); } catch (Throwable ignore) { /* ignore */ }
916 packetWriter = null;
918 if (packetReader != null) {
919 try { packetReader.shutdown(); } catch (Throwable ignore) { /* ignore */ }
920 packetReader = null;
922 if (reader != null) {
923 try { reader.close(); } catch (Throwable ignore) { /* ignore */ }
924 reader = null;
926 if (writer != null) {
927 try { writer.close(); } catch (Throwable ignore) { /* ignore */}
928 writer = null;
930 if (socket != null) {
931 try { socket.close(); } catch (Exception e) { /* ignore */ }
932 socket = null;
934 authenticated = false;
935 connected = false;
937 throw ex; // Everything stoppped. Now throw the exception.
941 private void initReaderAndWriter() throws XMPPException {
942 try {
943 if (!usingCompression) {
944 reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
945 writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
947 else {
948 try {
949 Class zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream");
950 //ZOutputStream out = new ZOutputStream(socket.getOutputStream(), JZlib.Z_BEST_COMPRESSION);
951 Constructor constructor =
952 zoClass.getConstructor(new Class[]{OutputStream.class, Integer.TYPE});
953 Object out = constructor.newInstance(new Object[] {socket.getOutputStream(), new Integer(9)});
954 //out.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
955 Method method = zoClass.getMethod("setFlushMode", new Class[] {Integer.TYPE});
956 method.invoke(out, new Object[] {new Integer(1)});
957 writer = new BufferedWriter(new OutputStreamWriter((OutputStream) out, "UTF-8"));
959 Class ziClass = Class.forName("com.jcraft.jzlib.ZInputStream");
960 //ZInputStream in = new ZInputStream(socket.getInputStream());
961 constructor = ziClass.getConstructor(new Class[]{InputStream.class});
962 Object in = constructor.newInstance(new Object[] {socket.getInputStream()});
963 //in.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
964 method = ziClass.getMethod("setFlushMode", new Class[] {Integer.TYPE});
965 method.invoke(in, new Object[] {new Integer(1)});
966 reader = new BufferedReader(new InputStreamReader((InputStream) in, "UTF-8"));
968 catch (Exception e) {
969 e.printStackTrace();
970 reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
971 writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
975 catch (IOException ioe) {
976 throw new XMPPException(
977 "XMPPError establishing connection with server.",
978 new XMPPError(502),
979 ioe);
982 // If debugging is enabled, we open a window and write out all network traffic.
983 if (configuration.isDebuggerEnabled()) {
984 if (debugger == null) {
985 // Detect the debugger class to use.
986 String className = null;
987 // Use try block since we may not have permission to get a system
988 // property (for example, when an applet).
989 try {
990 className = System.getProperty("smack.debuggerClass");
992 catch (Throwable t) {
994 Class debuggerClass = null;
995 if (className != null) {
996 try {
997 debuggerClass = Class.forName(className);
999 catch (Exception e) {
1000 e.printStackTrace();
1003 if (debuggerClass == null) {
1004 try {
1005 debuggerClass =
1006 Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger");
1008 catch (Exception ex) {
1009 try {
1010 debuggerClass = Class.forName("org.jivesoftware.smack.debugger.LiteDebugger");
1012 catch (Exception ex2) {
1013 ex2.printStackTrace();
1017 // Create a new debugger instance. If an exception occurs then disable the debugging
1018 // option
1019 try {
1020 Constructor constructor =
1021 debuggerClass.getConstructor(
1022 new Class[] { XMPPConnection.class, Writer.class, Reader.class });
1023 debugger = (SmackDebugger) constructor
1024 .newInstance(new Object[]{this, writer, reader});
1025 reader = debugger.getReader();
1026 writer = debugger.getWriter();
1028 catch (Exception e) {
1029 e.printStackTrace();
1030 DEBUG_ENABLED = false;
1033 else {
1034 // Obtain new reader and writer from the existing debugger
1035 reader = debugger.newConnectionReader(reader);
1036 writer = debugger.newConnectionWriter(writer);
1042 * Fires listeners on connection established events.
1044 private static void connectionEstablished(XMPPConnection connection) {
1045 ConnectionEstablishedListener[] listeners = null;
1046 synchronized (connectionEstablishedListeners) {
1047 listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()];
1048 connectionEstablishedListeners.toArray(listeners);
1050 for (int i = 0; i < listeners.length; i++) {
1051 listeners[i].connectionEstablished(connection);
1055 /***********************************************
1056 * TLS code below
1057 **********************************************/
1060 * Returns true if the connection to the server has successfully negotiated TLS. Once TLS
1061 * has been negotiatied the connection has been secured.
1063 * @return true if the connection to the server has successfully negotiated TLS.
1065 public boolean isUsingTLS() {
1066 return usingTLS;
1070 * Returns the SASLAuthentication manager that is responsible for authenticating with
1071 * the server.
1073 * @return the SASLAuthentication manager that is responsible for authenticating with
1074 * the server.
1076 public SASLAuthentication getSASLAuthentication() {
1077 return saslAuthentication;
1081 * Notification message saying that the server supports TLS so confirm the server that we
1082 * want to secure the connection.
1084 void startTLSReceived() {
1085 if (!configuration.isTLSEnabled()) {
1086 // Do not secure the connection using TLS since TLS was disabled
1087 return;
1089 try {
1090 writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
1091 writer.flush();
1093 catch (IOException e) {
1094 packetReader.notifyConnectionError(e);
1099 * The server has indicated that TLS negotiation can start. We now need to secure the
1100 * existing plain connection and perform a handshake. This method won't return until the
1101 * connection has finished the handshake or an error occured while securing the connection.
1103 void proceedTLSReceived() throws Exception {
1104 SSLContext context = SSLContext.getInstance("TLS");
1105 // Verify certificate presented by the server
1106 context.init(null, // KeyManager not required
1107 new javax.net.ssl.TrustManager[]{new ServerTrustManager(serviceName, configuration)},
1108 new java.security.SecureRandom());
1109 Socket plain = socket;
1110 // Secure the plain connection
1111 socket = context.getSocketFactory().createSocket(plain,
1112 plain.getInetAddress().getHostName(), plain.getPort(), true);
1113 socket.setSoTimeout(0);
1114 socket.setKeepAlive(true);
1115 // Initialize the reader and writer with the new secured version
1116 initReaderAndWriter();
1117 // Proceed to do the handshake
1118 ((SSLSocket) socket).startHandshake();
1120 // Set that TLS was successful
1121 usingTLS = true;
1123 // Set the new writer to use
1124 packetWriter.setWriter(writer);
1125 // Send a new opening stream to the server
1126 packetWriter.openStream();
1130 * Sets the available stream compression methods offered by the server.
1132 * @param methods compression methods offered by the server.
1134 void setAvailableCompressionMethods(Collection methods) {
1135 compressionMethods = methods;
1139 * Returns true if the specified compression method was offered by the server.
1141 * @param method the method to check.
1142 * @return true if the specified compression method was offered by the server.
1144 private boolean hasAvailableCompressionMethod(String method) {
1145 return compressionMethods != null && compressionMethods.contains(method);
1149 * Returns true if network traffic is being compressed. When using stream compression network
1150 * traffic can be reduced up to 90%. Therefore, stream compression is ideal when using a slow
1151 * speed network connection. However, the server will need to use more CPU time in order to
1152 * un/compress network data so under high load the server performance might be affected.<p>
1154 * Note: To use stream compression the smackx.jar file has to be present in the classpath.
1156 * @return true if network traffic is being compressed.
1158 public boolean isUsingCompression() {
1159 return usingCompression;
1163 * Starts using stream compression that will compress network traffic. Traffic can be
1164 * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
1165 * connection. However, the server and the client will need to use more CPU time in order to
1166 * un/compress network data so under high load the server performance might be affected.<p>
1168 * Stream compression has to have been previously offered by the server. Currently only the
1169 * zlib method is supported by the client. Stream compression negotiation has to be done
1170 * before authentication took place.<p>
1172 * Note: To use stream compression the smackx.jar file has to be present in the classpath.
1174 * @return true if stream compression negotiation was successful.
1176 private boolean useCompression() {
1177 // If stream compression was offered by the server and we want to use
1178 // compression then send compression request to the server
1179 if (authenticated) {
1180 throw new IllegalStateException("Compression should be negotiated before authentication.");
1182 try {
1183 Class.forName("com.jcraft.jzlib.ZOutputStream");
1185 catch (ClassNotFoundException e) {
1186 throw new IllegalStateException("Cannot use compression. Add smackx.jar to the classpath");
1188 if (hasAvailableCompressionMethod("zlib")) {
1189 requestStreamCompression();
1190 // Wait until compression is being used or a timeout happened
1191 synchronized (this) {
1192 try {
1193 this.wait(SmackConfiguration.getPacketReplyTimeout() * 5);
1195 catch (InterruptedException e) {}
1197 return usingCompression;
1199 return false;
1203 * Request the server that we want to start using stream compression. When using TLS
1204 * then negotiation of stream compression can only happen after TLS was negotiated. If TLS
1205 * compression is being used the stream compression should not be used.
1207 private void requestStreamCompression() {
1208 try {
1209 writer.write("<compress xmlns='http://jabber.org/protocol/compress'>");
1210 writer.write("<method>zlib</method></compress>");
1211 writer.flush();
1213 catch (IOException e) {
1214 packetReader.notifyConnectionError(e);
1219 * Start using stream compression since the server has acknowledged 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();
1237 void streamCompressionDenied() {
1238 // Notify that compression has been denied
1239 synchronized (this) {
1240 this.notify();