/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2002-2003 Jive Software. All rights reserved. * ==================================================================== * The Jive Software License (based on Apache Software License, Version 1.1) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by * Jive Software (http://www.jivesoftware.com)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Smack" and "Jive Software" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please * contact webmaster@jivesoftware.com. * * 5. Products derived from this software may not be called "Smack", * nor may "Smack" appear in their name, without prior written * permission of Jive Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jivesoftware.smack; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.debugger.*; import org.jivesoftware.smack.filter.*; import java.lang.reflect.Constructor; import java.net.*; import java.util.*; import java.io.*; /** * Creates a connection to a XMPP server. A simple use of this API might * look like the following: *
* // Create a connection to the jivesoftware.com XMPP server. * XMPPConnection con = new XMPPConnection("jivesoftware.com"); * // 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 = con.createChat("jdoe@jabber.org"); * chat.sendMessage("Hey, how's it going?"); ** * @author Matt Tucker */ public class XMPPConnection { /** * Value that indicates whether debugging is enabled. When enabled, a debug * window will apear for each new connection that will contain the following * information:
* Most XMPP servers use a sub-domain for the chat service (eg chat.example.com * for the XMPP server example.com). You must ensure that the room address you're * trying to connect to includes the proper chat sub-domain. * * @param room the fully qualifed name of the room. * @return a new GroupChat object. */ public GroupChat createGroupChat(String room) { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } return new GroupChat(this, room); } /** * Returns true if currently connected to the XMPP server. * * @return true if connected. */ public boolean isConnected() { return connected; } /** * Returns true if the connection is a secured one, such as an SSL connection. * * @return true if a secure connection to the server. */ public boolean isSecureConnection() { return false; } /** * 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; } /** * Closes the connection by setting presence to unavailable then closing the stream to * the XMPP server. Once a connection has been closed, it cannot be re-opened. */ public void close() { // Set presence to offline. packetWriter.sendPacket(new Presence(Presence.Type.UNAVAILABLE)); packetReader.shutdown(); packetWriter.shutdown(); // Wait 150 ms for processes to clean-up, then shutdown. try { Thread.sleep(150); } catch (Exception e) { } try { socket.close(); } catch (Exception e) { } authenticated = false; connected = false; } /** * 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."); } if (packet == null) { throw new NullPointerException("Packet is null."); } packetWriter.sendPacket(packet); } /** * Registers a packet listener with this connection. A packet filter determines * which packets will be delivered to the listener. * * @param packetListener the packet listener to notify of new packets. * @param packetFilter the packet filter to use. */ public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } packetReader.addPacketListener(packetListener, packetFilter); } /** * Removes a packet listener from this connection. * * @param packetListener the packet listener to remove. */ public void removePacketListener(PacketListener packetListener) { packetReader.removePacketListener(packetListener); } /** * Registers a packet listener with this connection. The listener will be * notified of every packet that this connection sends. A packet filter determines * which packets will be delivered to the listener. * * @param packetListener the packet listener to notify of sent packets. * @param packetFilter the packet filter to use. */ public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) { if (!isConnected()) { throw new IllegalStateException("Not connected to server."); } packetWriter.addPacketListener(packetListener, packetFilter); } /** * Removes a packet listener from this connection. * * @param packetListener the packet listener to remove. */ public void removePacketWriterListener(PacketListener packetListener) { packetWriter.removePacketListener(packetListener); } /** * 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. * * @param connectionListener a connection listener. */ public void addConnectionListener(ConnectionListener connectionListener) { if (connectionListener == null) { return; } synchronized (packetReader.connectionListeners) { 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) { synchronized (packetReader.connectionListeners) { packetReader.connectionListeners.remove(connectionListener); } } /** * Adds a connection established listener that will be notified when a new connection * is established. * * @param connectionEstablishedListener a listener interested on connection established events. */ public static void addConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) { synchronized (connectionEstablishedListeners) { if (!connectionEstablishedListeners.contains(connectionEstablishedListener)) { connectionEstablishedListeners.add(connectionEstablishedListener); } } } /** * Removes a listener on new established connections. * * @param connectionEstablishedListener a listener interested on connection established events. */ public static void removeConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) { synchronized (connectionEstablishedListeners) { connectionEstablishedListeners.remove(connectionEstablishedListener); } } /** * Initializes the connection by creating a packet reader and writer and opening a * XMPP stream to the server. * * @throws XMPPException if establishing a connection to the server fails. */ void init() throws XMPPException { try { reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } catch (IOException ioe) { throw new XMPPException( "XMPPError establishing connection with server.", new XMPPError(502), ioe); } // If debugging is enabled, we open a window and write out all network traffic. if (DEBUG_ENABLED) { // Detect the debugger class to use. String className = System.getProperty("smack.debuggerClass"); Class debuggerClass = null; try { debuggerClass = Class.forName(className); } catch (Exception e) { try { debuggerClass = Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger"); } catch (Exception ex) { debuggerClass = LiteDebugger.class; } } // Create a new debugger instance. If an exception occurs then disable the debugging // option try { Constructor constructor = debuggerClass.getConstructor( new Class[] { XMPPConnection.class, Writer.class, Reader.class }); debugger = (SmackDebugger) constructor.newInstance(new Object[] { this, writer, reader }); reader = debugger.getReader(); writer = debugger.getWriter(); } catch (Exception e) { e.printStackTrace(); DEBUG_ENABLED = false; } } packetWriter = new PacketWriter(this); packetReader = new PacketReader(this); // If debugging is enabled, we should start the thread that will listen for // all packets and then log them. if (DEBUG_ENABLED) { packetReader.addPacketListener(debugger.getReaderListener(), null); if (debugger.getWriterListener() != null) { packetWriter.addPacketListener(debugger.getWriterListener(), null); } } // Start the packet writer. This will open a XMPP stream to the server packetWriter.startup(); // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader.startup(); // Make note of the fact that we're now connected. connected = true; // Create the roster. this.roster = new Roster(this); // Notify that a new connection has been established connectionEstablished(this); } /** * Fires listeners on connection established events. */ private static void connectionEstablished(XMPPConnection connection) { ConnectionEstablishedListener[] listeners = null; synchronized (connectionEstablishedListeners) { listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()]; connectionEstablishedListeners.toArray(listeners); } for (int i = 0; i < listeners.length; i++) { listeners[i].connectionEstablished(connection); } } }