Interface XMPPConnection

  • All Known Implementing Classes:
    AbstractXMPPConnection, ModularXmppClientToServerConnection, XMPPBOSHConnection, XMPPTCPConnection

    public interface XMPPConnection
    The XMPPConnection interface provides an interface for connections to an XMPP server and implements shared methods which are used by the different types of connections (e.g. XMPPTCPConnection or XMPPBOSHConnection). To create a connection to an XMPP server a simple usage of this API might look like the following:
     // Create a connection to the igniterealtime.org XMPP server.
     XMPPTCPConnection con = new XMPPTCPConnection("igniterealtime.org");
     // Connect to the server
     con.connect();
     // Most servers require you to login before performing other tasks.
     con.login("jsmith", "mypass");
     // Start a new conversation with John Doe and send him a message.
     ChatManager chatManager = ChatManager.getInstanceFor(con);
     chatManager.addIncomingListener(new IncomingChatMessageListener() {
         public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
             // Print out any messages we get back to standard out.
             System.out.println("Received message: " + message);
         }
     });
     Chat chat = chatManager.chatWith("jdoe@igniterealtime.org");
     chat.send("Howdy!");
     // Disconnect from the server
     con.disconnect();
     

    Note that the XMPPConnection interface does intentionally not declare any methods that manipulate the connection state, e.g. connect(), disconnect(). You should use the most specific connection type, e.g. XMPPTCPConnection as declared type and use the XMPPConnection interface when you don't need to manipulate the connection state.

    XMPPConnections can be reused between connections. This means that an Connection may be connected, disconnected and then connected again. Listeners of the XMPPConnection will be retained across connections.

    Incoming Stanza Listeners

    Most callbacks (listeners, handlers, …) than you can add to a connection come in three different variants:
    • standard
    • async (asynchronous)
    • sync (synchronous)

    Standard callbacks are invoked concurrently, but it is ensured that the same callback is never run concurrently. The callback's identity is used as key for that. The events delivered to the callback preserve the order of the causing events of the connection.

    Asynchronous callbacks are run decoupled from the connections main event loop. Hence a callback triggered by stanza B may (appear to) invoked before a callback triggered by stanza A, even though stanza A arrived before B.

    Synchronous callbacks are run synchronous to the main event loop of a connection. Hence they are invoked in the exact order of how events happen there, most importantly the arrival order of incoming stanzas. You should only use synchronous callbacks in rare situations.

    • Method Detail

      • getXMPPServiceDomain

        DomainBareJid getXMPPServiceDomain()
        Returns the XMPP Domain of the service provided by the XMPP server and used for this connection. After authenticating with the server the returned value may be different.
        Returns:
        the XMPP domain of this XMPP session.
      • getHost

        String getHost()
        Returns the host name of the server where the XMPP server is running. This would be the IP address of the server or a name that may be resolved by a DNS server.
        Returns:
        the host name of the server where the XMPP server is running or null if not yet connected.
      • getPort

        int getPort()
        Returns the port number of the XMPP server for this connection. The default port for normal connections is 5222.
        Returns:
        the port number of the XMPP server or 0 if not yet connected.
      • getUser

        EntityFullJid getUser()
        Returns the full XMPP address of the user that is logged in to the connection or null if not logged in yet. An XMPP address is in the form username@server/resource.
        Returns:
        the full XMPP address of the user logged in.
      • getStreamId

        String getStreamId()
        Returns the stream ID for this connection, which is the value set by the server when opening an XMPP stream. This value will be null if not connected to the server.
        Returns:
        the ID of this connection returned from the XMPP server or null if not connected to the server.
        See Also:
        RFC 6120 § 4.7.3. id
      • isConnected

        boolean isConnected()
        Returns true if currently connected to the XMPP server.
        Returns:
        true if connected.
      • isAuthenticated

        boolean isAuthenticated()
        Returns true if currently authenticated by successfully calling the login method.
        Returns:
        true if authenticated.
      • isAnonymous

        boolean isAnonymous()
        Returns true if currently authenticated anonymously.
        Returns:
        true if authenticated anonymously.
      • isSecureConnection

        boolean isSecureConnection()
        Returns true if the connection to the server has successfully negotiated encryption.
        Returns:
        true if a secure connection to the server.
      • isUsingCompression

        boolean isUsingCompression()
        Returns true if network traffic is being compressed. When using stream compression network traffic can be reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network connection. However, the server will need to use more CPU time in order to un/compress network data so under high load the server performance might be affected.
        Returns:
        true if network traffic is being compressed.
      • trySendStanza

        boolean trySendStanza​(Stanza stanza)
                       throws SmackException.NotConnectedException
        Try to send the given stanza. Returns true if the stanza was successfully put into the outgoing stanza queue, otherwise, if false is returned, the stanza could not be scheduled for sending (for example because the outgoing element queue is full). Note that this means that the stanza possibly was not put onto the wire, even if true is returned, it just has been successfully scheduled for sending.

        Note: Implementations are not required to provide that functionality. In that case this method is mapped to sendStanza(Stanza) and will possibly block until the stanza could be scheduled for sending.

        Parameters:
        stanza - the stanza to send.
        Returns:
        true if the stanza was successfully scheduled to be send, false otherwise.
        Throws:
        SmackException.NotConnectedException - if the connection is not connected.
        Since:
        4.4.0
      • trySendStanza

        boolean trySendStanza​(Stanza stanza,
                              long timeout,
                              TimeUnit unit)
                       throws SmackException.NotConnectedException,
                              InterruptedException
        Try to send the given stanza. Returns true if the stanza was successfully put into the outgoing stanza queue within the given timeout period, otherwise, if false is returned, the stanza could not be scheduled for sending (for example because the outgoing element queue is full). Note that this means that the stanza possibly was not put onto the wire, even if true is returned, it just has been successfully scheduled for sending.

        Note: Implementations are not required to provide that functionality. In that case this method is mapped to sendStanza(Stanza) and will possibly block until the stanza could be scheduled for sending.

        Parameters:
        stanza - the stanza to send.
        timeout - how long to wait before giving up, in units of unit.
        unit - a TimeUnit determining how to interpret the timeout parameter.
        Returns:
        true if the stanza was successfully scheduled to be send, false otherwise.
        Throws:
        SmackException.NotConnectedException - if the connection is not connected.
        InterruptedException - if the calling thread was interrupted.
        Since:
        4.4.0
      • addConnectionListener

        void addConnectionListener​(ConnectionListener connectionListener)
        Adds a connection listener to this connection that will be notified when the connection closes or fails.
        Parameters:
        connectionListener - a connection listener.
      • createStanzaCollector

        StanzaCollector createStanzaCollector​(StanzaFilter stanzaFilter)
        Creates a new stanza collector for this connection. A stanza filter determines which stanzas will be accumulated by the collector. A StanzaCollector is more suitable to use than a StanzaListener when you need to wait for a specific result.

        Note: If you send a Stanza right after using this method, then consider using createStanzaCollectorAndSend(StanzaFilter, Stanza) instead. Otherwise make sure cancel the StanzaCollector in every case, e.g. even if an exception is thrown, or otherwise you may leak the StanzaCollector.

        Parameters:
        stanzaFilter - the stanza filter to use.
        Returns:
        a new stanza collector.
      • removeStanzaCollector

        void removeStanzaCollector​(StanzaCollector collector)
        Remove a stanza collector of this connection.
        Parameters:
        collector - a stanza collectors which was created for this connection.
      • addStanzaListener

        void addStanzaListener​(StanzaListener stanzaListener,
                               StanzaFilter stanzaFilter)
        Registers a stanza listener with this connection. The listener will be invoked when a (matching) incoming stanza is received. The stanza filter determines which stanzas will be delivered to the listener. It is guaranteed that the same listener will not be invoked concurrently and the the order of invocation will reflect the order in which the stanzas have been received. If the same stanza listener is added again with a different filter, only the new filter will be used.
        Parameters:
        stanzaListener - the stanza listener to notify of new received stanzas.
        stanzaFilter - the stanza filter to use.
        Since:
        4.4.0
      • removeStanzaListener

        boolean removeStanzaListener​(StanzaListener stanzaListener)
        Removes a stanza listener for received stanzas from this connection.
        Parameters:
        stanzaListener - the stanza listener to remove.
        Returns:
        true if the stanza listener was removed.
        Since:
        4.4.0
      • addSyncStanzaListener

        void addSyncStanzaListener​(StanzaListener stanzaListener,
                                   StanzaFilter stanzaFilter)
        Registers a synchronous stanza listener with this connection. A stanza listener will be invoked only when an incoming stanza is received. A stanza filter determines which stanzas will be delivered to the listener. If the same stanza listener is added again with a different filter, only the new filter will be used.

        Important: This stanza listeners will be called in the same single thread that processes all incoming stanzas. Only use this kind of stanza filter if it does not perform any XMPP activity that waits for a response. Consider using addAsyncStanzaListener(StanzaListener, StanzaFilter) when possible, i.e. when the invocation order doesn't have to be the same as the order of the arriving stanzas. If the order of the arriving stanzas, consider using a StanzaCollector when possible.

        Parameters:
        stanzaListener - the stanza listener to notify of new received stanzas.
        stanzaFilter - the stanza filter to use.
        Since:
        4.1
        See Also:
        addStanzaInterceptor(StanzaListener, StanzaFilter)
      • removeSyncStanzaListener

        boolean removeSyncStanzaListener​(StanzaListener stanzaListener)
        Removes a stanza listener for received stanzas from this connection.
        Parameters:
        stanzaListener - the stanza listener to remove.
        Returns:
        true if the stanza listener was removed
        Since:
        4.1
      • addAsyncStanzaListener

        void addAsyncStanzaListener​(StanzaListener stanzaListener,
                                    StanzaFilter stanzaFilter)
        Registers an asynchronous stanza listener with this connection. A stanza listener will be invoked only when an incoming stanza is received. A stanza filter determines which stanzas will be delivered to the listener. If the same stanza listener is added again with a different filter, only the new filter will be used.

        Unlike addAsyncStanzaListener(StanzaListener, StanzaFilter) stanza listeners added with this method will be invoked asynchronously in their own thread. Use this method if the order of the stanza listeners must not depend on the order how the stanzas where received.

        Parameters:
        stanzaListener - the stanza listener to notify of new received stanzas.
        stanzaFilter - the stanza filter to use.
        Since:
        4.1
        See Also:
        addStanzaInterceptor(StanzaListener, StanzaFilter)
      • removeAsyncStanzaListener

        boolean removeAsyncStanzaListener​(StanzaListener stanzaListener)
        Removes an asynchronous stanza listener for received stanzas from this connection.
        Parameters:
        stanzaListener - the stanza listener to remove.
        Returns:
        true if the stanza listener was removed
        Since:
        4.1
      • addStanzaSendingListener

        void addStanzaSendingListener​(StanzaListener stanzaListener,
                                      StanzaFilter stanzaFilter)
        Registers a stanza listener with this connection. The listener will be notified of every stanza that this connection sends. A stanza filter determines which stanzas will be delivered to the listener. Note that the thread that writes stanzas will be used to invoke the listeners. Therefore, each stanza listener should complete all operations quickly or use a different thread for processing.
        Parameters:
        stanzaListener - the stanza listener to notify of sent stanzas.
        stanzaFilter - the stanza filter to use.
      • removeStanzaSendingListener

        void removeStanzaSendingListener​(StanzaListener stanzaListener)
        Removes a stanza listener for sending stanzas from this connection.
        Parameters:
        stanzaListener - the stanza listener to remove.
      • addMessageInterceptor

        void addMessageInterceptor​(Consumer<MessageBuilder> messageInterceptor,
                                   Predicate<Message> messageFilter)
        Registers a stanza interceptor with this connection. The interceptor will be invoked every time a stanza is about to be sent by this connection. Interceptors may modify the stanza to be sent. A stanza filter determines which stanzas will be delivered to the interceptor.

        NOTE: For a similar functionality on incoming stanzas, see addAsyncStanzaListener(StanzaListener, StanzaFilter).

        Parameters:
        messageInterceptor - the stanza interceptor to notify of stanzas about to be sent.
        messageFilter - the stanza filter to use.
      • addPresenceInterceptor

        void addPresenceInterceptor​(Consumer<PresenceBuilder> presenceInterceptor,
                                    Predicate<Presence> presenceFilter)
        Registers a stanza interceptor with this connection. The interceptor will be invoked every time a stanza is about to be sent by this connection. Interceptors may modify the stanza to be sent. A stanza filter determines which stanzas will be delivered to the interceptor.

        NOTE: For a similar functionality on incoming stanzas, see addAsyncStanzaListener(StanzaListener, StanzaFilter).

        Parameters:
        presenceInterceptor - the stanza interceptor to notify of stanzas about to be sent.
        presenceFilter - the stanza filter to use.
      • getReplyTimeout

        long getReplyTimeout()
        Returns the current value of the reply timeout in milliseconds for request for this XMPPConnection instance.
        Returns:
        the reply timeout in milliseconds
      • setReplyTimeout

        void setReplyTimeout​(long timeout)
        Set the stanza reply timeout in milliseconds. In most cases, Smack will throw a SmackException.NoResponseException if no reply to a request was received within the timeout period.
        Parameters:
        timeout - for a reply in milliseconds
      • getConnectionCounter

        int getConnectionCounter()
        Get the connection counter of this XMPPConnection instance. Those can be used as ID to identify the connection, but beware that the ID may not be unique if you create more then 2*Integer.MAX_VALUE instances as the counter could wrap.
        Returns:
        the connection counter of this XMPPConnection
      • setFromMode

        void setFromMode​(XMPPConnection.FromMode fromMode)
        Set the FromMode for this connection instance. Defines how the 'from' attribute of outgoing stanzas should be populated by Smack.
        Parameters:
        fromMode - TODO javadoc me please
      • getFeature

        @Deprecated
        default <F extends XmlElement> F getFeature​(String element,
                                                    String namespace)
        Deprecated.
        use getFeature(Class) instead.
        Get the feature stanza extensions for a given stream feature of the server, or null if the server doesn't support that feature.
        Type Parameters:
        F - ExtensionElement type of the feature.
        Parameters:
        element - TODO javadoc me please
        namespace - TODO javadoc me please
        Returns:
        a stanza extensions of the feature or null
      • getFeature

        <F extends XmlElement> F getFeature​(QName qname)
        Get the feature stanza extensions for a given stream feature of the server, or null if the server doesn't support that feature.
        Type Parameters:
        F - ExtensionElement type of the feature.
        Parameters:
        qname - the qualified name of the XML element of feature.
        Returns:
        a stanza extensions of the feature or null
        Since:
        4.4
      • getFeature

        default <F extends XmlElement> F getFeature​(Class<F> featureClass)
        Get the feature stanza extensions for a given stream feature of the server, or null if the server doesn't support that feature.
        Type Parameters:
        F - ExtensionElement type of the feature.
        Parameters:
        featureClass - the class of the feature.
        Returns:
        a stanza extensions of the feature or null
        Since:
        4.4
      • hasFeature

        default boolean hasFeature​(String element,
                                   String namespace)
        Return true if the server supports the given stream feature.
        Parameters:
        element - TODO javadoc me please
        namespace - TODO javadoc me please
        Returns:
        true if the server supports the stream feature.
      • hasFeature

        boolean hasFeature​(QName qname)
        Return true if the server supports the given stream feature.
        Parameters:
        qname - the qualified name of the XML element of feature.
        Returns:
        true if the server supports the stream feature.
      • sendIqRequestAsync

        SmackFuture<IQ,​ExceptionsendIqRequestAsync​(IQ request)
        Send an IQ request asynchronously. The connection's default reply timeout will be used.
        Parameters:
        request - the IQ request to send.
        Returns:
        a SmackFuture for the response.
      • sendIqRequestAsync

        SmackFuture<IQ,​ExceptionsendIqRequestAsync​(IQ request,
                                                           long timeout)
        Send an IQ request asynchronously.
        Parameters:
        request - the IQ request to send.
        timeout - the reply timeout in milliseconds.
        Returns:
        a SmackFuture for the response.
      • sendAsync

        <S extends StanzaSmackFuture<S,​ExceptionsendAsync​(S stanza,
                                                                    StanzaFilter replyFilter)
        Send a stanza asynchronously, waiting for exactly one response stanza using the given reply filter. The connection's default reply timeout will be used.
        Type Parameters:
        S - the type of the stanza to send.
        Parameters:
        stanza - the stanza to send.
        replyFilter - the filter used for the response stanza.
        Returns:
        a SmackFuture for the response.
      • sendAsync

        <S extends StanzaSmackFuture<S,​ExceptionsendAsync​(S stanza,
                                                                    StanzaFilter replyFilter,
                                                                    long timeout)
        Send a stanza asynchronously, waiting for exactly one response stanza using the given reply filter.
        Type Parameters:
        S - the type of the stanza to send.
        Parameters:
        stanza - the stanza to send.
        replyFilter - the filter used for the response stanza.
        timeout - the reply timeout in milliseconds.
        Returns:
        a SmackFuture for the response.
      • addOneTimeSyncCallback

        void addOneTimeSyncCallback​(StanzaListener callback,
                                    StanzaFilter stanzaFilter)
        Add a callback that is called exactly once and synchronously with the incoming stanza that matches the given stanza filter.
        Parameters:
        callback - the callback invoked once the stanza filter matches a stanza.
        stanzaFilter - the filter to match stanzas or null to match all.
      • registerIQRequestHandler

        IQRequestHandler registerIQRequestHandler​(IQRequestHandler iqRequestHandler)
        Register an IQ request handler with this connection.

        IQ request handler process incoming IQ requests, i.e. incoming IQ stanzas of type 'get' or 'set', and return a result.

        Parameters:
        iqRequestHandler - the IQ request handler to register.
        Returns:
        the previously registered IQ request handler or null.
      • unregisterIQRequestHandler

        IQRequestHandler unregisterIQRequestHandler​(String element,
                                                    String namespace,
                                                    IQ.Type type)
        Unregister an IQ request handler with this connection.
        Parameters:
        element - the IQ element the IQ request handler is responsible for.
        namespace - the IQ namespace the IQ request handler is responsible for.
        type - the IQ type the IQ request handler is responsible for.
        Returns:
        the previously registered IQ request handler or null.
      • getLastStanzaReceived

        long getLastStanzaReceived()
        Returns the timestamp in milliseconds when the last stanza was received.
        Returns:
        the timestamp in milliseconds