1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-22 12:02:05 +01:00

Add PingManager.pingAsync(Jid, long)

and SmackFuture API.
This commit is contained in:
Florian Schmaus 2017-04-04 08:22:11 +02:00
parent cb971f2e10
commit 5f900d3713
5 changed files with 351 additions and 2 deletions

View file

@ -0,0 +1,170 @@
/**
*
* Copyright 2017 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.packet.Stanza;
public abstract class SmackFuture<V> implements Future<V> {
private boolean cancelled;
private V result;
protected Exception exception;
private SuccessCallback<V> successCallback;
private ExceptionCallback exceptionCallback;
@Override
public synchronized final boolean cancel(boolean mayInterruptIfRunning) {
if (isDone()) {
return false;
}
cancelled = true;
return true;
}
@Override
public synchronized final boolean isCancelled() {
return cancelled;
}
@Override
public synchronized final boolean isDone() {
return result != null;
}
public void onSuccessOrError(SuccessCallback<V> successCallback, ExceptionCallback exceptionCallback) {
this.successCallback = successCallback;
this.exceptionCallback = exceptionCallback;
maybeInvokeCallbacks();
}
public void onSuccess(SuccessCallback<V> successCallback) {
onSuccessOrError(successCallback, null);
}
public void onError(ExceptionCallback exceptionCallback) {
onSuccessOrError(null, exceptionCallback);
}
private final V getResultOrThrow() throws ExecutionException {
assert (result != null || exception != null);
if (result != null) {
return result;
}
throw new ExecutionException(exception);
}
@Override
public synchronized final V get() throws InterruptedException, ExecutionException {
while (result == null && exception == null) {
wait();
}
return getResultOrThrow();
}
@Override
public synchronized final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
final long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
while (result != null && exception != null) {
final long waitTimeRemaining = deadline - System.currentTimeMillis();
if (waitTimeRemaining > 0) {
wait(waitTimeRemaining);
}
}
if (result == null || exception == null) {
throw new TimeoutException();
}
return getResultOrThrow();
}
protected final synchronized void maybeInvokeCallbacks() {
if (result != null && successCallback != null) {
successCallback.onSuccess(result);
} else if (exception != null && exceptionCallback != null) {
exceptionCallback.processException(exception);
}
}
/**
* This method checks if the given exception is <b>not</b> fatal. If this method returns <code>false</code>, then
* the future will automatically set the given exception as failure reason and notify potential waiting threads.
*
* @param exception the exception to check.
* @return <code>true</code> if the exception is not fatal, <code>false</code> otherwise.
*/
protected abstract boolean isNonFatalException(Exception exception);
protected abstract void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException;
protected final void setResult(V result) {
assert (Thread.holdsLock(this));
this.result = result;
this.notifyAll();
maybeInvokeCallbacks();
}
public static abstract class InternalSmackFuture<V> extends SmackFuture<V> implements StanzaListener, ExceptionCallback {
@Override
public synchronized final void processException(Exception exception) {
if (!isNonFatalException(exception)) {
this.exception = exception;
this.notifyAll();
maybeInvokeCallbacks();
}
}
/**
* Wrapper method for {@link #handleStanza(Stanza)}. Note that this method is <code>synchronized</code>.
*/
@Override
public synchronized final void processStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
handleStanza(stanza);
}
}
/**
* A simple version of InternalSmackFuture which implements {@link #isNonFatalException(Exception)} as always returning <code>false</code> method.
*
* @param <V>
*/
public static abstract class SimpleInternalSmackFuture<V> extends InternalSmackFuture<V> {
@Override
protected boolean isNonFatalException(Exception exception) {
return false;
}
}
}

View file

