PingManager.java

  1. /**
  2.  *
  3.  * Copyright 2012-2015 Florian Schmaus
  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.smackx.ping;

  18. import java.util.Collections;
  19. import java.util.HashSet;
  20. import java.util.Map;
  21. import java.util.Set;
  22. import java.util.WeakHashMap;
  23. import java.util.concurrent.Executors;
  24. import java.util.concurrent.ScheduledExecutorService;
  25. import java.util.concurrent.ScheduledFuture;
  26. import java.util.concurrent.TimeUnit;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;

  29. import org.jivesoftware.smack.AbstractConnectionClosedListener;
  30. import org.jivesoftware.smack.SmackException;
  31. import org.jivesoftware.smack.SmackException.NoResponseException;
  32. import org.jivesoftware.smack.SmackException.NotConnectedException;
  33. import org.jivesoftware.smack.XMPPConnection;
  34. import org.jivesoftware.smack.ConnectionCreationListener;
  35. import org.jivesoftware.smack.Manager;
  36. import org.jivesoftware.smack.XMPPConnectionRegistry;
  37. import org.jivesoftware.smack.XMPPException;
  38. import org.jivesoftware.smack.XMPPException.XMPPErrorException;
  39. import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
  40. import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
  41. import org.jivesoftware.smack.packet.IQ;
  42. import org.jivesoftware.smack.packet.IQ.Type;
  43. import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
  44. import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
  45. import org.jivesoftware.smackx.ping.packet.Ping;
  46. import org.jxmpp.jid.Jid;

  47. /**
  48.  * Implements the XMPP Ping as defined by XEP-0199. The XMPP Ping protocol allows one entity to
  49.  * ping any other entity by simply sending a ping to the appropriate JID. PingManger also
  50.  * periodically sends XMPP pings to the server to avoid NAT timeouts and to test
  51.  * the connection status.
  52.  * <p>
  53.  * The default server ping interval is 30 minutes and can be modified with
  54.  * {@link #setDefaultPingInterval(int)} and {@link #setPingInterval(int)}.
  55.  * </p>
  56.  *
  57.  * @author Florian Schmaus
  58.  * @see <a href="http://www.xmpp.org/extensions/xep-0199.html">XEP-0199:XMPP Ping</a>
  59.  */
  60. public class PingManager extends Manager {
  61.     private static final Logger LOGGER = Logger.getLogger(PingManager.class.getName());

  62.     private static final Map<XMPPConnection, PingManager> INSTANCES = new WeakHashMap<XMPPConnection, PingManager>();

  63.     static {
  64.         XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
  65.             public void connectionCreated(XMPPConnection connection) {
  66.                 getInstanceFor(connection);
  67.             }
  68.         });
  69.     }

  70.     /**
  71.      * Retrieves a {@link PingManager} for the specified {@link XMPPConnection}, creating one if it doesn't already
  72.      * exist.
  73.      *
  74.      * @param connection
  75.      * The connection the manager is attached to.
  76.      * @return The new or existing manager.
  77.      */
  78.     public synchronized static PingManager getInstanceFor(XMPPConnection connection) {
  79.         PingManager pingManager = INSTANCES.get(connection);
  80.         if (pingManager == null) {
  81.             pingManager = new PingManager(connection);
  82.             INSTANCES.put(connection, pingManager);
  83.         }
  84.         return pingManager;
  85.     }

  86.     /**
  87.      * The default ping interval in seconds used by new PingManager instances. The default is 30 minutes.
  88.      */
  89.     private static int defaultPingInterval = 60 * 30;

  90.     /**
  91.      * Set the default ping interval which will be used for new connections.
  92.      *
  93.      * @param interval the interval in seconds
  94.      */
  95.     public static void setDefaultPingInterval(int interval) {
  96.         defaultPingInterval = interval;
  97.     }

  98.     private final Set<PingFailedListener> pingFailedListeners = Collections
  99.                     .synchronizedSet(new HashSet<PingFailedListener>());

  100.     private final ScheduledExecutorService executorService;

  101.     /**
  102.      * The interval in seconds between pings are send to the users server.
  103.      */
  104.     private int pingInterval = defaultPingInterval;

  105.     private ScheduledFuture<?> nextAutomaticPing;

  106.     private PingManager(XMPPConnection connection) {
  107.         super(connection);
  108.         executorService = Executors.newSingleThreadScheduledExecutor(
  109.                         new SmackExecutorThreadFactory(connection.getConnectionCounter(), "Ping"));
  110.         ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
  111.         sdm.addFeature(Ping.NAMESPACE);

  112.         connection.registerIQRequestHandler(new AbstractIqRequestHandler(Ping.ELEMENT, Ping.NAMESPACE, Type.get, Mode.async) {
  113.             @Override
  114.             public IQ handleIQRequest(IQ iqRequest) {
  115.                 Ping ping = (Ping) iqRequest;
  116.                 return ping.getPong();
  117.             }
  118.         });
  119.         connection.addConnectionListener(new AbstractConnectionClosedListener() {
  120.             @Override
  121.             public void authenticated(XMPPConnection connection, boolean resumed) {
  122.                 maybeSchedulePingServerTask();
  123.             }
  124.             @Override
  125.             public void connectionTerminated() {
  126.                 maybeStopPingServerTask();
  127.             }
  128.         });
  129.         maybeSchedulePingServerTask();
  130.     }

  131.     /**
  132.      * Pings the given jid. This method will return false if an error occurs.  The exception
  133.      * to this, is a server ping, which will always return true if the server is reachable,
  134.      * event if there is an error on the ping itself (i.e. ping not supported).
  135.      * <p>
  136.      * Use {@link #isPingSupported(Jid)} to determine if XMPP Ping is supported
  137.      * by the entity.
  138.      *
  139.      * @param jid The id of the entity the ping is being sent to
  140.      * @param pingTimeout The time to wait for a reply in milliseconds
  141.      * @return true if a reply was received from the entity, false otherwise.
  142.      * @throws NoResponseException if there was no response from the jid.
  143.      * @throws NotConnectedException
  144.      * @throws InterruptedException
  145.      */
  146.     public boolean ping(Jid jid, long pingTimeout) throws NotConnectedException, NoResponseException, InterruptedException {
  147.         final XMPPConnection connection = connection();
  148.         // Packet collector for IQs needs an connection that was at least authenticated once,
  149.         // otherwise the client JID will be null causing an NPE
  150.         if (!connection.isAuthenticated()) {
  151.             throw new NotConnectedException();
  152.         }
  153.         Ping ping = new Ping(jid);
  154.         try {
  155.             connection.createPacketCollectorAndSend(ping).nextResultOrThrow(pingTimeout);
  156.         }
  157.         catch (XMPPException exc) {
  158.             return jid.equals(connection.getServiceName());
  159.         }
  160.         return true;
  161.     }

  162.     /**
  163.      * Same as calling {@link #ping(Jid, long)} with the defaultpacket reply
  164.      * timeout.
  165.      *
  166.      * @param jid The id of the entity the ping is being sent to
  167.      * @return true if a reply was received from the entity, false otherwise.
  168.      * @throws NotConnectedException
  169.      * @throws NoResponseException if there was no response from the jid.
  170.      * @throws InterruptedException
  171.      */
  172.     public boolean ping(Jid jid) throws NotConnectedException, NoResponseException, InterruptedException {
  173.         return ping(jid, connection().getPacketReplyTimeout());
  174.     }

  175.     /**
  176.      * Query the specified entity to see if it supports the Ping protocol (XEP-0199)
  177.      *
  178.      * @param jid The id of the entity the query is being sent to
  179.      * @return true if it supports ping, false otherwise.
  180.      * @throws XMPPErrorException An XMPP related error occurred during the request
  181.      * @throws NoResponseException if there was no response from the jid.
  182.      * @throws NotConnectedException
  183.      * @throws InterruptedException
  184.      */
  185.     public boolean isPingSupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
  186.         return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, Ping.NAMESPACE);
  187.     }

  188.     /**
  189.      * Pings the server. This method will return true if the server is reachable.  It
  190.      * is the equivalent of calling <code>ping</code> with the XMPP domain.
  191.      * <p>
  192.      * Unlike the {@link #ping(Jid)} case, this method will return true even if
  193.      * {@link #isPingSupported(Jid)} is false.
  194.      *
  195.      * @return true if a reply was received from the server, false otherwise.
  196.      * @throws NotConnectedException
  197.      * @throws InterruptedException
  198.      */
  199.     public boolean pingMyServer() throws NotConnectedException, InterruptedException {
  200.         return pingMyServer(true);
  201.     }

  202.     /**
  203.      * Pings the server. This method will return true if the server is reachable.  It
  204.      * is the equivalent of calling <code>ping</code> with the XMPP domain.
  205.      * <p>
  206.      * Unlike the {@link #ping(Jid)} case, this method will return true even if
  207.      * {@link #isPingSupported(Jid)} is false.
  208.      *
  209.      * @param notifyListeners Notify the PingFailedListener in case of error if true
  210.      * @return true if the user's server could be pinged.
  211.      * @throws NotConnectedException
  212.      * @throws InterruptedException
  213.      */
  214.     public boolean pingMyServer(boolean notifyListeners) throws NotConnectedException, InterruptedException {
  215.         return pingMyServer(notifyListeners, connection().getPacketReplyTimeout());
  216.     }

  217.     /**
  218.      * Pings the server. This method will return true if the server is reachable.  It
  219.      * is the equivalent of calling <code>ping</code> with the XMPP domain.
  220.      * <p>
  221.      * Unlike the {@link #ping(Jid)} case, this method will return true even if
  222.      * {@link #isPingSupported(Jid)} is false.
  223.      *
  224.      * @param notifyListeners Notify the PingFailedListener in case of error if true
  225.      * @param pingTimeout The time to wait for a reply in milliseconds
  226.      * @return true if the user's server could be pinged.
  227.      * @throws NotConnectedException
  228.      * @throws InterruptedException
  229.      */
  230.     public boolean pingMyServer(boolean notifyListeners, long pingTimeout) throws NotConnectedException, InterruptedException {
  231.         boolean res;
  232.         try {
  233.             res = ping(connection().getServiceName(), pingTimeout);
  234.         }
  235.         catch (NoResponseException e) {
  236.             res = false;
  237.         }
  238.         if (!res && notifyListeners) {
  239.             for (PingFailedListener l : pingFailedListeners)
  240.                 l.pingFailed();
  241.         }
  242.         return res;
  243.     }

  244.     /**
  245.      * Set the interval in seconds between a automated server ping is send. A negative value disables automatic server
  246.      * pings. All settings take effect immediately. If there is an active scheduled server ping it will be canceled and,
  247.      * if <code>pingInterval</code> is positive, a new one will be scheduled in pingInterval seconds.
  248.      * <p>
  249.      * If the ping fails after 3 attempts waiting the connections reply timeout for an answer, then the ping failed
  250.      * listeners will be invoked.
  251.      * </p>
  252.      *
  253.      * @param pingInterval the interval in seconds between the automated server pings
  254.      */
  255.     public void setPingInterval(int pingInterval) {
  256.         this.pingInterval = pingInterval;
  257.         maybeSchedulePingServerTask();
  258.     }

  259.     /**
  260.      * Get the current ping interval.
  261.      *
  262.      * @return the interval between pings in seconds
  263.      */
  264.     public int getPingInterval() {
  265.         return pingInterval;
  266.     }

  267.     /**
  268.      * Register a new PingFailedListener
  269.      *
  270.      * @param listener the listener to invoke
  271.      */
  272.     public void registerPingFailedListener(PingFailedListener listener) {
  273.         pingFailedListeners.add(listener);
  274.     }

  275.     /**
  276.      * Unregister a PingFailedListener
  277.      *
  278.      * @param listener the listener to remove
  279.      */
  280.     public void unregisterPingFailedListener(PingFailedListener listener) {
  281.         pingFailedListeners.remove(listener);
  282.     }

  283.     private void maybeSchedulePingServerTask() {
  284.         maybeSchedulePingServerTask(0);
  285.     }

  286.     /**
  287.      * Cancels any existing periodic ping task if there is one and schedules a new ping task if
  288.      * pingInterval is greater then zero.
  289.      *
  290.      * @param delta the delta to the last received stanza in seconds
  291.      */
  292.     private synchronized void maybeSchedulePingServerTask(int delta) {
  293.         maybeStopPingServerTask();
  294.         if (pingInterval > 0) {
  295.             int nextPingIn = pingInterval - delta;
  296.             LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval="
  297.                             + pingInterval + ", delta=" + delta + ")");
  298.             nextAutomaticPing = executorService.schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS);
  299.         }
  300.     }

  301.     private void maybeStopPingServerTask() {
  302.         if (nextAutomaticPing != null) {
  303.             nextAutomaticPing.cancel(true);
  304.             nextAutomaticPing = null;
  305.         }
  306.     }

  307.     /**
  308.      * Ping the server if deemed necessary because automatic server pings are
  309.      * enabled ({@link #setPingInterval(int)}) and the ping interval has expired.
  310.      */
  311.     public synchronized void pingServerIfNecessary() {
  312.         final int DELTA = 1000; // 1 seconds
  313.         final int TRIES = 3; // 3 tries
  314.         final XMPPConnection connection = connection();
  315.         if (connection == null) {
  316.             // connection has been collected by GC
  317.             // which means we can stop the thread by breaking the loop
  318.             return;
  319.         }
  320.         if (pingInterval <= 0) {
  321.             // Ping has been disabled
  322.             return;
  323.         }
  324.         long lastStanzaReceived = connection.getLastStanzaReceived();
  325.         if (lastStanzaReceived > 0) {
  326.             long now = System.currentTimeMillis();
  327.             // Delta since the last stanza was received
  328.             int deltaInSeconds = (int)  ((now - lastStanzaReceived) / 1000);
  329.             // If the delta is small then the ping interval, then we can defer the ping
  330.             if (deltaInSeconds < pingInterval) {
  331.                 maybeSchedulePingServerTask(deltaInSeconds);
  332.                 return;
  333.             }
  334.         }
  335.         if (connection.isAuthenticated()) {
  336.             boolean res = false;

  337.             for (int i = 0; i < TRIES; i++) {
  338.                 if (i != 0) {
  339.                     try {
  340.                         Thread.sleep(DELTA);
  341.                     } catch (InterruptedException e) {
  342.                         // We received an interrupt
  343.                         // This only happens if we should stop pinging
  344.                         return;
  345.                     }
  346.                 }
  347.                 try {
  348.                     res = pingMyServer(false);
  349.                 }
  350.                 catch (InterruptedException | SmackException e) {
  351.                     LOGGER.log(Level.WARNING, "Exception while pinging server", e);
  352.                     res = false;
  353.                 }
  354.                 // stop when we receive a pong back
  355.                 if (res) {
  356.                     break;
  357.                 }
  358.             }
  359.             if (!res) {
  360.                 for (PingFailedListener l : pingFailedListeners) {
  361.                     l.pingFailed();
  362.                 }
  363.             } else {
  364.                 // Ping was successful, wind-up the periodic task again
  365.                 maybeSchedulePingServerTask();
  366.             }
  367.         } else {
  368.             LOGGER.warning("XMPPConnection was not authenticated");
  369.         }
  370.     }

  371.     private final Runnable pingServerRunnable = new Runnable() {
  372.         public void run() {
  373.             LOGGER.fine("ServerPingTask run()");
  374.             pingServerIfNecessary();
  375.         }
  376.     };

  377.     @Override
  378.     protected void finalize() throws Throwable {
  379.         LOGGER.fine("finalizing PingManager: Shutting down executor service");
  380.         try {
  381.             executorService.shutdown();
  382.         } catch (Throwable t) {
  383.             LOGGER.log(Level.WARNING, "finalize() threw throwable", t);
  384.         }
  385.         finally {
  386.             super.finalize();
  387.         }
  388.     }
  389. }