AbstractXMPPConnection.java

  1. /**
  2.  *
  3.  * Copyright 2009 Jive Software.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack;

  18. import java.io.IOException;
  19. import java.io.Reader;
  20. import java.io.Writer;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.HashMap;
  24. import java.util.LinkedHashMap;
  25. import java.util.LinkedList;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.concurrent.ArrayBlockingQueue;
  30. import java.util.concurrent.ConcurrentLinkedQueue;
  31. import java.util.concurrent.CopyOnWriteArraySet;
  32. import java.util.concurrent.ExecutorService;
  33. import java.util.concurrent.Executors;
  34. import java.util.concurrent.ScheduledExecutorService;
  35. import java.util.concurrent.ScheduledFuture;
  36. import java.util.concurrent.ThreadPoolExecutor;
  37. import java.util.concurrent.TimeUnit;
  38. import java.util.concurrent.atomic.AtomicInteger;
  39. import java.util.concurrent.locks.Lock;
  40. import java.util.concurrent.locks.ReentrantLock;
  41. import java.util.logging.Level;
  42. import java.util.logging.Logger;

  43. import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
  44. import org.jivesoftware.smack.SmackException.AlreadyConnectedException;
  45. import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
  46. import org.jivesoftware.smack.SmackException.NoResponseException;
  47. import org.jivesoftware.smack.SmackException.NotConnectedException;
  48. import org.jivesoftware.smack.SmackException.ConnectionException;
  49. import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;
  50. import org.jivesoftware.smack.SmackException.SecurityRequiredException;
  51. import org.jivesoftware.smack.XMPPException.XMPPErrorException;
  52. import org.jivesoftware.smack.compress.packet.Compress;
  53. import org.jivesoftware.smack.compression.XMPPInputOutputStream;
  54. import org.jivesoftware.smack.debugger.SmackDebugger;
  55. import org.jivesoftware.smack.filter.IQReplyFilter;
  56. import org.jivesoftware.smack.filter.StanzaFilter;
  57. import org.jivesoftware.smack.filter.StanzaIdFilter;
  58. import org.jivesoftware.smack.iqrequest.IQRequestHandler;
  59. import org.jivesoftware.smack.packet.Bind;
  60. import org.jivesoftware.smack.packet.ErrorIQ;
  61. import org.jivesoftware.smack.packet.IQ;
  62. import org.jivesoftware.smack.packet.Mechanisms;
  63. import org.jivesoftware.smack.packet.Stanza;
  64. import org.jivesoftware.smack.packet.ExtensionElement;
  65. import org.jivesoftware.smack.packet.Presence;
  66. import org.jivesoftware.smack.packet.Session;
  67. import org.jivesoftware.smack.packet.StartTls;
  68. import org.jivesoftware.smack.packet.PlainStreamElement;
  69. import org.jivesoftware.smack.packet.XMPPError;
  70. import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
  71. import org.jivesoftware.smack.parsing.UnparsablePacket;
  72. import org.jivesoftware.smack.provider.ExtensionElementProvider;
  73. import org.jivesoftware.smack.provider.ProviderManager;
  74. import org.jivesoftware.smack.util.DNSUtil;
  75. import org.jivesoftware.smack.util.Objects;
  76. import org.jivesoftware.smack.util.PacketParserUtils;
  77. import org.jivesoftware.smack.util.ParserUtils;
  78. import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
  79. import org.jivesoftware.smack.util.StringUtils;
  80. import org.jivesoftware.smack.util.dns.HostAddress;
  81. import org.jxmpp.jid.DomainBareJid;
  82. import org.jxmpp.jid.FullJid;
  83. import org.jxmpp.jid.Jid;
  84. import org.jxmpp.util.XmppStringUtils;
  85. import org.xmlpull.v1.XmlPullParser;


  86. public abstract class AbstractXMPPConnection implements XMPPConnection {
  87.     private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName());

  88.     /**
  89.      * Counter to uniquely identify connections that are created.
  90.      */
  91.     private final static AtomicInteger connectionCounter = new AtomicInteger(0);

  92.     static {
  93.         // Ensure the SmackConfiguration class is loaded by calling a method in it.
  94.         SmackConfiguration.getVersion();
  95.     }

  96.     /**
  97.      * Get the collection of listeners that are interested in connection creation events.
  98.      *
  99.      * @return a collection of listeners interested on new connections.
  100.      */
  101.     protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() {
  102.         return XMPPConnectionRegistry.getConnectionCreationListeners();
  103.     }
  104.  
  105.     /**
  106.      * A collection of ConnectionListeners which listen for connection closing
  107.      * and reconnection events.
  108.      */
  109.     protected final Set<ConnectionListener> connectionListeners =
  110.             new CopyOnWriteArraySet<ConnectionListener>();

  111.     /**
  112.      * A collection of PacketCollectors which collects packets for a specified filter
  113.      * and perform blocking and polling operations on the result queue.
  114.      * <p>
  115.      * We use a ConcurrentLinkedQueue here, because its Iterator is weakly
  116.      * consistent and we want {@link #invokePacketCollectors(Stanza)} for-each
  117.      * loop to be lock free. As drawback, removing a PacketCollector is O(n).
  118.      * The alternative would be a synchronized HashSet, but this would mean a
  119.      * synchronized block around every usage of <code>collectors</code>.
  120.      * </p>
  121.      */
  122.     private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>();

  123.     /**
  124.      * List of PacketListeners that will be notified synchronously when a new packet was received.
  125.      */
  126.     private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>();

  127.     /**
  128.      * List of PacketListeners that will be notified asynchronously when a new packet was received.
  129.      */
  130.     private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>();

  131.     /**
  132.      * List of PacketListeners that will be notified when a new packet was sent.
  133.      */
  134.     private final Map<StanzaListener, ListenerWrapper> sendListeners =
  135.             new HashMap<StanzaListener, ListenerWrapper>();

  136.     /**
  137.      * List of PacketListeners that will be notified when a new packet is about to be
  138.      * sent to the server. These interceptors may modify the packet before it is being
  139.      * actually sent to the server.
  140.      */
  141.     private final Map<StanzaListener, InterceptorWrapper> interceptors =
  142.             new HashMap<StanzaListener, InterceptorWrapper>();

  143.     protected final Lock connectionLock = new ReentrantLock();

  144.     protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>();

  145.     /**
  146.      * The full JID of the authenticated user, as returned by the resource binding response of the server.
  147.      * <p>
  148.      * It is important that we don't infer the user from the login() arguments and the configurations service name, as,
  149.      * for example, when SASL External is used, the username is not given to login but taken from the 'external'
  150.      * certificate.
  151.      * </p>
  152.      */
  153.     protected FullJid user;

  154.     protected boolean connected = false;

  155.     /**
  156.      * The stream ID, see RFC 6120 ยง 4.7.3
  157.      */
  158.     protected String streamId;

  159.     /**
  160.      *
  161.      */
  162.     private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout();

  163.     /**
  164.      * The SmackDebugger allows to log and debug XML traffic.
  165.      */
  166.     protected SmackDebugger debugger = null;

  167.     /**
  168.      * The Reader which is used for the debugger.
  169.      */
  170.     protected Reader reader;

  171.     /**
  172.      * The Writer which is used for the debugger.
  173.      */
  174.     protected Writer writer;

  175.     /**
  176.      * Set to success if the last features stanza from the server has been parsed. A XMPP connection
  177.      * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature
  178.      * stanza is send by the server. This is set to true once the last feature stanza has been
  179.      * parsed.
  180.      */
  181.     protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>(
  182.                     AbstractXMPPConnection.this);

  183.     /**
  184.      * Set to success if the sasl feature has been received.
  185.      */
  186.     protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>(
  187.                     AbstractXMPPConnection.this);
  188.  
  189.     /**
  190.      * The SASLAuthentication manager that is responsible for authenticating with the server.
  191.      */
  192.     protected SASLAuthentication saslAuthentication = new SASLAuthentication(this);

  193.     /**
  194.      * A number to uniquely identify connections that are created. This is distinct from the
  195.      * connection ID, which is a value sent by the server once a connection is made.
  196.      */
  197.     protected final int connectionCounterValue = connectionCounter.getAndIncrement();

  198.     /**
  199.      * Holds the initial configuration used while creating the connection.
  200.      */
  201.     protected final ConnectionConfiguration config;

  202.     /**
  203.      * Defines how the from attribute of outgoing stanzas should be handled.
  204.      */
  205.     private FromMode fromMode = FromMode.OMITTED;

  206.     protected XMPPInputOutputStream compressionHandler;

  207.     private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback();

  208.     /**
  209.      * ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is
  210.      * important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the
  211.      * PacketListeners are invoked in the same order the stanzas arrived.
  212.      */
  213.     private final ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
  214.                     new ArrayBlockingQueue<Runnable>(100), new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor"));

  215.     /**
  216.      * This scheduled thread pool executor is used to remove pending callbacks.
  217.      */
  218.     private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor(
  219.                     new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks"));

  220.     /**
  221.      * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set
  222.      * them 'daemon'.
  223.      */
  224.     private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool(
  225.                     // @formatter:off
  226.                     new SmackExecutorThreadFactory(    // threadFactory
  227.                                     connectionCounterValue,
  228.                                     "Cached Executor"
  229.                                     )
  230.                     // @formatter:on
  231.                     );

  232.     /**
  233.      * A executor service used to invoke the callbacks of synchronous packet listeners. We use a executor service to
  234.      * decouple incoming stanza processing from callback invocation. It is important that order of callback invocation
  235.      * is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service.
  236.      */
  237.     private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory(
  238.                     getConnectionCounter(), "Single Threaded Executor"));

  239.     /**
  240.      * The used host to establish the connection to
  241.      */
  242.     protected String host;

  243.     /**
  244.      * The used port to establish the connection to
  245.      */
  246.     protected int port;

  247.     /**
  248.      * Flag that indicates if the user is currently authenticated with the server.
  249.      */
  250.     protected boolean authenticated = false;

  251.     /**
  252.      * Flag that indicates if the user was authenticated with the server when the connection
  253.      * to the server was closed (abruptly or not).
  254.      */
  255.     protected boolean wasAuthenticated = false;

  256.     private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>();
  257.     private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>();

  258.     /**
  259.      * Create a new XMPPConnection to an XMPP server.
  260.      *
  261.      * @param configuration The configuration which is used to establish the connection.
  262.      */
  263.     protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
  264.         config = configuration;
  265.     }

  266.     protected ConnectionConfiguration getConfiguration() {
  267.         return config;
  268.     }

  269.     @Override
  270.     public DomainBareJid getServiceName() {
  271.         if (serviceName != null) {
  272.             return serviceName;
  273.         }
  274.         return config.getServiceName();
  275.     }

  276.     @Override
  277.     public String getHost() {
  278.         return host;
  279.     }

  280.     @Override
  281.     public int getPort() {
  282.         return port;
  283.     }

  284.     @Override
  285.     public abstract boolean isSecureConnection();

  286.     protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException;

  287.     @Override
  288.     public abstract void send(PlainStreamElement element) throws NotConnectedException, InterruptedException;

  289.     @Override
  290.     public abstract boolean isUsingCompression();

  291.     /**
  292.      * Establishes a connection to the XMPP server and performs an automatic login
  293.      * only if the previous connection state was logged (authenticated). It basically
  294.      * creates and maintains a connection to the server.
  295.      * <p>
  296.      * Listeners will be preserved from a previous connection.
  297.      *
  298.      * @throws XMPPException if an error occurs on the XMPP protocol level.
  299.      * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
  300.      * @throws IOException
  301.      * @throws ConnectionException with detailed information about the failed connection.
  302.      * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
  303.      * @throws InterruptedException
  304.      */
  305.     public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException, InterruptedException {
  306.         // Check if not already connected
  307.         throwAlreadyConnectedExceptionIfAppropriate();

  308.         // Reset the connection state
  309.         saslAuthentication.init();
  310.         saslFeatureReceived.init();
  311.         lastFeaturesReceived.init();
  312.         streamId = null;

  313.         // Perform the actual connection to the XMPP service
  314.         connectInternal();
  315.         return this;
  316.     }

  317.     /**
  318.      * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their
  319.      * way of XMPP connection establishment. Implementations are required to perform an automatic
  320.      * login if the previous connection state was logged (authenticated).
  321.      *
  322.      * @throws SmackException
  323.      * @throws IOException
  324.      * @throws XMPPException
  325.      * @throws InterruptedException
  326.      */
  327.     protected abstract void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException;

  328.     private String usedUsername, usedPassword, usedResource;

  329.     /**
  330.      * Logs in to the server using the strongest SASL mechanism supported by
  331.      * the server. If more than the connection's default packet timeout elapses in each step of the
  332.      * authentication process without a response from the server, a
  333.      * {@link SmackException.NoResponseException} will be thrown.
  334.      * <p>
  335.      * Before logging in (i.e. authenticate) to the server the connection must be connected
  336.      * by calling {@link #connect}.
  337.      * </p>
  338.      * <p>
  339.      * It is possible to log in without sending an initial available presence by using
  340.      * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}.
  341.      * Finally, if you want to not pass a password and instead use a more advanced mechanism
  342.      * while using SASL then you may be interested in using
  343.      * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}.
  344.      * For more advanced login settings see {@link ConnectionConfiguration}.
  345.      * </p>
  346.      *
  347.      * @throws XMPPException if an error occurs on the XMPP protocol level.
  348.      * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
  349.      * @throws IOException if an I/O error occurs during login.
  350.      * @throws InterruptedException
  351.      */
  352.     public synchronized void login() throws XMPPException, SmackException, IOException, InterruptedException {
  353.         if (isAnonymous()) {
  354.             throwNotConnectedExceptionIfAppropriate();
  355.             throwAlreadyLoggedInExceptionIfAppropriate();
  356.             loginAnonymously();
  357.         } else {
  358.             // The previously used username, password and resource take over precedence over the
  359.             // ones from the connection configuration
  360.             CharSequence username = usedUsername != null ? usedUsername : config.getUsername();
  361.             String password = usedPassword != null ? usedPassword : config.getPassword();
  362.             String resource = usedResource != null ? usedResource : config.getResource();
  363.             login(username, password, resource);
  364.         }
  365.     }

  366.     /**
  367.      * Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection
  368.      * configuration.
  369.      *
  370.      * @param username
  371.      * @param password
  372.      * @throws XMPPException
  373.      * @throws SmackException
  374.      * @throws IOException
  375.      * @throws InterruptedException
  376.      * @see #login
  377.      */
  378.     public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException,
  379.                     IOException, InterruptedException {
  380.         login(username, password, config.getResource());
  381.     }

  382.     /**
  383.      * Login with the given username (authorization identity). You may omit the password if a callback handler is used.
  384.      * If resource is null, then the server will generate one.
  385.      *
  386.      * @param username
  387.      * @param password
  388.      * @param resource
  389.      * @throws XMPPException
  390.      * @throws SmackException
  391.      * @throws IOException
  392.      * @throws InterruptedException
  393.      * @see #login
  394.      */
  395.     public synchronized void login(CharSequence username, String password, String resource) throws XMPPException,
  396.                     SmackException, IOException, InterruptedException {
  397.         if (!config.allowNullOrEmptyUsername) {
  398.             StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty");
  399.         }
  400.         throwNotConnectedExceptionIfAppropriate();
  401.         throwAlreadyLoggedInExceptionIfAppropriate();
  402.         usedUsername = username != null ? username.toString() : null;
  403.         usedPassword = password;
  404.         usedResource = resource;
  405.         loginNonAnonymously(usedUsername, usedPassword, usedResource);
  406.     }

  407.     protected abstract void loginNonAnonymously(String username, String password, String resource)
  408.                     throws XMPPException, SmackException, IOException, InterruptedException;

  409.     protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException, InterruptedException;

  410.     @Override
  411.     public final boolean isConnected() {
  412.         return connected;
  413.     }

  414.     @Override
  415.     public final boolean isAuthenticated() {
  416.         return authenticated;
  417.     }

  418.     @Override
  419.     public final FullJid getUser() {
  420.         return user;
  421.     }

  422.     @Override
  423.     public String getStreamId() {
  424.         if (!isConnected()) {
  425.             return null;
  426.         }
  427.         return streamId;
  428.     }

  429.     // TODO remove this suppression once "disable legacy session" code has been removed from Smack
  430.     @SuppressWarnings("deprecation")
  431.     protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
  432.                     IOException, SmackException, InterruptedException {

  433.         // Wait until either:
  434.         // - the servers last features stanza has been parsed
  435.         // - the timeout occurs
  436.         LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
  437.         lastFeaturesReceived.checkIfSuccessOrWait();


  438.         if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
  439.             // Server never offered resource binding, which is REQURIED in XMPP client and
  440.             // server implementations as per RFC6120 7.2
  441.             throw new ResourceBindingNotOfferedException();
  442.         }

  443.         // Resource binding, see RFC6120 7.
  444.         // Note that we can not use IQReplyFilter here, since the users full JID is not yet
  445.         // available. It will become available right after the resource has been successfully bound.
  446.         Bind bindResource = Bind.newSet(resource);
  447.         PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
  448.         Bind response = packetCollector.nextResultOrThrow();
  449.         // Set the connections user to the result of resource binding. It is important that we don't infer the user
  450.         // from the login() arguments and the configurations service name, as, for example, when SASL External is used,
  451.         // the username is not given to login but taken from the 'external' certificate.
  452.         user = response.getJid();
  453.         serviceName = user.asDomainBareJid();

  454.         Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
  455.         // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
  456.         // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
  457.         if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) {
  458.             Session session = new Session();
  459.             packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session);
  460.             packetCollector.nextResultOrThrow();
  461.         }
  462.     }

  463.     protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException, InterruptedException {
  464.         // Indicate that we're now authenticated.
  465.         this.authenticated = true;

  466.         // If debugging is enabled, change the the debug window title to include the
  467.         // name we are now logged-in as.
  468.         // If DEBUG was set to true AFTER the connection was created the debugger
  469.         // will be null
  470.         if (config.isDebuggerEnabled() && debugger != null) {
  471.             debugger.userHasLogged(user);
  472.         }
  473.         callConnectionAuthenticatedListener(resumed);

  474.         // Set presence to online. It is important that this is done after
  475.         // callConnectionAuthenticatedListener(), as this call will also
  476.         // eventually load the roster. And we should load the roster before we
  477.         // send the initial presence.
  478.         if (config.isSendPresence() && !resumed) {
  479.             sendStanza(new Presence(Presence.Type.available));
  480.         }
  481.     }

  482.     @Override
  483.     public final boolean isAnonymous() {
  484.         return config.getUsername() == null && usedUsername == null
  485.                         && !config.allowNullOrEmptyUsername;
  486.     }

  487.     private DomainBareJid serviceName;

  488.     protected List<HostAddress> hostAddresses;

  489.     /**
  490.      * Populates {@link #hostAddresses} with at least one host address.
  491.      *
  492.      * @return a list of host addresses where DNS (SRV) RR resolution failed.
  493.      */
  494.     protected List<HostAddress> populateHostAddresses() {
  495.         List<HostAddress> failedAddresses = new LinkedList<>();
  496.         // N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName
  497.         if (config.host != null) {
  498.             hostAddresses = new ArrayList<HostAddress>(1);
  499.             HostAddress hostAddress;
  500.             hostAddress = new HostAddress(config.host, config.port);
  501.             hostAddresses.add(hostAddress);
  502.         } else {
  503.             hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName.toString(), failedAddresses);
  504.         }
  505.         // If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the
  506.         // config.host one or the host representing the service name by DNSUtil
  507.         assert(!hostAddresses.isEmpty());
  508.         return failedAddresses;
  509.     }

  510.     protected Lock getConnectionLock() {
  511.         return connectionLock;
  512.     }

  513.     protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException {
  514.         if (!isConnected()) {
  515.             throw new NotConnectedException();
  516.         }
  517.     }

  518.     protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException {
  519.         if (isConnected()) {
  520.             throw new AlreadyConnectedException();
  521.         }
  522.     }

  523.     protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException {
  524.         if (isAuthenticated()) {
  525.             throw new AlreadyLoggedInException();
  526.         }
  527.     }

  528.     @Deprecated
  529.     @Override
  530.     public void sendPacket(Stanza packet) throws NotConnectedException, InterruptedException {
  531.         sendStanza(packet);
  532.     }

  533.     @Override
  534.     public void sendStanza(Stanza packet) throws NotConnectedException, InterruptedException {
  535.         Objects.requireNonNull(packet, "Packet must not be null");

  536.         throwNotConnectedExceptionIfAppropriate();
  537.         switch (fromMode) {
  538.         case OMITTED:
  539.             packet.setFrom((Jid) null);
  540.             break;
  541.         case USER:
  542.             packet.setFrom(getUser());
  543.             break;
  544.         case UNCHANGED:
  545.         default:
  546.             break;
  547.         }
  548.         // Invoke interceptors for the new packet that is about to be sent. Interceptors may modify
  549.         // the content of the packet.
  550.         firePacketInterceptors(packet);
  551.         sendStanzaInternal(packet);
  552.     }

  553.     /**
  554.      * Returns the SASLAuthentication manager that is responsible for authenticating with
  555.      * the server.
  556.      *
  557.      * @return the SASLAuthentication manager that is responsible for authenticating with
  558.      *         the server.
  559.      */
  560.     protected SASLAuthentication getSASLAuthentication() {
  561.         return saslAuthentication;
  562.     }

  563.     /**
  564.      * Closes the connection by setting presence to unavailable then closing the connection to
  565.      * the XMPP server. The XMPPConnection can still be used for connecting to the server
  566.      * again.
  567.      *
  568.      */
  569.     public void disconnect() {
  570.         try {
  571.             disconnect(new Presence(Presence.Type.unavailable));
  572.         }
  573.         catch (NotConnectedException e) {
  574.             LOGGER.log(Level.FINEST, "Connection is already disconnected", e);
  575.         }
  576.     }

  577.     /**
  578.      * Closes the connection. A custom unavailable presence is sent to the server, followed
  579.      * by closing the stream. The XMPPConnection can still be used for connecting to the server
  580.      * again. A custom unavailable presence is useful for communicating offline presence
  581.      * information such as "On vacation". Typically, just the status text of the presence
  582.      * packet is set with online information, but most XMPP servers will deliver the full
  583.      * presence packet with whatever data is set.
  584.      *
  585.      * @param unavailablePresence the presence packet to send during shutdown.
  586.      * @throws NotConnectedException
  587.      */
  588.     public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException {
  589.         try {
  590.             sendStanza(unavailablePresence);
  591.         }
  592.         catch (InterruptedException e) {
  593.             LOGGER.log(Level.FINE, "Was interrupted while sending unavailable presence. Continuing to disconnect the connection", e);
  594.         }
  595.         shutdown();
  596.         callConnectionClosedListener();
  597.     }

  598.     /**
  599.      * Shuts the current connection down.
  600.      */
  601.     protected abstract void shutdown();

  602.     @Override
  603.     public void addConnectionListener(ConnectionListener connectionListener) {
  604.         if (connectionListener == null) {
  605.             return;
  606.         }
  607.         connectionListeners.add(connectionListener);
  608.     }

  609.     @Override
  610.     public void removeConnectionListener(ConnectionListener connectionListener) {
  611.         connectionListeners.remove(connectionListener);
  612.     }

  613.     @Override
  614.     public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException, InterruptedException {
  615.         StanzaFilter packetFilter = new IQReplyFilter(packet, this);
  616.         // Create the packet collector before sending the packet
  617.         PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet);
  618.         return packetCollector;
  619.     }

  620.     @Override
  621.     public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet)
  622.                     throws NotConnectedException, InterruptedException {
  623.         // Create the packet collector before sending the packet
  624.         PacketCollector packetCollector = createPacketCollector(packetFilter);
  625.         try {
  626.             // Now we can send the packet as the collector has been created
  627.             sendStanza(packet);
  628.         }
  629.         catch (InterruptedException | NotConnectedException | RuntimeException e) {
  630.             packetCollector.cancel();
  631.             throw e;
  632.         }
  633.         return packetCollector;
  634.     }

  635.     @Override
  636.     public PacketCollector createPacketCollector(StanzaFilter packetFilter) {
  637.         PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter);
  638.         return createPacketCollector(configuration);
  639.     }

  640.     @Override
  641.     public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) {
  642.         PacketCollector collector = new PacketCollector(this, configuration);
  643.         // Add the collector to the list of active collectors.
  644.         collectors.add(collector);
  645.         return collector;
  646.     }

  647.     @Override
  648.     public void removePacketCollector(PacketCollector collector) {
  649.         collectors.remove(collector);
  650.     }

  651.     @Override
  652.     @Deprecated
  653.     public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) {
  654.         addAsyncStanzaListener(packetListener, packetFilter);
  655.     }

  656.     @Override
  657.     @Deprecated
  658.     public boolean removePacketListener(StanzaListener packetListener) {
  659.         return removeAsyncStanzaListener(packetListener);
  660.     }

  661.     @Override
  662.     public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
  663.         if (packetListener == null) {
  664.             throw new NullPointerException("Packet listener is null.");
  665.         }
  666.         ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
  667.         synchronized (syncRecvListeners) {
  668.             syncRecvListeners.put(packetListener, wrapper);
  669.         }
  670.     }

  671.     @Override
  672.     public boolean removeSyncStanzaListener(StanzaListener packetListener) {
  673.         synchronized (syncRecvListeners) {
  674.             return syncRecvListeners.remove(packetListener) != null;
  675.         }
  676.     }

  677.     @Override
  678.     public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) {
  679.         if (packetListener == null) {
  680.             throw new NullPointerException("Packet listener is null.");
  681.         }
  682.         ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
  683.         synchronized (asyncRecvListeners) {
  684.             asyncRecvListeners.put(packetListener, wrapper);
  685.         }
  686.     }

  687.     @Override
  688.     public boolean removeAsyncStanzaListener(StanzaListener packetListener) {
  689.         synchronized (asyncRecvListeners) {
  690.             return asyncRecvListeners.remove(packetListener) != null;
  691.         }
  692.     }

  693.     @Override
  694.     public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) {
  695.         if (packetListener == null) {
  696.             throw new NullPointerException("Packet listener is null.");
  697.         }
  698.         ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
  699.         synchronized (sendListeners) {
  700.             sendListeners.put(packetListener, wrapper);
  701.         }
  702.     }

  703.     @Override
  704.     public void removePacketSendingListener(StanzaListener packetListener) {
  705.         synchronized (sendListeners) {
  706.             sendListeners.remove(packetListener);
  707.         }
  708.     }

  709.     /**
  710.      * Process all packet listeners for sending packets.
  711.      * <p>
  712.      * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread.
  713.      * </p>
  714.      *
  715.      * @param packet the packet to process.
  716.      */
  717.     @SuppressWarnings("javadoc")
  718.     protected void firePacketSendingListeners(final Stanza packet) {
  719.         final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
  720.         synchronized (sendListeners) {
  721.             for (ListenerWrapper listenerWrapper : sendListeners.values()) {
  722.                 if (listenerWrapper.filterMatches(packet)) {
  723.                     listenersToNotify.add(listenerWrapper.getListener());
  724.                 }
  725.             }
  726.         }
  727.         if (listenersToNotify.isEmpty()) {
  728.             return;
  729.         }
  730.         // Notify in a new thread, because we can
  731.         asyncGo(new Runnable() {
  732.             @Override
  733.             public void run() {
  734.                 for (StanzaListener listener : listenersToNotify) {
  735.                     try {
  736.                         listener.processPacket(packet);
  737.                     }
  738.                     catch (Exception e) {
  739.                         LOGGER.log(Level.WARNING, "Sending listener threw exception", e);
  740.                         continue;
  741.                     }
  742.                 }
  743.             }});
  744.     }

  745.     @Override
  746.     public void addPacketInterceptor(StanzaListener packetInterceptor,
  747.             StanzaFilter packetFilter) {
  748.         if (packetInterceptor == null) {
  749.             throw new NullPointerException("Packet interceptor is null.");
  750.         }
  751.         InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter);
  752.         synchronized (interceptors) {
  753.             interceptors.put(packetInterceptor, interceptorWrapper);
  754.         }
  755.     }

  756.     @Override
  757.     public void removePacketInterceptor(StanzaListener packetInterceptor) {
  758.         synchronized (interceptors) {
  759.             interceptors.remove(packetInterceptor);
  760.         }
  761.     }

  762.     /**
  763.      * Process interceptors. Interceptors may modify the packet that is about to be sent.
  764.      * Since the thread that requested to send the packet will invoke all interceptors, it
  765.      * is important that interceptors perform their work as soon as possible so that the
  766.      * thread does not remain blocked for a long period.
  767.      *
  768.      * @param packet the packet that is going to be sent to the server
  769.      */
  770.     private void firePacketInterceptors(Stanza packet) {
  771.         List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>();
  772.         synchronized (interceptors) {
  773.             for (InterceptorWrapper interceptorWrapper : interceptors.values()) {
  774.                 if (interceptorWrapper.filterMatches(packet)) {
  775.                     interceptorsToInvoke.add(interceptorWrapper.getInterceptor());
  776.                 }
  777.             }
  778.         }
  779.         for (StanzaListener interceptor : interceptorsToInvoke) {
  780.             try {
  781.                 interceptor.processPacket(packet);
  782.             } catch (Exception e) {
  783.                 LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e);
  784.             }
  785.         }
  786.     }

  787.     /**
  788.      * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger}
  789.      * by setup the system property <code>smack.debuggerClass</code> to the implementation.
  790.      *
  791.      * @throws IllegalStateException if the reader or writer isn't yet initialized.
  792.      * @throws IllegalArgumentException if the SmackDebugger can't be loaded.
  793.      */
  794.     protected void initDebugger() {
  795.         if (reader == null || writer == null) {
  796.             throw new NullPointerException("Reader or writer isn't initialized.");
  797.         }
  798.         // If debugging is enabled, we open a window and write out all network traffic.
  799.         if (config.isDebuggerEnabled()) {
  800.             if (debugger == null) {
  801.                 debugger = SmackConfiguration.createDebugger(this, writer, reader);
  802.             }

  803.             if (debugger == null) {
  804.                 LOGGER.severe("Debugging enabled but could not find debugger class");
  805.             } else {
  806.                 // Obtain new reader and writer from the existing debugger
  807.                 reader = debugger.newConnectionReader(reader);
  808.                 writer = debugger.newConnectionWriter(writer);
  809.             }
  810.         }
  811.     }

  812.     @Override
  813.     public long getPacketReplyTimeout() {
  814.         return packetReplyTimeout;
  815.     }

  816.     @Override
  817.     public void setPacketReplyTimeout(long timeout) {
  818.         packetReplyTimeout = timeout;
  819.     }

  820.     private static boolean replyToUnknownIqDefault = true;

  821.     /**
  822.      * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured
  823.      * default is 'true'.
  824.      *
  825.      * @param replyToUnkownIqDefault
  826.      * @see #setReplyToUnknownIq(boolean)
  827.      */
  828.     public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) {
  829.         AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault;
  830.     }

  831.     private boolean replyToUnkownIq = replyToUnknownIqDefault;

  832.     /**
  833.      * Set if Smack will automatically send
  834.      * {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a
  835.      * registered {@link IQRequestHandler} is received.
  836.      *
  837.      * @param replyToUnknownIq
  838.      */
  839.     public void setReplyToUnknownIq(boolean replyToUnknownIq) {
  840.         this.replyToUnkownIq = replyToUnknownIq;
  841.     }

  842.     protected void parseAndProcessStanza(XmlPullParser parser) throws Exception {
  843.         ParserUtils.assertAtStartTag(parser);
  844.         int parserDepth = parser.getDepth();
  845.         Stanza stanza = null;
  846.         try {
  847.             stanza = PacketParserUtils.parseStanza(parser);
  848.         }
  849.         catch (Exception e) {
  850.             // Always re-throw runtime exceptions, they are fatal
  851.             if (e instanceof RuntimeException) {
  852.                 throw (RuntimeException) e;
  853.             }
  854.             CharSequence content = PacketParserUtils.parseContentDepth(parser,
  855.                             parserDepth);
  856.             UnparsablePacket message = new UnparsablePacket(content, e);
  857.             ParsingExceptionCallback callback = getParsingExceptionCallback();
  858.             if (callback != null) {
  859.                 callback.handleUnparsablePacket(message);
  860.             }
  861.         }
  862.         ParserUtils.assertAtEndTag(parser);
  863.         if (stanza != null) {
  864.             processPacket(stanza);
  865.         }
  866.     }

  867.     /**
  868.      * Processes a packet after it's been fully parsed by looping through the installed
  869.      * packet collectors and listeners and letting them examine the packet to see if
  870.      * they are a match with the filter.
  871.      *
  872.      * @param packet the packet to process.
  873.      */
  874.     protected void processPacket(Stanza packet) {
  875.         assert(packet != null);
  876.         lastStanzaReceived = System.currentTimeMillis();
  877.         // Deliver the incoming packet to listeners.
  878.         executorService.submit(new ListenerNotification(packet));
  879.     }

  880.     /**
  881.      * A runnable to notify all listeners and packet collectors of a packet.
  882.      */
  883.     private class ListenerNotification implements Runnable {

  884.         private final Stanza packet;

  885.         public ListenerNotification(Stanza packet) {
  886.             this.packet = packet;
  887.         }

  888.         public void run() {
  889.             invokePacketCollectorsAndNotifyRecvListeners(packet);
  890.         }
  891.     }

  892.     /**
  893.      * Invoke {@link PacketCollector#processPacket(Stanza)} for every
  894.      * PacketCollector with the given packet. Also notify the receive listeners with a matching packet filter about the packet.
  895.      *
  896.      * @param packet the packet to notify the PacketCollectors and receive listeners about.
  897.      */
  898.     protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) {
  899.         if (packet instanceof IQ) {
  900.             final IQ iq = (IQ) packet;
  901.             final IQ.Type type = iq.getType();
  902.             switch (type) {
  903.             case set:
  904.             case get:
  905.                 final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
  906.                 IQRequestHandler iqRequestHandler = null;
  907.                 switch (type) {
  908.                 case set:
  909.                     synchronized (setIqRequestHandler) {
  910.                         iqRequestHandler = setIqRequestHandler.get(key);
  911.                     }
  912.                     break;
  913.                 case get:
  914.                     synchronized (getIqRequestHandler) {
  915.                         iqRequestHandler = getIqRequestHandler.get(key);
  916.                     }
  917.                     break;
  918.                 default:
  919.                     throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
  920.                 }
  921.                 if (iqRequestHandler == null) {
  922.                     if (!replyToUnkownIq) {
  923.                         return;
  924.                     }
  925.                     // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
  926.                     // IQ of type "error" with code 501 ("feature-not-implemented")
  927.                     ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError(
  928.                                     XMPPError.Condition.feature_not_implemented));
  929.                     try {
  930.                         sendStanza(errorIQ);
  931.                     }
  932.                     catch (InterruptedException | NotConnectedException e) {
  933.                         LOGGER.log(Level.WARNING, "Exception while sending error IQ to unkown IQ request", e);
  934.                     }
  935.                 } else {
  936.                     ExecutorService executorService = null;
  937.                     switch (iqRequestHandler.getMode()) {
  938.                     case sync:
  939.                         executorService = singleThreadedExecutorService;
  940.                         break;
  941.                     case async:
  942.                         executorService = cachedExecutorService;
  943.                         break;
  944.                     }
  945.                     final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
  946.                     executorService.execute(new Runnable() {
  947.                         @Override
  948.                         public void run() {
  949.                             IQ response = finalIqRequestHandler.handleIQRequest(iq);
  950.                             if (response == null) {
  951.                                 // It is not ideal if the IQ request handler does not return an IQ response, because RFC
  952.                                 // 6120 ยง 8.1.2 does specify that a response is mandatory. But some APIs, mostly the
  953.                                 // file transfer one, does not always return a result, so we need to handle this case.
  954.                                 // Also sometimes a request handler may decide that it's better to not send a response,
  955.                                 // e.g. to avoid presence leaks.
  956.                                 return;
  957.                             }
  958.                             try {
  959.                                 sendStanza(response);
  960.                             }
  961.                             catch (InterruptedException | NotConnectedException e) {
  962.                                 LOGGER.log(Level.WARNING, "Exception while sending response to IQ request", e);
  963.                             }
  964.                         }
  965.                     });
  966.                     // The following returns makes it impossible for packet listeners and collectors to
  967.                     // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the
  968.                     // desired behavior.
  969.                     return;
  970.                 }
  971.             default:
  972.                 break;
  973.             }
  974.         }

  975.         // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
  976.         // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
  977.         // their own thread.
  978.         final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
  979.         synchronized (asyncRecvListeners) {
  980.             for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
  981.                 if (listenerWrapper.filterMatches(packet)) {
  982.                     listenersToNotify.add(listenerWrapper.getListener());
  983.                 }
  984.             }
  985.         }

  986.         for (final StanzaListener listener : listenersToNotify) {
  987.             asyncGo(new Runnable() {
  988.                 @Override
  989.                 public void run() {
  990.                     try {
  991.                         listener.processPacket(packet);
  992.                     } catch (Exception e) {
  993.                         LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
  994.                     }
  995.                 }
  996.             });
  997.         }

  998.         // Loop through all collectors and notify the appropriate ones.
  999.         for (PacketCollector collector: collectors) {
  1000.             collector.processPacket(packet);
  1001.         }

  1002.         // Notify the receive listeners interested in the packet
  1003.         listenersToNotify.clear();
  1004.         synchronized (syncRecvListeners) {
  1005.             for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
  1006.                 if (listenerWrapper.filterMatches(packet)) {
  1007.                     listenersToNotify.add(listenerWrapper.getListener());
  1008.                 }
  1009.             }
  1010.         }

  1011.         // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
  1012.         // threaded executor service and therefore keeps the order.
  1013.         singleThreadedExecutorService.execute(new Runnable() {
  1014.             @Override
  1015.             public void run() {
  1016.                 for (StanzaListener listener : listenersToNotify) {
  1017.                     try {
  1018.                         listener.processPacket(packet);
  1019.                     } catch(NotConnectedException e) {
  1020.                         LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
  1021.                         break;
  1022.                     } catch (Exception e) {
  1023.                         LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
  1024.                     }
  1025.                 }
  1026.             }
  1027.         });

  1028.     }

  1029.     /**
  1030.      * Sets whether the connection has already logged in the server. This method assures that the
  1031.      * {@link #wasAuthenticated} flag is never reset once it has ever been set.
  1032.      *
  1033.      */
  1034.     protected void setWasAuthenticated() {
  1035.         // Never reset the flag if the connection has ever been authenticated
  1036.         if (!wasAuthenticated) {
  1037.             wasAuthenticated = authenticated;
  1038.         }
  1039.     }

  1040.     protected void callConnectionConnectedListener() {
  1041.         for (ConnectionListener listener : connectionListeners) {
  1042.             listener.connected(this);
  1043.         }
  1044.     }

  1045.     protected void callConnectionAuthenticatedListener(boolean resumed) {
  1046.         for (ConnectionListener listener : connectionListeners) {
  1047.             try {
  1048.                 listener.authenticated(this, resumed);
  1049.             } catch (Exception e) {
  1050.                 // Catch and print any exception so we can recover
  1051.                 // from a faulty listener and finish the shutdown process
  1052.                 LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e);
  1053.             }
  1054.         }
  1055.     }

  1056.     void callConnectionClosedListener() {
  1057.         for (ConnectionListener listener : connectionListeners) {
  1058.             try {
  1059.                 listener.connectionClosed();
  1060.             }
  1061.             catch (Exception e) {
  1062.                 // Catch and print any exception so we can recover
  1063.                 // from a faulty listener and finish the shutdown process
  1064.                 LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e);
  1065.             }
  1066.         }
  1067.     }

  1068.     protected void callConnectionClosedOnErrorListener(Exception e) {
  1069.         LOGGER.log(Level.WARNING, "Connection closed with error", e);
  1070.         for (ConnectionListener listener : connectionListeners) {
  1071.             try {
  1072.                 listener.connectionClosedOnError(e);
  1073.             }
  1074.             catch (Exception e2) {
  1075.                 // Catch and print any exception so we can recover
  1076.                 // from a faulty listener
  1077.                 LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2);
  1078.             }
  1079.         }
  1080.     }

  1081.     /**
  1082.      * Sends a notification indicating that the connection was reconnected successfully.
  1083.      */
  1084.     protected void notifyReconnection() {
  1085.         // Notify connection listeners of the reconnection.
  1086.         for (ConnectionListener listener : connectionListeners) {
  1087.             try {
  1088.                 listener.reconnectionSuccessful();
  1089.             }
  1090.             catch (Exception e) {
  1091.                 // Catch and print any exception so we can recover
  1092.                 // from a faulty listener
  1093.                 LOGGER.log(Level.WARNING, "notifyReconnection()", e);
  1094.             }
  1095.         }
  1096.     }

  1097.     /**
  1098.      * A wrapper class to associate a packet filter with a listener.
  1099.      */
  1100.     protected static class ListenerWrapper {

  1101.         private final StanzaListener packetListener;
  1102.         private final StanzaFilter packetFilter;

  1103.         /**
  1104.          * Create a class which associates a packet filter with a listener.
  1105.          *
  1106.          * @param packetListener the packet listener.
  1107.          * @param packetFilter the associated filter or null if it listen for all packets.
  1108.          */
  1109.         public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) {
  1110.             this.packetListener = packetListener;
  1111.             this.packetFilter = packetFilter;
  1112.         }

  1113.         public boolean filterMatches(Stanza packet) {
  1114.             return packetFilter == null || packetFilter.accept(packet);
  1115.         }

  1116.         public StanzaListener getListener() {
  1117.             return packetListener;
  1118.         }
  1119.     }

  1120.     /**
  1121.      * A wrapper class to associate a packet filter with an interceptor.
  1122.      */
  1123.     protected static class InterceptorWrapper {

  1124.         private final StanzaListener packetInterceptor;
  1125.         private final StanzaFilter packetFilter;

  1126.         /**
  1127.          * Create a class which associates a packet filter with an interceptor.
  1128.          *
  1129.          * @param packetInterceptor the interceptor.
  1130.          * @param packetFilter the associated filter or null if it intercepts all packets.
  1131.          */
  1132.         public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) {
  1133.             this.packetInterceptor = packetInterceptor;
  1134.             this.packetFilter = packetFilter;
  1135.         }

  1136.         public boolean filterMatches(Stanza packet) {
  1137.             return packetFilter == null || packetFilter.accept(packet);
  1138.         }

  1139.         public StanzaListener getInterceptor() {
  1140.             return packetInterceptor;
  1141.         }
  1142.     }

  1143.     @Override
  1144.     public int getConnectionCounter() {
  1145.         return connectionCounterValue;
  1146.     }

  1147.     @Override
  1148.     public void setFromMode(FromMode fromMode) {
  1149.         this.fromMode = fromMode;
  1150.     }

  1151.     @Override
  1152.     public FromMode getFromMode() {
  1153.         return this.fromMode;
  1154.     }

  1155.     @Override
  1156.     protected void finalize() throws Throwable {
  1157.         LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter()
  1158.                         + "): Shutting down executor services");
  1159.         try {
  1160.             // It's usually not a good idea to rely on finalize. But this is the easiest way to
  1161.             // avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a
  1162.             // reference to their ExecutorService which prevents the ExecutorService from being
  1163.             // gc'ed. It is possible that the XMPPConnection instance is gc'ed while the
  1164.             // listenerExecutor ExecutorService call not be gc'ed until it got shut down.
  1165.             executorService.shutdownNow();
  1166.             cachedExecutorService.shutdown();
  1167.             removeCallbacksService.shutdownNow();
  1168.             singleThreadedExecutorService.shutdownNow();
  1169.         } catch (Throwable t) {
  1170.             LOGGER.log(Level.WARNING, "finalize() threw trhowable", t);
  1171.         }
  1172.         finally {
  1173.             super.finalize();
  1174.         }
  1175.     }

  1176.     protected final void parseFeatures(XmlPullParser parser) throws Exception {
  1177.         streamFeatures.clear();
  1178.         final int initialDepth = parser.getDepth();
  1179.         while (true) {
  1180.             int eventType = parser.next();

  1181.             if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) {
  1182.                 ExtensionElement streamFeature = null;
  1183.                 String name = parser.getName();
  1184.                 String namespace = parser.getNamespace();
  1185.                 switch (name) {
  1186.                 case StartTls.ELEMENT:
  1187.                     streamFeature = PacketParserUtils.parseStartTlsFeature(parser);
  1188.                     break;
  1189.                 case Mechanisms.ELEMENT:
  1190.                     streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser));
  1191.                     break;
  1192.                 case Bind.ELEMENT:
  1193.                     streamFeature = Bind.Feature.INSTANCE;
  1194.                     break;
  1195.                 case Session.ELEMENT:
  1196.                     streamFeature = PacketParserUtils.parseSessionFeature(parser);
  1197.                     break;
  1198.                 case Compress.Feature.ELEMENT:
  1199.                     streamFeature = PacketParserUtils.parseCompressionFeature(parser);
  1200.                     break;
  1201.                 default:
  1202.                     ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace);
  1203.                     if (provider != null) {
  1204.                         streamFeature = provider.parse(parser);
  1205.                     }
  1206.                     break;
  1207.                 }
  1208.                 if (streamFeature != null) {
  1209.                     addStreamFeature(streamFeature);
  1210.                 }
  1211.             }
  1212.             else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) {
  1213.                 break;
  1214.             }
  1215.         }

  1216.         if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
  1217.             // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
  1218.             if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
  1219.                             || config.getSecurityMode() == SecurityMode.disabled) {
  1220.                 saslFeatureReceived.reportSuccess();
  1221.             }
  1222.         }

  1223.         // If the server reported the bind feature then we are that that we did SASL and maybe
  1224.         // STARTTLS. We can then report that the last 'stream:features' have been parsed
  1225.         if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
  1226.             if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
  1227.                             || !config.isCompressionEnabled()) {
  1228.                 // This was was last features from the server is either it did not contain
  1229.                 // compression or if we disabled it
  1230.                 lastFeaturesReceived.reportSuccess();
  1231.             }
  1232.         }
  1233.         afterFeaturesReceived();
  1234.     }

  1235.     protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
  1236.         // Default implementation does nothing
  1237.     }

  1238.     @SuppressWarnings("unchecked")
  1239.     @Override
  1240.     public <F extends ExtensionElement> F getFeature(String element, String namespace) {
  1241.         return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace));
  1242.     }

  1243.     @Override
  1244.     public boolean hasFeature(String element, String namespace) {
  1245.         return getFeature(element, namespace) != null;
  1246.     }

  1247.     private void addStreamFeature(ExtensionElement feature) {
  1248.         String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace());
  1249.         streamFeatures.put(key, feature);
  1250.     }

  1251.     @Override
  1252.     public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
  1253.                     StanzaListener callback) throws NotConnectedException, InterruptedException {
  1254.         sendStanzaWithResponseCallback(stanza, replyFilter, callback, null);
  1255.     }

  1256.     @Override
  1257.     public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter,
  1258.                     StanzaListener callback, ExceptionCallback exceptionCallback)
  1259.                     throws NotConnectedException, InterruptedException {
  1260.         sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback,
  1261.                         getPacketReplyTimeout());
  1262.     }

  1263.     @Override
  1264.     public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
  1265.                     final StanzaListener callback, final ExceptionCallback exceptionCallback,
  1266.                     long timeout) throws NotConnectedException, InterruptedException {
  1267.         Objects.requireNonNull(stanza, "stanza must not be null");
  1268.         // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
  1269.         // disallow it here in the async API as it makes no sense
  1270.         Objects.requireNonNull(replyFilter, "replyFilter must not be null");
  1271.         Objects.requireNonNull(callback, "callback must not be null");

  1272.         final StanzaListener packetListener = new StanzaListener() {
  1273.             @Override
  1274.             public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
  1275.                 try {
  1276.                     XMPPErrorException.ifHasErrorThenThrow(packet);
  1277.                     callback.processPacket(packet);
  1278.                 }
  1279.                 catch (XMPPErrorException e) {
  1280.                     if (exceptionCallback != null) {
  1281.                         exceptionCallback.processException(e);
  1282.                     }
  1283.                 }
  1284.                 finally {
  1285.                     removeAsyncStanzaListener(this);
  1286.                 }
  1287.             }
  1288.         };
  1289.         removeCallbacksService.schedule(new Runnable() {
  1290.             @Override
  1291.             public void run() {
  1292.                 boolean removed = removeAsyncStanzaListener(packetListener);
  1293.                 // If the packetListener got removed, then it was never run and
  1294.                 // we never received a response, inform the exception callback
  1295.                 if (removed && exceptionCallback != null) {
  1296.                     exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
  1297.                 }
  1298.             }
  1299.         }, timeout, TimeUnit.MILLISECONDS);
  1300.         addAsyncStanzaListener(packetListener, replyFilter);
  1301.         sendStanza(stanza);
  1302.     }

  1303.     @Override
  1304.     public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback)
  1305.                     throws NotConnectedException, InterruptedException {
  1306.         sendIqWithResponseCallback(iqRequest, callback, null);
  1307.     }

  1308.     @Override
  1309.     public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback,
  1310.                     ExceptionCallback exceptionCallback) throws NotConnectedException, InterruptedException {
  1311.         sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout());
  1312.     }

  1313.     @Override
  1314.     public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback,
  1315.                     final ExceptionCallback exceptionCallback, long timeout)
  1316.                     throws NotConnectedException, InterruptedException {
  1317.         StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this);
  1318.         sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout);
  1319.     }

  1320.     @Override
  1321.     public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
  1322.         final StanzaListener packetListener = new StanzaListener() {
  1323.             @Override
  1324.             public void processPacket(Stanza packet) throws NotConnectedException, InterruptedException {
  1325.                 try {
  1326.                     callback.processPacket(packet);
  1327.                 } finally {
  1328.                     removeSyncStanzaListener(this);
  1329.                 }
  1330.             }
  1331.         };
  1332.         addSyncStanzaListener(packetListener, packetFilter);
  1333.         removeCallbacksService.schedule(new Runnable() {
  1334.             @Override
  1335.             public void run() {
  1336.                 removeSyncStanzaListener(packetListener);
  1337.             }
  1338.         }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
  1339.     }

  1340.     @Override
  1341.     public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) {
  1342.         final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace());
  1343.         switch (iqRequestHandler.getType()) {
  1344.         case set:
  1345.             synchronized (setIqRequestHandler) {
  1346.                 return setIqRequestHandler.put(key, iqRequestHandler);
  1347.             }
  1348.         case get:
  1349.             synchronized (getIqRequestHandler) {
  1350.                 return getIqRequestHandler.put(key, iqRequestHandler);
  1351.             }
  1352.         default:
  1353.             throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
  1354.         }
  1355.     }

  1356.     @Override
  1357.     public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) {
  1358.         return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(),
  1359.                         iqRequestHandler.getType());
  1360.     }

  1361.     @Override
  1362.     public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) {
  1363.         final String key = XmppStringUtils.generateKey(element, namespace);
  1364.         switch (type) {
  1365.         case set:
  1366.             synchronized (setIqRequestHandler) {
  1367.                 return setIqRequestHandler.remove(key);
  1368.             }
  1369.         case get:
  1370.             synchronized (getIqRequestHandler) {
  1371.                 return getIqRequestHandler.remove(key);
  1372.             }
  1373.         default:
  1374.             throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed");
  1375.         }
  1376.     }

  1377.     private long lastStanzaReceived;

  1378.     public long getLastStanzaReceived() {
  1379.         return lastStanzaReceived;
  1380.     }

  1381.     /**
  1382.      * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a
  1383.      * stanza
  1384.      *
  1385.      * @param callback the callback to install
  1386.      */
  1387.     public void setParsingExceptionCallback(ParsingExceptionCallback callback) {
  1388.         parsingExceptionCallback = callback;
  1389.     }

  1390.     /**
  1391.      * Get the current active parsing exception callback.
  1392.      *  
  1393.      * @return the active exception callback or null if there is none
  1394.      */
  1395.     public ParsingExceptionCallback getParsingExceptionCallback() {
  1396.         return parsingExceptionCallback;
  1397.     }

  1398.     protected final void asyncGo(Runnable runnable) {
  1399.         cachedExecutorService.execute(runnable);
  1400.     }

  1401.     protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
  1402.         return removeCallbacksService.schedule(runnable, delay, unit);
  1403.     }
  1404. }