@ -0,0 +1,23 @@
/**
*
* Copyright 2017 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
public interface SuccessCallback<T> {
public void onSuccess(T result);
}

View file

@ -0,0 +1,57 @@
/**
*
* Copyright 2017 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackFuture.InternalSmackFuture;
import org.jivesoftware.smack.SmackFuture.SimpleInternalSmackFuture;
import org.jivesoftware.smack.packet.Stanza;
import org.junit.Test;
public class SmackFutureTest {
@Test
public void simpleSmackFutureSuccessTest() throws NotConnectedException, InterruptedException, ExecutionException {
InternalSmackFuture<Boolean> future = new SimpleInternalSmackFuture<Boolean>() {
@Override
protected void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
setResult(true);
}
};
future.processStanza(null);
assertTrue(future.get());
}
@Test(expected = TimeoutException.class)
public void simpleSmackFutureTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
InternalSmackFuture<Boolean> future = new SimpleInternalSmackFuture<Boolean>() {
@Override
protected void handleStanza(Stanza stanza) throws NotConnectedException, InterruptedException {
}
};
future.get(5, TimeUnit.SECONDS);
}
}

View file

@ -31,17 +31,20 @@ import org.jivesoftware.smack.AbstractConnectionClosedListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.NotLoggedInException;
import org.jivesoftware.smack.SmackFuture;
import org.jivesoftware.smack.SmackFuture.InternalSmackFuture;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.ping.packet.Ping;
@ -173,6 +176,41 @@ public final class PingManager extends Manager {
return type == XMPPError.Type.CANCEL && condition == XMPPError.Condition.feature_not_implemented;
}
public SmackFuture<Boolean> pingAsync(Jid jid) {
return pingAsync(jid, connection().getReplyTimeout());
}
public SmackFuture<Boolean> pingAsync(final Jid jid, long pongTimeout) {
final InternalSmackFuture<Boolean> future = new InternalSmackFuture<Boolean>() {
@Override
public void handleStanza(Stanza packet) throws NotConnectedException, InterruptedException {
setResult(true);
}
@Override
public boolean isNonFatalException(Exception exception) {
if (exception instanceof XMPPErrorException) {
XMPPErrorException xmppErrorException = (XMPPErrorException) exception;
if (isValidErrorPong(jid, xmppErrorException)) {
setResult(true);
return true;
}
}
return false;
}
};
Ping ping = new Ping(jid);
try {
XMPPConnection connection = getAuthenticatedConnectionOrThrow();
connection.sendIqWithResponseCallback(ping, future, future, pongTimeout);
}
catch (NotLoggedInException | NotConnectedException | InterruptedException e) {
future.processException(e);
}
return future;
}
/**
* Pings the given jid. This method will return false if an error occurs. The exception
* to this, is a server ping, which will always return true if the server is reachable,

View file

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2017 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,10 +18,23 @@ package org.jivesoftware.smackx.ping;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jxmpp.jid.Jid;
public class PingIntegrationTest extends AbstractSmackIntegrationTest {
@ -35,4 +48,52 @@ public class PingIntegrationTest extends AbstractSmackIntegrationTest {
assertTrue(pingManager.pingMyServer());
}
private static final class Pinger implements Runnable {
private final List<Jid> toPing;
private final Collection<Future<Boolean>> pongFutures;
private final PingManager pingManager;
private Pinger(XMPPConnection connection, Collection<Future<Boolean>> pongFutures, Jid... toPing) {
this(connection, pongFutures, Arrays.asList(toPing));
}
private Pinger(XMPPConnection connection, Collection<Future<Boolean>> pongFutures, List<Jid> toPing) {
this.toPing = toPing;
this.pongFutures = pongFutures;
this.pingManager = PingManager.getInstanceFor(connection);
}
@Override
public void run() {
List<Future<Boolean>> futures = new ArrayList<>();
for (Jid jid : toPing) {
Future<Boolean> future = pingManager.pingAsync(jid);
futures.add(future);
}
pongFutures.addAll(futures);
}
}
@SmackIntegrationTest
public void pingAsync() throws InterruptedException, ExecutionException {
List<Future<Boolean>> pongFutures = Collections.synchronizedList(new ArrayList<Future<Boolean>>());
Runnable[] pinger = new Runnable[3];
pinger[0] = new Pinger(conOne, pongFutures, conTwo.getUser(), conThree.getUser());
pinger[1] = new Pinger(conTwo, pongFutures, conOne.getUser(), conThree.getUser());
pinger[2] = new Pinger(conThree, pongFutures, conOne.getUser(), conTwo.getUser());
ExecutorService executorService = Executors.newFixedThreadPool(pinger.length);
for (Runnable runnable : pinger) {
executorService.execute(runnable);
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
for (Future<Boolean> pongFuture : pongFutures) {
assertTrue(pongFuture.get());
}
}
}