* Use {@link #isPingSupported(String)} to determine if XMPP Ping is supported
* by the entity.
*
* @param jid The id of the entity the ping is being sent to
* @param pingTimeout The time to wait for a reply
* @return true if a reply was received from the entity, false otherwise.
* @throws NoResponseException if there was no response from the jid.
* @throws NotConnectedException
*/
public boolean ping(String jid, long pingTimeout) throws NotConnectedException, NoResponseException {
Ping ping = new Ping(jid);
try {
connection().createPacketCollectorAndSend(ping).nextResultOrThrow();
}
catch (XMPPException exc) {
return jid.equals(connection().getServiceName());
}
return true;
}
/**
* Same as calling {@link #ping(String, long)} with the defaultpacket reply
* timeout.
*
* @param jid The id of the entity the ping is being sent to
* @return true if a reply was received from the entity, false otherwise.
* @throws NotConnectedException
* @throws NoResponseException if there was no response from the jid.
*/
public boolean ping(String jid) throws NotConnectedException, NoResponseException {
return ping(jid, connection().getPacketReplyTimeout());
}
/**
* Query the specified entity to see if it supports the Ping protocol (XEP-0199)
*
* @param jid The id of the entity the query is being sent to
* @return true if it supports ping, false otherwise.
* @throws XMPPErrorException An XMPP related error occurred during the request
* @throws NoResponseException if there was no response from the jid.
* @throws NotConnectedException
*/
public boolean isPingSupported(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException {
return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, PingManager.NAMESPACE);
}
/**
* Pings the server. This method will return true if the server is reachable. It
* is the equivalent of calling ping
with the XMPP domain.
*
* Unlike the {@link #ping(String)} case, this method will return true even if
* {@link #isPingSupported(String)} is false.
*
* @return true if a reply was received from the server, false otherwise.
* @throws NotConnectedException
*/
public boolean pingMyServer() throws NotConnectedException {
return pingMyServer(true);
}
/**
* Pings the server. This method will return true if the server is reachable. It
* is the equivalent of calling ping
with the XMPP domain.
*
* Unlike the {@link #ping(String)} case, this method will return true even if * {@link #isPingSupported(String)} is false. * * @param notifyListeners Notify the PingFailedListener in case of error if true * @return true if the user's server could be pinged. * @throws NotConnectedException */ public boolean pingMyServer(boolean notifyListeners) throws NotConnectedException { boolean res; try { res = ping(connection().getServiceName()); } catch (NoResponseException e) { res = false; } if (!res && notifyListeners) { for (PingFailedListener l : pingFailedListeners) l.pingFailed(); } return res; } /** * Set the interval between the server is automatic pinged. A negative value disables automatic server pings. * * @param pingInterval the interval between the ping */ public void setPingInterval(int pingInterval) { this.pingInterval = pingInterval; maybeSchedulePingServerTask(); } /** * Get the current ping interval. * * @return the interval between pings in seconds */ public int getPingInterval() { return pingInterval; } /** * Register a new PingFailedListener * * @param listener the listener to invoke */ public void registerPingFailedListener(PingFailedListener listener) { pingFailedListeners.add(listener); } /** * Unregister a PingFailedListener * * @param listener the listener to remove */ public void unregisterPingFailedListener(PingFailedListener listener) { pingFailedListeners.remove(listener); } /** * Returns the timestamp when the last XMPP Pong was received. * * @return the timestamp of the last XMPP Pong */ public long getLastReceivedPong() { return lastPongReceived; } private void maybeSchedulePingServerTask() { maybeSchedulePingServerTask(0); } /** * Cancels any existing periodic ping task if there is one and schedules a new ping task if * pingInterval is greater then zero. * * @param delta the delta to the last received ping in seconds */ private synchronized void maybeSchedulePingServerTask(int delta) { maybeStopPingServerTask(); if (pingInterval > 0) { int nextPingIn = pingInterval - delta; LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" + pingInterval + ", delta=" + delta + ")"); nextAutomaticPing = schedule(pingServerRunnable, pingInterval, TimeUnit.SECONDS); } } private void maybeStopPingServerTask() { if (nextAutomaticPing != null) { nextAutomaticPing.cancel(true); nextAutomaticPing = null; } } private final Runnable pingServerRunnable = new Runnable() { private static final int DELTA = 1000; // 1 seconds private static final int TRIES = 3; // 3 tries public void run() { LOGGER.fine("ServerPingTask run()"); XMPPConnection connection = connection(); if (connection == null) { // connection has been collected by GC // which means we can stop the thread by breaking the loop return; } if (pingInterval <= 0) { // Ping has been disabled return; } long lastReceivedPong = getLastReceivedPong(); if (lastReceivedPong > 0) { long now = System.currentTimeMillis(); // Calculate the delta from now to the next ping time. If delta is positive, the // last successful ping was not to long ago, so we can defer the current ping. int delta = (int) (((pingInterval * 1000) - (now - lastReceivedPong)) / 1000); if (delta > 0) { maybeSchedulePingServerTask(delta); return; } } if (connection.isAuthenticated()) { boolean res = false; for (int i = 0; i < TRIES; i++) { if (i != 0) { try { Thread.sleep(DELTA); } catch (InterruptedException e) { // We received an interrupt // This only happens if we should stop pinging return; } } try { res = pingMyServer(false); } catch (SmackException e) { LOGGER.log(Level.WARNING, "SmackError while pinging server", e); res = false; } // stop when we receive a pong back if (res) { break; } } LOGGER.fine("ServerPingTask res=" + res); if (!res) { for (PingFailedListener l : pingFailedListeners) { l.pingFailed(); } } else { // Ping was successful, wind-up the periodic task again maybeSchedulePingServerTask(); } } else { LOGGER.warning("ServerPingTask: XMPPConnection was not authenticated"); } } }; }