001/**
002 *
003 * Copyright 2009 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack;
018
019import java.io.IOException;
020import java.io.Reader;
021import java.io.Writer;
022import java.util.ArrayList;
023import java.util.Collection;
024import java.util.HashMap;
025import java.util.LinkedHashMap;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029import java.util.Set;
030import java.util.concurrent.ArrayBlockingQueue;
031import java.util.concurrent.ConcurrentLinkedQueue;
032import java.util.concurrent.CopyOnWriteArraySet;
033import java.util.concurrent.ExecutorService;
034import java.util.concurrent.Executors;
035import java.util.concurrent.ScheduledExecutorService;
036import java.util.concurrent.ScheduledFuture;
037import java.util.concurrent.ThreadPoolExecutor;
038import java.util.concurrent.TimeUnit;
039import java.util.concurrent.atomic.AtomicInteger;
040import java.util.concurrent.locks.Lock;
041import java.util.concurrent.locks.ReentrantLock;
042import java.util.logging.Level;
043import java.util.logging.Logger;
044
045import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
046import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
047import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
048import org.jivesoftware.smack.SmackException.NoResponseException;
049import org.jivesoftware.smack.SmackException.NotConnectedException;
050import org.jivesoftware.smack.SmackException.ConnectionException;
051import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
052import org.jivesoftware.smack.SmackException.SecurityRequiredException;
053import org.jivesoftware.smack.XMPPException.XMPPErrorException;
054import org.jivesoftware.smack.compress.packet.Compress;
055import org.jivesoftware.smack.compression.XMPPInputOutputStream;
056import org.jivesoftware.smack.debugger.SmackDebugger;
057import org.jivesoftware.smack.filter.IQReplyFilter;
058import org.jivesoftware.smack.filter.StanzaFilter;
059import org.jivesoftware.smack.filter.StanzaIdFilter;
060import org.jivesoftware.smack.iqrequest.IQRequestHandler;
061import org.jivesoftware.smack.packet.Bind;
062import org.jivesoftware.smack.packet.ErrorIQ;
063import org.jivesoftware.smack.packet.IQ;
064import org.jivesoftware.smack.packet.Mechanisms;
065import org.jivesoftware.smack.packet.Stanza;
066import org.jivesoftware.smack.packet.ExtensionElement;
067import org.jivesoftware.smack.packet.Presence;
068import org.jivesoftware.smack.packet.Session;
069import org.jivesoftware.smack.packet.StartTls;
070import org.jivesoftware.smack.packet.PlainStreamElement;
071import org.jivesoftware.smack.packet.XMPPError;
072import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
073import org.jivesoftware.smack.parsing.UnparsablePacket;
074import org.jivesoftware.smack.provider.ExtensionElementProvider;
075import org.jivesoftware.smack.provider.ProviderManager;
076import org.jivesoftware.smack.util.DNSUtil;
077import org.jivesoftware.smack.util.Objects;
078import org.jivesoftware.smack.util.PacketParserUtils;
079import org.jivesoftware.smack.util.ParserUtils;
080import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
081import org.jivesoftware.smack.util.StringUtils;
082import org.jivesoftware.smack.util.dns.HostAddress;
083import org.jxmpp.util.XmppStringUtils;
084import org.xmlpull.v1.XmlPullParser;
085import org.xmlpull.v1.XmlPullParserException;
086
087
088public abstract class AbstractXMPPConnection implements XMPPConnection {
089    private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());
090
091    /** 
092     * Counter to uniquely identify connections that are created.
093     */
094    private final static AtomicInteger connectionCounter = new AtomicInteger(0);
095
096    static {
097        // Ensure the SmackConfiguration class is loaded by calling a method in it.
098        SmackConfiguration.getVersion();
099    }
100
101    /**
102     * Get the collection of listeners that are interested in connection creation events.
103     * 
104     * @return a collection of listeners interested on new connections.
105     */
106    protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() {
107        return XMPPConnectionRegistry.getConnectionCreationListeners();
108    }
109 
110    /**
111     * A collection of ConnectionListeners which listen for connection closing
112     * and reconnection events.
113     */
114    protected final Set<ConnectionListener> connectionListeners =
115            new CopyOnWriteArraySet<ConnectionListener>();
116
117    /**
118     * A collection of PacketCollectors which collects packets for a specified filter
119     * and perform blocking and polling operations on the result queue.
120     * <p>
121     * We use a ConcurrentLinkedQueue here, because its Iterator is weakly
122     * consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
123     * loop to be lock free. As drawback, removing a PacketCollector is O(n).
124     * The alternative would be a synchronized HashSet, but this would mean a
125     * synchronized block around every usage of <code>collectors</code>.
126     * </p>
127     */
128    private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();
129
130    /**
131     * List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received.
132     */
133    private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();
134
135    /**
136     * List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received.
137     */
138    private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();
139
140    /**
141     * List of PacketListeners that will be notified when a new stanza(/packet) was sent.
142     */
143    private final Map<StanzaListener, ListenerWrapper> sendListeners =
144            new HashMap<StanzaListener, ListenerWrapper>();
145
146    /**
147     * List of PacketListeners that will be notified when a new stanza(/packet) is about to be
148     * sent to the server. These interceptors may modify the stanza(/packet) before it is being
149     * actually sent to the server.
150     */
151    private final Map<StanzaListener, InterceptorWrapper> interceptors =
152            new HashMap<StanzaListener, InterceptorWrapper>();
153
154    protected final Lock connectionLock = new ReentrantLock();
155
156    protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();
157
158    /**
159     * The full JID of the authenticated user, as returned by the resource binding response of the server.
160     * <p>
161     * It is important that we don't infer the user from the login() arguments and the configurations service name, as,
162     * for example, when SASL External is used, the username is not given to login but taken from the 'external'
163     * certificate.
164     * </p>
165     */
166    protected String user;
167
168    protected boolean connected = false;
169
170    /**
171     * The stream ID, see RFC 6120 § 4.7.3
172     */
173    protected String streamId;
174
175    /**
176     * 
177     */
178    private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();
179
180    /**
181     * The SmackDebugger allows to log and debug XML traffic.
182     */
183    protected SmackDebugger debugger = null;
184
185    /**
186     * The Reader which is used for the debugger.
187     */
188    protected Reader reader;
189
190    /**
191     * The Writer which is used for the debugger.
192     */
193    protected Writer writer;
194
195    /**
196     * Set to success if the last features stanza from the server has been parsed. A XMPP connection
197     * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
198     * stanza is send by the server. This is set to true once the last feature stanza has been
199     * parsed.
200     */
201    protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
202                    AbstractXMPPConnection.this);
203
204    /**
205     * Set to success if the sasl feature has been received.
206     */
207    protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
208                    AbstractXMPPConnection.this);
209 
210    /**
211     * The SASLAuthentication manager that is responsible for authenticating with the server.
212     */
213    protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);
214
215    /**
216     * A number to uniquely identify connections that are created. This is distinct from the
217     * connection ID, which is a value sent by the server once a connection is made.
218     */
219    protected final int connectionCounterValue = connectionCounter.getAndIncrement();
220
221    /**
222     * Holds the initial configuration used while creating the connection.
223     */
224    protected final ConnectionConfiguration config;
225
226    /**
227     * Defines how the from attribute of outgoing stanzas should be handled.
228     */
229    private FromMode fromMode = FromMode.OMITTED;
230
231    protected XMPPInputOutputStream compressionHandler;
232
233    private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();
234
235    /**
236     * ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
237     * important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
238     * PacketListeners are invoked in the same order the stanzas arrived.
239     */
240    private final ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
241                    new ArrayBlockingQueue<Runnable>(100), new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor"));
242
243    /**
244     * This scheduled thread pool executor is used to remove pending callbacks.
245     */
246    private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
247                    new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks"));
248
249    /**
250     * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
251     * them 'daemon'.
252     */
253    private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
254                    // @formatter:off
255                    new SmackExecutorThreadFactory(    // threadFactory
256                                    connectionCounterValue,
257                                    "Cached Executor"
258                                    )
259                    // @formatter:on
260                    );
261
262    /**
263     * A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to
264     * decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
265     * is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
266     */
267    private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
268                    getConnectionCounter(), "Single Threaded Executor"));
269
270    /**
271     * The used host to establish the connection to
272     */
273    protected String host;
274
275    /**
276     * The used port to establish the connection to
277     */
278    protected int port;
279
280    /**
281     * Flag that indicates if the user is currently authenticated with the server.
282     */
283    protected boolean authenticated = false;
284
285    /**
286     * Flag that indicates if the user was authenticated with the server when the connection
287     * to the server was closed (abruptly or not).
288     */
289    protected boolean wasAuthenticated = false;
290
291    private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
292    private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();
293
294    /**
295     * Create a new XMPPConnection to an XMPP server.
296     * 
297     * @param configuration The configuration which is used to establish the connection.
298     */
299    protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
300        config = configuration;
301    }
302
303    /**
304     * Get the connection configuration used by this connection.
305     *
306     * @return the connection configuration.
307     */
308    public ConnectionConfiguration getConfiguration() {
309        return config;
310    }
311
312    @Override
313    public String getServiceName() {
314        if (serviceName != null) {
315            return serviceName;
316        }
317        return config.getServiceName();
318    }
319
320    @Override
321    public String getHost() {
322        return host;
323    }
324
325    @Override
326    public int getPort() {
327        return port;
328    }
329
330    @Override
331    public abstract boolean isSecureConnection();
332
333    protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException;
334
335    @Override
336    public abstract void send(PlainStreamElement element) throws NotConnectedException;
337
338    @Override
339    public abstract boolean isUsingCompression();
340
341    /**
342     * Establishes a connection to the XMPP server and performs an automatic login
343     * only if the previous connection state was logged (authenticated). It basically
344     * creates and maintains a connection to the server.
345     * <p>
346     * Listeners will be preserved from a previous connection.
347     * 
348     * @throws XMPPException if an error occurs on the XMPP protocol level.
349     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
350     * @throws IOException 
351     * @throws ConnectionException with detailed information about the failed connection.
352     * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
353     */
354    public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException {
355        // Check if not already connected
356        throwAlreadyConnectedExceptionIfAppropriate();
357
358        // Reset the connection state
359        saslAuthentication.init();
360        saslFeatureReceived.init();
361        lastFeaturesReceived.init();
362        streamId = null;
363
364        // Perform the actual connection to the XMPP service
365        connectInternal();
366        return this;
367    }
368
369    /**
370     * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
371     * way of XMPP connection establishment. Implementations are required to perform an automatic
372     * login if the previous connection state was logged (authenticated).
373     * 
374     * @throws SmackException
375     * @throws IOException
376     * @throws XMPPException
377     */
378    protected abstract void connectInternal() throws SmackException, IOException, XMPPException;
379
380    private String usedUsername, usedPassword, usedResource;
381
382    /**
383     * Logs in to the server using the strongest SASL mechanism supported by
384     * the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the 
385     * authentication process without a response from the server, a
386     * {@link SmackException.NoResponseException} will be thrown.
387     * <p>
388     * Before logging in (i.e. authenticate) to the server the connection must be connected
389     * by calling {@link #connect}.
390     * </p>
391     * <p>
392     * It is possible to log in without sending an initial available presence by using
393     * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
394     * Finally, if you want to not pass a password and instead use a more advanced mechanism
395     * while using SASL then you may be interested in using
396     * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
397     * For more advanced login settings see {@link ConnectionConfiguration}.
398     * </p>
399     * 
400     * @throws XMPPException if an error occurs on the XMPP protocol level.
401     * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
402     * @throws IOException if an I/O error occurs during login.
403     */
404    public synchronized void login() throws XMPPException, SmackException, IOException {
405        if (isAnonymous()) {
406            throwNotConnectedExceptionIfAppropriate();
407            throwAlreadyLoggedInExceptionIfAppropriate();
408            loginAnonymously();
409        } else {
410            // The previously used username, password and resource take over precedence over the
411            // ones from the connection configuration
412            CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
413            String password = usedPassword != null ? usedPassword : config.getPassword();
414            String resource = usedResource != null ? usedResource : config.getResource();
415            login(username, password, resource);
416        }
417    }
418
419    /**
420     * Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection
421     * configuration.
422     * 
423     * @param username
424     * @param password
425     * @throws XMPPException
426     * @throws SmackException
427     * @throws IOException
428     * @see #login
429     */
430    public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
431                    IOException {
432        login(username, password, config.getResource());
433    }
434
435    /**
436     * Login with the given username (authorization identity). You may omit the password if a callback handler is used.
437     * If resource is null, then the server will generate one.
438     * 
439     * @param username
440     * @param password
441     * @param resource
442     * @throws XMPPException
443     * @throws SmackException
444     * @throws IOException
445     * @see #login
446     */
447    public synchronized void login(CharSequence username, String password, String resource) throws XMPPException,
448                    SmackException, IOException {
449        if (!config.allowNullOrEmptyUsername) {
450            StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
451        }
452        throwNotConnectedExceptionIfAppropriate();
453        throwAlreadyLoggedInExceptionIfAppropriate();
454        usedUsername = username != null ? username.toString() : null;
455        usedPassword = password;
456        usedResource = resource;
457        loginNonAnonymously(usedUsername, usedPassword, usedResource);
458    }
459
460    protected abstract void loginNonAnonymously(String username, String password, String resource)
461                    throws XMPPException, SmackException, IOException;
462
463    protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException;
464
465    @Override
466    public final boolean isConnected() {
467        return connected;
468    }
469
470    @Override
471    public final boolean isAuthenticated() {
472        return authenticated;
473    }
474
475    @Override
476    public final String getUser() {
477        return user;
478    }
479
480    @Override
481    public String getStreamId() {
482        if (!isConnected()) {
483            return null;
484        }
485        return streamId;
486    }
487
488    // TODO remove this suppression once "disable legacy session" code has been removed from Smack
489    @SuppressWarnings("deprecation")
490    protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
491                    IOException, SmackException {
492
493        // Wait until either:
494        // - the servers last features stanza has been parsed
495        // - the timeout occurs
496        LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
497        lastFeaturesReceived.checkIfSuccessOrWait();
498
499
500        if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
501            // Server never offered resource binding, which is REQURIED in XMPP client and
502            // server implementations as per RFC6120 7.2
503            throw new ResourceBindingNotOfferedException();
504        }
505
506        // Resource binding, see RFC6120 7.
507        // Note that we can not use IQReplyFilter here, since the users full JID is not yet
508        // available. It will become available right after the resource has been successfully bound.
509        Bind bindResource = Bind.newSet(resource);
510        PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
511        Bind response = packetCollector.nextResultOrThrow();
512        // Set the connections user to the result of resource binding. It is important that we don't infer the user
513        // from the login() arguments and the configurations service name, as, for example, when SASL External is used,
514        // the username is not given to login but taken from the 'external' certificate.
515        user = response.getJid();
516        serviceName = XmppStringUtils.parseDomain(user);
517
518        Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
519        // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
520        // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
521        if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) {
522            Session session = new Session();
523            packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
524            packetCollector.nextResultOrThrow();
525        }
526    }
527
528    protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException {
529        // Indicate that we're now authenticated.
530        this.authenticated = true;
531
532        // If debugging is enabled, change the the debug window title to include the
533        // name we are now logged-in as.
534        // If DEBUG was set to true AFTER the connection was created the debugger
535        // will be null
536        if (config.isDebuggerEnabled() && debugger != null) {
537            debugger.userHasLogged(user);
538        }
539        callConnectionAuthenticatedListener(resumed);
540
541        // Set presence to online. It is important that this is done after
542        // callConnectionAuthenticatedListener(), as this call will also
543        // eventually load the roster. And we should load the roster before we
544        // send the initial presence.
545        if (config.isSendPresence() && !resumed) {
546            sendStanza(new Presence(Presence.Type.available));
547        }
548    }
549
550    @Override
551    public final boolean isAnonymous() {
552        return config.getUsername() == null && usedUsername == null
553                        && !config.allowNullOrEmptyUsername;
554    }
555
556    private String serviceName;
557
558    protected List<HostAddress> hostAddresses;
559
560    /**
561     * Populates {@link #hostAddresses} with at least one host address.
562     *
563     * @return a list of host addresses where DNS (SRV) RR resolution failed.
564     */
565    protected List<HostAddress> populateHostAddresses() {
566        List<HostAddress> failedAddresses = new LinkedList<>();
567        // N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
568        if (config.host != null) {
569            hostAddresses = new ArrayList<HostAddress>(1);
570            HostAddress hostAddress;
571            hostAddress = new HostAddress(config.host, config.port);
572            hostAddresses.add(hostAddress);
573        } else {
574            hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses);
575        }
576        // If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
577        // config.host one or the host representing the service name by DNSUtil
578        assert(!hostAddresses.isEmpty());
579        return failedAddresses;
580    }
581
582    protected Lock getConnectionLock() {
583        return connectionLock;
584    }
585
586    protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
587        if (!isConnected()) {
588            throw new NotConnectedException();
589        }
590    }
591
592    protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
593        if (isConnected()) {
594            throw new AlreadyConnectedException();
595        }
596    }
597
598    protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
599        if (isAuthenticated()) {
600            throw new AlreadyLoggedInException();
601        }
602    }
603
604    @Deprecated
605    @Override
606    public void sendPacket(Stanza packet) throws NotConnectedException {
607        sendStanza(packet);
608    }
609
610    @Override
611    public void sendStanza(Stanza packet) throws NotConnectedException {
612        Objects.requireNonNull(packet, "Packet must not be null");
613
614        throwNotConnectedExceptionIfAppropriate();
615        switch (fromMode) {
616        case OMITTED:
617            packet.setFrom(null);
618            break;
619        case USER:
620            packet.setFrom(getUser());
621            break;
622        case UNCHANGED:
623        default:
624            break;
625        }
626        // Invoke interceptors for the new packet that is about to be sent. Interceptors may modify
627        // the content of the packet.
628        firePacketInterceptors(packet);
629        sendStanzaInternal(packet);
630    }
631
632    /**
633     * Returns the SASLAuthentication manager that is responsible for authenticating with
634     * the server.
635     * 
636     * @return the SASLAuthentication manager that is responsible for authenticating with
637     *         the server.
638     */
639    protected SASLAuthentication getSASLAuthentication() {
640        return saslAuthentication;
641    }
642
643    /**
644     * Closes the connection by setting presence to unavailable then closing the connection to
645     * the XMPP server. The XMPPConnection can still be used for connecting to the server
646     * again.
647     *
648     */
649    public void disconnect() {
650        try {
651            disconnect(new Presence(Presence.Type.unavailable));
652        }
653        catch (NotConnectedException e) {
654            LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
655        }
656    }
657
658    /**
659     * Closes the connection. A custom unavailable presence is sent to the server, followed
660     * by closing the stream. The XMPPConnection can still be used for connecting to the server
661     * again. A custom unavailable presence is useful for communicating offline presence
662     * information such as "On vacation". Typically, just the status text of the presence
663     * stanza(/packet) is set with online information, but most XMPP servers will deliver the full
664     * presence stanza(/packet) with whatever data is set.
665     * 
666     * @param unavailablePresence the presence stanza(/packet) to send during shutdown.
667     * @throws NotConnectedException 
668     */
669    public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
670        sendStanza(unavailablePresence);
671        shutdown();
672        callConnectionClosedListener();
673    }
674
675    /**
676     * Shuts the current connection down.
677     */
678    protected abstract void shutdown();
679
680    @Override
681    public void addConnectionListener(ConnectionListener connectionListener) {
682        if (connectionListener == null) {
683            return;
684        }
685        connectionListeners.add(connectionListener);
686    }
687
688    @Override
689    public void removeConnectionListener(ConnectionListener connectionListener) {
690        connectionListeners.remove(connectionListener);
691    }
692
693    @Override
694    public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException {
695        StanzaFilter packetFilter = new IQReplyFilter(packet, this);
696        // Create the packet collector before sending the packet
697        PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
698        return packetCollector;
699    }
700
701    @Override
702    public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
703                    throws NotConnectedException {
704        // Create the packet collector before sending the packet
705        PacketCollector packetCollector = createPacketCollector(packetFilter);
706        try {
707            // Now we can send the packet as the collector has been created
708            sendStanza(packet);
709        }
710        catch (NotConnectedException | RuntimeException e) {
711            packetCollector.cancel();
712            throw e;
713        }
714        return packetCollector;
715    }
716
717    @Override
718    public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
719        PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
720        return createPacketCollector(configuration);
721    }
722
723    @Override
724    public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
725        PacketCollector collector = new PacketCollector(this, configuration);
726        // Add the collector to the list of active collectors.
727        collectors.add(collector);
728        return collector;
729    }
730
731    @Override
732    public void removePacketCollector(PacketCollector collector) {
733        collectors.remove(collector);
734    }
735
736    @Override
737    @Deprecated
738    public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
739        addAsyncStanzaListener(packetListener, packetFilter);
740    }
741
742    @Override
743    @Deprecated
744    public boolean removePacketListener(StanzaListener packetListener) {
745        return removeAsyncStanzaListener(packetListener);
746    }
747
748    @Override
749    public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
750        if (packetListener == null) {
751            throw new NullPointerException("Packet listener is null.");
752        }
753        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
754        synchronized (syncRecvListeners) {
755            syncRecvListeners.put(packetListener, wrapper);
756        }
757    }
758
759    @Override
760    public boolean removeSyncStanzaListener(StanzaListener packetListener) {
761        synchronized (syncRecvListeners) {
762            return syncRecvListeners.remove(packetListener) != null;
763        }
764    }
765
766    @Override
767    public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
768        if (packetListener == null) {
769            throw new NullPointerException("Packet listener is null.");
770        }
771        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
772        synchronized (asyncRecvListeners) {
773            asyncRecvListeners.put(packetListener, wrapper);
774        }
775    }
776
777    @Override
778    public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
779        synchronized (asyncRecvListeners) {
780            return asyncRecvListeners.remove(packetListener) != null;
781        }
782    }
783
784    @Override
785    public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
786        if (packetListener == null) {
787            throw new NullPointerException("Packet listener is null.");
788        }
789        ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
790        synchronized (sendListeners) {
791            sendListeners.put(packetListener, wrapper);
792        }
793    }
794
795    @Override
796    public void removePacketSendingListener(StanzaListener packetListener) {
797        synchronized (sendListeners) {
798            sendListeners.remove(packetListener);
799        }
800    }
801
802    /**
803     * Process all stanza(/packet) listeners for sending packets.
804     * <p>
805     * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
806     * </p>
807     * 
808     * @param packet the stanza(/packet) to process.
809     */
810    @SuppressWarnings("javadoc")
811    protected void firePacketSendingListeners(final Stanza packet) {
812        final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
813        synchronized (sendListeners) {
814            for (ListenerWrapper listenerWrapper : sendListeners.values()) {
815                if (listenerWrapper.filterMatches(packet)) {
816                    listenersToNotify.add(listenerWrapper.getListener());
817                }
818            }
819        }
820        if (listenersToNotify.isEmpty()) {
821            return;
822        }
823        // Notify in a new thread, because we can
824        asyncGo(new Runnable() {
825            @Override
826            public void run() {
827                for (StanzaListener listener : listenersToNotify) {
828                    try {
829                        listener.processPacket(packet);
830                    }
831                    catch (Exception e) {
832                        LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
833                        continue;
834                    }
835                }
836            }});
837    }
838
839    @Override
840    public void addPacketInterceptor(StanzaListener packetInterceptor,
841            StanzaFilter packetFilter) {
842        if (packetInterceptor == null) {
843            throw new NullPointerException("Packet interceptor is null.");
844        }
845        InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
846        synchronized (interceptors) {
847            interceptors.put(packetInterceptor, interceptorWrapper);
848        }
849    }
850
851    @Override
852    public void removePacketInterceptor(StanzaListener packetInterceptor) {
853        synchronized (interceptors) {
854            interceptors.remove(packetInterceptor);
855        }
856    }
857
858    /**
859     * Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent.
860     * Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it
861     * is important that interceptors perform their work as soon as possible so that the
862     * thread does not remain blocked for a long period.
863     * 
864     * @param packet the stanza(/packet) that is going to be sent to the server
865     */
866    private void firePacketInterceptors(Stanza packet) {
867        List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
868        synchronized (interceptors) {
869            for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
870                if (interceptorWrapper.filterMatches(packet)) {
871                    interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
872                }
873            }
874        }
875        for (StanzaListener interceptor : interceptorsToInvoke) {
876            try {
877                interceptor.processPacket(packet);
878            } catch (Exception e) {
879                LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
880            }
881        }
882    }
883
884    /**
885     * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
886     * by setup the system property <code>smack.debuggerClass</code> to the implementation.
887     * 
888     * @throws IllegalStateException if the reader or writer isn't yet initialized.
889     * @throws IllegalArgumentException if the SmackDebugger can't be loaded.
890     */
891    protected void initDebugger() {
892        if (reader == null || writer == null) {
893            throw new NullPointerException("Reader or writer isn't initialized.");
894        }
895        // If debugging is enabled, we open a window and write out all network traffic.
896        if (config.isDebuggerEnabled()) {
897            if (debugger == null) {
898                debugger = SmackConfiguration.createDebugger(this, writer, reader);
899            }
900
901            if (debugger == null) {
902                LOGGER.severe("Debugging enabled but could not find debugger class");
903            } else {
904                // Obtain new reader and writer from the existing debugger
905                reader = debugger.newConnectionReader(reader);
906                writer = debugger.newConnectionWriter(writer);
907            }
908        }
909    }
910
911    @Override
912    public long getPacketReplyTimeout() {
913        return packetReplyTimeout;
914    }
915
916    @Override
917    public void setPacketReplyTimeout(long timeout) {
918        packetReplyTimeout = timeout;
919    }
920
921    private static boolean replyToUnknownIqDefault = true;
922
923    /**
924     * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
925     * default is 'true'.
926     *
927     * @param replyToUnkownIqDefault
928     * @see #setReplyToUnknownIq(boolean)
929     */
930    public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
931        AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
932    }
933
934    private boolean replyToUnkownIq = replyToUnknownIqDefault;
935
936    /**
937     * Set if Smack will automatically send
938     * {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
939     * registered {@link IQRequestHandler} is received.
940     *
941     * @param replyToUnknownIq
942     */
943    public void setReplyToUnknownIq(boolean replyToUnknownIq) {
944        this.replyToUnkownIq = replyToUnknownIq;
945    }
946
947    protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
948        ParserUtils.assertAtStartTag(parser);
949        int parserDepth = parser.getDepth();
950        Stanza stanza = null;
951        try {
952            stanza = PacketParserUtils.parseStanza(parser);
953        }
954        catch (Exception e) {
955            CharSequence content = PacketParserUtils.parseContentDepth(parser,
956                            parserDepth);
957            UnparsablePacket message = new UnparsablePacket(content, e);
958            ParsingExceptionCallback callback = getParsingExceptionCallback();
959            if (callback != null) {
960                callback.handleUnparsablePacket(message);
961            }
962        }
963        ParserUtils.assertAtEndTag(parser);
964        if (stanza != null) {
965            processPacket(stanza);
966        }
967    }
968
969    /**
970     * Processes a stanza(/packet) after it's been fully parsed by looping through the installed
971     * stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if
972     * they are a match with the filter.
973     *
974     * @param packet the stanza(/packet) to process.
975     */
976    protected void processPacket(Stanza packet) {
977        assert(packet != null);
978        lastStanzaReceived = System.currentTimeMillis();
979        // Deliver the incoming packet to listeners.
980        executorService.submit(new ListenerNotification(packet));
981    }
982
983    /**
984     * A runnable to notify all listeners and stanza(/packet) collectors of a packet.
985     */
986    private class ListenerNotification implements Runnable {
987
988        private final Stanza packet;
989
990        public ListenerNotification(Stanza packet) {
991            this.packet = packet;
992        }
993
994        public void run() {
995            invokePacketCollectorsAndNotifyRecvListeners(packet);
996        }
997    }
998
999    /**
1000     * Invoke {@link PacketCollector#processPacket(Stanza)} for every
1001     * PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
1002     *
1003     * @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about.
1004     */
1005    protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
1006        if (packet instanceof IQ) {
1007            final IQ iq = (IQ) packet;
1008            final IQ.Type type = iq.getType();
1009            switch (type) {
1010            case set:
1011            case get:
1012                final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
1013                IQRequestHandler iqRequestHandler = null;
1014                switch (type) {
1015                case set:
1016                    synchronized (setIqRequestHandler) {
1017                        iqRequestHandler = setIqRequestHandler.get(key);
1018                    }
1019                    break;
1020                case get:
1021                    synchronized (getIqRequestHandler) {
1022                        iqRequestHandler = getIqRequestHandler.get(key);
1023                    }
1024                    break;
1025                default:
1026                    throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
1027                }
1028                if (iqRequestHandler == null) {
1029                    if (!replyToUnkownIq) {
1030                        return;
1031                    }
1032                    // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
1033                    // IQ of type "error" with code 501 ("feature-not-implemented")
1034                    ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError(
1035                                    XMPPError.Condition.feature_not_implemented));
1036                    try {
1037                        sendStanza(errorIQ);
1038                    }
1039                    catch (NotConnectedException e) {
1040                        LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e);
1041                    }
1042                } else {
1043                    ExecutorService executorService = null;
1044                    switch (iqRequestHandler.getMode()) {
1045                    case sync:
1046                        executorService = singleThreadedExecutorService;
1047                        break;
1048                    case async:
1049                        executorService = cachedExecutorService;
1050                        break;
1051                    }
1052                    final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
1053                    executorService.execute(new Runnable() {
1054                        @Override
1055                        public void run() {
1056                            IQ response = finalIqRequestHandler.handleIQRequest(iq);
1057                            if (response == null) {
1058                                // It is not ideal if the IQ request handler does not return an IQ response, because RFC
1059                                // 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
1060                                // file transfer one, does not always return a result, so we need to handle this case.
1061                                // Also sometimes a request handler may decide that it's better to not send a response,
1062                                // e.g. to avoid presence leaks.
1063                                return;
1064                            }
1065                            try {
1066                                sendStanza(response);
1067                            }
1068                            catch (NotConnectedException e) {
1069                                LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e);
1070                            }
1071                        }
1072                    });
1073                    // The following returns makes it impossible for packet listeners and collectors to
1074                    // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
1075                    // desired behavior.
1076                    return;
1077                }
1078                break;
1079            default:
1080                break;
1081            }
1082        }
1083
1084        // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
1085        // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
1086        // their own thread.
1087        final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
1088        synchronized (asyncRecvListeners) {
1089            for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
1090                if (listenerWrapper.filterMatches(packet)) {
1091                    listenersToNotify.add(listenerWrapper.getListener());
1092                }
1093            }
1094        }
1095
1096        for (final StanzaListener listener : listenersToNotify) {
1097            asyncGo(new Runnable() {
1098                @Override
1099                public void run() {
1100                    try {
1101                        listener.processPacket(packet);
1102                    } catch (Exception e) {
1103                        LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
1104                    }
1105                }
1106            });
1107        }
1108
1109        // Loop through all collectors and notify the appropriate ones.
1110        for (PacketCollector collector: collectors) {
1111            collector.processPacket(packet);
1112        }
1113
1114        // Notify the receive listeners interested in the packet
1115        listenersToNotify.clear();
1116        synchronized (syncRecvListeners) {
1117            for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
1118                if (listenerWrapper.filterMatches(packet)) {
1119                    listenersToNotify.add(listenerWrapper.getListener());
1120                }
1121            }
1122        }
1123
1124        // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
1125        // threaded executor service and therefore keeps the order.
1126        singleThreadedExecutorService.execute(new Runnable() {
1127            @Override
1128            public void run() {
1129                for (StanzaListener listener : listenersToNotify) {
1130                    try {
1131                        listener.processPacket(packet);
1132                    } catch(NotConnectedException e) {
1133                        LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
1134                        break;
1135                    } catch (Exception e) {
1136                        LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
1137                    }
1138                }
1139            }
1140        });
1141
1142    }
1143
1144    /**
1145     * Sets whether the connection has already logged in the server. This method assures that the
1146     * {@link #wasAuthenticated} flag is never reset once it has ever been set.
1147     * 
1148     */
1149    protected void setWasAuthenticated() {
1150        // Never reset the flag if the connection has ever been authenticated
1151        if (!wasAuthenticated) {
1152            wasAuthenticated = authenticated;
1153        }
1154    }
1155
1156    protected void callConnectionConnectedListener() {
1157        for (ConnectionListener listener : connectionListeners) {
1158            listener.connected(this);
1159        }
1160    }
1161
1162    protected void callConnectionAuthenticatedListener(boolean resumed) {
1163        for (ConnectionListener listener : connectionListeners) {
1164            try {
1165                listener.authenticated(this, resumed);
1166            } catch (Exception e) {
1167                // Catch and print any exception so we can recover
1168                // from a faulty listener and finish the shutdown process
1169                LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
1170            }
1171        }
1172    }
1173
1174    void callConnectionClosedListener() {
1175        for (ConnectionListener listener : connectionListeners) {
1176            try {
1177                listener.connectionClosed();
1178            }
1179            catch (Exception e) {
1180                // Catch and print any exception so we can recover
1181                // from a faulty listener and finish the shutdown process
1182                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
1183            }
1184        }
1185    }
1186
1187    protected void callConnectionClosedOnErrorListener(Exception e) {
1188        LOGGER.log(Level.WARNING, "Connection closed with error", e);
1189        for (ConnectionListener listener : connectionListeners) {
1190            try {
1191                listener.connectionClosedOnError(e);
1192            }
1193            catch (Exception e2) {
1194                // Catch and print any exception so we can recover
1195                // from a faulty listener
1196                LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
1197            }
1198        }
1199    }
1200
1201    /**
1202     * Sends a notification indicating that the connection was reconnected successfully.
1203     */
1204    protected void notifyReconnection() {
1205        // Notify connection listeners of the reconnection.
1206        for (ConnectionListener listener : connectionListeners) {
1207            try {
1208                listener.reconnectionSuccessful();
1209            }
1210            catch (Exception e) {
1211                // Catch and print any exception so we can recover
1212                // from a faulty listener
1213                LOGGER.log(Level.WARNING, "notifyReconnection()", e);
1214            }
1215        }
1216    }
1217
1218    /**
1219     * A wrapper class to associate a stanza(/packet) filter with a listener.
1220     */
1221    protected static class ListenerWrapper {
1222
1223        private final StanzaListener packetListener;
1224        private final StanzaFilter packetFilter;
1225
1226        /**
1227         * Create a class which associates a stanza(/packet) filter with a listener.
1228         * 
1229         * @param packetListener the stanza(/packet) listener.
1230         * @param packetFilter the associated filter or null if it listen for all packets.
1231         */
1232        public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
1233            this.packetListener = packetListener;
1234            this.packetFilter = packetFilter;
1235        }
1236
1237        public boolean filterMatches(Stanza packet) {
1238            return packetFilter == null || packetFilter.accept(packet);
1239        }
1240
1241        public StanzaListener getListener() {
1242            return packetListener;
1243        }
1244    }
1245
1246    /**
1247     * A wrapper class to associate a stanza(/packet) filter with an interceptor.
1248     */
1249    protected static class InterceptorWrapper {
1250
1251        private final StanzaListener packetInterceptor;
1252        private final StanzaFilter packetFilter;
1253
1254        /**
1255         * Create a class which associates a stanza(/packet) filter with an interceptor.
1256         * 
1257         * @param packetInterceptor the interceptor.
1258         * @param packetFilter the associated filter or null if it intercepts all packets.
1259         */
1260        public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
1261            this.packetInterceptor = packetInterceptor;
1262            this.packetFilter = packetFilter;
1263        }
1264
1265        public boolean filterMatches(Stanza packet) {
1266            return packetFilter == null || packetFilter.accept(packet);
1267        }
1268
1269        public StanzaListener getInterceptor() {
1270            return packetInterceptor;
1271        }
1272    }
1273
1274    @Override
1275    public int getConnectionCounter() {
1276        return connectionCounterValue;
1277    }
1278
1279    @Override
1280    public void setFromMode(FromMode fromMode) {
1281        this.fromMode = fromMode;
1282    }
1283
1284    @Override
1285    public FromMode getFromMode() {
1286        return this.fromMode;
1287    }
1288
1289    @Override
1290    protected void finalize() throws Throwable {
1291        LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter()
1292                        + "): Shutting down executor services");
1293        try {
1294            // It's usually not a good idea to rely on finalize. But this is the easiest way to
1295            // avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
1296            // reference to their ExecutorService which prevents the ExecutorService from being
1297            // gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
1298            // listenerExecutor ExecutorService call not be gc'ed until it got shut down.
1299            executorService.shutdownNow();
1300            cachedExecutorService.shutdown();
1301            removeCallbacksService.shutdownNow();
1302            singleThreadedExecutorService.shutdownNow();
1303        } catch (Throwable t) {
1304            LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
1305        }
1306        finally {
1307            super.finalize();
1308        }
1309    }
1310
1311    protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException,
1312                    IOException, SmackException {
1313        streamFeatures.clear();
1314        final int initialDepth = parser.getDepth();
1315        while (true) {
1316            int eventType = parser.next();
1317
1318            if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
1319                ExtensionElement streamFeature = null;
1320                String name = parser.getName();
1321                String namespace = parser.getNamespace();
1322                switch (name) {
1323                case StartTls.ELEMENT:
1324                    streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
1325                    break;
1326                case Mechanisms.ELEMENT:
1327                    streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
1328                    break;
1329                case Bind.ELEMENT:
1330                    streamFeature = Bind.Feature.INSTANCE;
1331                    break;
1332                case Session.ELEMENT:
1333                    streamFeature = PacketParserUtils.parseSessionFeature(parser);
1334                    break;
1335                case Compress.Feature.ELEMENT:
1336                    streamFeature = PacketParserUtils.parseCompressionFeature(parser);
1337                    break;
1338                default:
1339                    ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
1340                    if (provider != null) {
1341                        streamFeature = provider.parse(parser);
1342                    }
1343                    break;
1344                }
1345                if (streamFeature != null) {
1346                    addStreamFeature(streamFeature);
1347                }
1348            }
1349            else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
1350                break;
1351            }
1352        }
1353
1354        if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
1355            // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
1356            if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
1357                            || config.getSecurityMode() == SecurityMode.disabled) {
1358                saslFeatureReceived.reportSuccess();
1359            }
1360        }
1361
1362        // If the server reported the bind feature then we are that that we did SASL and maybe
1363        // STARTTLS. We can then report that the last 'stream:features' have been parsed
1364        if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
1365            if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
1366                            || !config.isCompressionEnabled()) {
1367                // This was was last features from the server is either it did not contain
1368                // compression or if we disabled it
1369                lastFeaturesReceived.reportSuccess();
1370            }
1371        }
1372        afterFeaturesReceived();
1373    }
1374
1375    protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
1376        // Default implementation does nothing
1377    }
1378
1379    @SuppressWarnings("unchecked")
1380    @Override
1381    public <F extends ExtensionElement> F getFeature(String element, String namespace) {
1382        return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
1383    }
1384
1385    @Override
1386    public boolean hasFeature(String element, String namespace) {
1387        return getFeature(element, namespace) != null;
1388    }
1389
1390    private void addStreamFeature(ExtensionElement feature) {
1391        String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
1392        streamFeatures.put(key, feature);
1393    }
1394
1395    @Override
1396    public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
1397                    StanzaListener callback) throws NotConnectedException {
1398        sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
1399    }
1400
1401    @Override
1402    public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
1403                    StanzaListener callback, ExceptionCallback exceptionCallback)
1404                    throws NotConnectedException {
1405        sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
1406                        getPacketReplyTimeout());
1407    }
1408
1409    @Override
1410    public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
1411                    final StanzaListener callback, final ExceptionCallback exceptionCallback,
1412                    long timeout) throws NotConnectedException {
1413        Objects.requireNonNull(stanza, "stanza must not be null");
1414        // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
1415        // disallow it here in the async API as it makes no sense
1416        Objects.requireNonNull(replyFilter, "replyFilter must not be null");
1417        Objects.requireNonNull(callback, "callback must not be null");
1418
1419        final StanzaListener packetListener = new StanzaListener() {
1420            @Override
1421            public void processPacket(Stanza packet) throws NotConnectedException {
1422                try {
1423                    XMPPErrorException.ifHasErrorThenThrow(packet);
1424                    callback.processPacket(packet);
1425                }
1426                catch (XMPPErrorException e) {
1427                    if (exceptionCallback != null) {
1428                        exceptionCallback.processException(e);
1429                    }
1430                }
1431                finally {
1432                    removeAsyncStanzaListener(this);
1433                }
1434            }
1435        };
1436        removeCallbacksService.schedule(new Runnable() {
1437            @Override
1438            public void run() {
1439                boolean removed = removeAsyncStanzaListener(packetListener);
1440                // If the packetListener got removed, then it was never run and
1441                // we never received a response, inform the exception callback
1442                if (removed && exceptionCallback != null) {
1443                    exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
1444                }
1445            }
1446        }, timeout, TimeUnit.MILLISECONDS);
1447        addAsyncStanzaListener(packetListener, replyFilter);
1448        sendStanza(stanza);
1449    }
1450
1451    @Override
1452    public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
1453                    throws NotConnectedException {
1454        sendIqWithResponseCallback(iqRequest, callback, null);
1455    }
1456
1457    @Override
1458    public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
1459                    ExceptionCallback exceptionCallback) throws NotConnectedException {
1460        sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
1461    }
1462
1463    @Override
1464    public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
1465                    final ExceptionCallback exceptionCallback, long timeout)
1466                    throws NotConnectedException {
1467        StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
1468        sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
1469    }
1470
1471    @Override
1472    public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
1473        final StanzaListener packetListener = new StanzaListener() {
1474            @Override
1475            public void processPacket(Stanza packet) throws NotConnectedException {
1476                try {
1477                    callback.processPacket(packet);
1478                } finally {
1479                    removeSyncStanzaListener(this);
1480                }
1481            }
1482        };
1483        addSyncStanzaListener(packetListener, packetFilter);
1484        removeCallbacksService.schedule(new Runnable() {
1485            @Override
1486            public void run() {
1487                removeSyncStanzaListener(packetListener);
1488            }
1489        }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
1490    }
1491
1492    @Override
1493    public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
1494        final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
1495        switch (iqRequestHandler.getType()) {
1496        case set:
1497            synchronized (setIqRequestHandler) {
1498                return setIqRequestHandler.put(key, iqRequestHandler);
1499            }
1500        case get:
1501            synchronized (getIqRequestHandler) {
1502                return getIqRequestHandler.put(key, iqRequestHandler);
1503            }
1504        default:
1505            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
1506        }
1507    }
1508
1509    @Override
1510    public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
1511        return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
1512                        iqRequestHandler.getType());
1513    }
1514
1515    @Override
1516    public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
1517        final String key = XmppStringUtils.generateKey(element, namespace);
1518        switch (type) {
1519        case set:
1520            synchronized (setIqRequestHandler) {
1521                return setIqRequestHandler.remove(key);
1522            }
1523        case get:
1524            synchronized (getIqRequestHandler) {
1525                return getIqRequestHandler.remove(key);
1526            }
1527        default:
1528            throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
1529        }
1530    }
1531
1532    private long lastStanzaReceived;
1533
1534    public long getLastStanzaReceived() {
1535        return lastStanzaReceived;
1536    }
1537
1538    /**
1539     * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
1540     * stanza
1541     * 
1542     * @param callback the callback to install
1543     */
1544    public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
1545        parsingExceptionCallback = callback;
1546    }
1547
1548    /**
1549     * Get the current active parsing exception callback.
1550     *  
1551     * @return the active exception callback or null if there is none
1552     */
1553    public ParsingExceptionCallback getParsingExceptionCallback() {
1554        return parsingExceptionCallback;
1555    }
1556
1557    protected final void asyncGo(Runnable runnable) {
1558        cachedExecutorService.execute(runnable);
1559    }
1560
1561    protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
1562        return removeCallbacksService.schedule(runnable, delay, unit);
1563    }
1564}