public void testListenInPoolThreadReturnsSameFuture() throws Exception { ListenableFuture<String> listenableFuture = immediateFuture(DATA1); assertSame(listenableFuture, listenInPoolThread(listenableFuture)); }
@Override public void send(final String topic, final byte[] message) { final String combinedTopic = topicPrefix + topic; if (!healthchecker.isHealthy()) { log.warn("will not publish message to pubsub topic={} as the pubsub client " + "appears to be unhealthy", combinedTopic); return; } try { Futures.addCallback( JdkFutureAdapters.listenInPoolThread( pubsub.publishAsync(combinedTopic, Message.of(ByteArray.copyFrom(message)))), new FutureCallback<String>() { @Override public void onSuccess(@Nullable final String ackId) { log.debug("Sent an event to Google PubSub, topic: {}, ack: {}", combinedTopic, ackId); } @Override public void onFailure(final Throwable th) { log.warn("Unable to send an event to Google PubSub, topic: {}", combinedTopic, th); } }, MoreExecutors.directExecutor()); } catch (Exception e) { log.warn("Failed to publish Google PubSub message, topic: {}", combinedTopic, e); } }
public void testListenInPoolThreadRunsListenerAfterRuntimeException() throws Exception { RuntimeExceptionThrowingFuture<String> input = new RuntimeExceptionThrowingFuture<>(); /* * The compiler recognizes that "input instanceof ListenableFuture" is * impossible. We want the test, though, in case that changes in the future, * so we use isInstance instead. */ assertFalse( "Can't test the main listenInPoolThread path " + "if the input is already a ListenableFuture", ListenableFuture.class.isInstance(input)); ListenableFuture<String> listenable = listenInPoolThread(input); /* * This will occur before the waiting get() in the * listenInPoolThread-spawned thread completes: */ RecordingRunnable earlyListener = new RecordingRunnable(); listenable.addListener(earlyListener, directExecutor()); input.allowGetToComplete.countDown(); // Now give the get() thread time to finish: assertTrue(earlyListener.wasRun.await(1, SECONDS)); // Now test an additional addListener call, which will be run in-thread: RecordingRunnable lateListener = new RecordingRunnable(); listenable.addListener(lateListener, directExecutor()); assertTrue(lateListener.wasRun.await(1, SECONDS)); }
ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, executorService);
public void testListenInPoolThreadUsesGivenExecutor() throws Exception { ExecutorService executorService = newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).build()); NonListenableSettableFuture<String> abstractFuture = NonListenableSettableFuture.create(); ExecutorSpy spy = new ExecutorSpy(executorService); ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, spy); SingleCallListener singleCallListener = new SingleCallListener(); singleCallListener.expectCall(); assertFalse(spy.wasExecuted); assertFalse(singleCallListener.wasCalled()); assertFalse(listenableFuture.isDone()); listenableFuture.addListener(singleCallListener, executorService); abstractFuture.set(DATA1); assertEquals(DATA1, listenableFuture.get()); singleCallListener.waitForCall(); assertTrue(spy.wasExecuted); assertTrue(singleCallListener.wasCalled()); assertTrue(listenableFuture.isDone()); }
public void testListenInPoolThreadIgnoresExecutorWhenDelegateIsDone() throws Exception { NonListenableSettableFuture<String> abstractFuture = NonListenableSettableFuture.create(); abstractFuture.set(DATA1); ExecutorSpy spy = new ExecutorSpy(directExecutor()); ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, spy); SingleCallListener singleCallListener = new SingleCallListener(); singleCallListener.expectCall(); assertFalse(spy.wasExecuted); assertFalse(singleCallListener.wasCalled()); assertTrue(listenableFuture.isDone()); // We call AbstractFuture#set above. // #addListener() will run the listener immediately because the Future is // already finished (we explicitly set the result of it above). listenableFuture.addListener(singleCallListener, directExecutor()); assertEquals(DATA1, listenableFuture.get()); // 'spy' should have been ignored since 'abstractFuture' was done before // a listener was added. assertFalse(spy.wasExecuted); assertTrue(singleCallListener.wasCalled()); assertTrue(listenableFuture.isDone()); }
/** * {@inheritDoc} */ @Override public Object processResultFuture(final Future<?> future, final ExecutorService executor) { return JdkFutureAdapters.listenInPoolThread(future, executor); }
protected ScheduledTask<V> submittedScheduledTask(ScheduledFuture delegate) { this.submissionDate = System.currentTimeMillis(); this.scheduledFuture = delegate; this.future = JdkFutureAdapters.listenInPoolThread(delegate); return this; }
protected Task<V> submitted(Future<V> future) { this.submissionDate = System.currentTimeMillis(); this.future = JdkFutureAdapters.listenInPoolThread(future); return this; }
@Override public ListenableFuture<String> asyncGet(final String url) { return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() { @Override public String call() throws RobotConnectionException { return get(url); } })); }
@Override public ListenableFuture<String> asyncPostJson(final String url, final String body) { return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() { @Override public String call() throws RobotConnectionException { return postJson(url, body); } })); }
public ListenableFuture<State> start() { ListenableFuture<Nothing> runListener = JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<Nothing>() { @Override public Nothing call() { listener.onDistributionStarted(sessionId, taskId, task, remotes.keySet()); return Nothing.INSTANCE; } })); return Futures.transform(runListener, new AsyncFunction<Nothing, State>() { @Override public ListenableFuture<State> apply(Nothing input) { return doStart(); } }); }
public <E extends DataObject> void sendResponseToCore(Future<RpcResult<E>> switchReply, final ZeroMQBaseConnector coreConnector, final short ofVersion, final long xId, final long datapathId, final int moduleId) { Futures.addCallback(JdkFutureAdapters.listenInPoolThread(switchReply), new FutureCallback<RpcResult<E>>() { @Override public void onSuccess(RpcResult<E> rpcReply) { if (rpcReply.isSuccessful()) { E result = rpcReply.getResult(); sendOpenFlowMessageToCore(coreConnector, result, ofVersion, xId, datapathId, moduleId); } else { for (RpcError rpcError : rpcReply.getErrors()) { LOG.info("SHIM RELAY: error in communication with switch: {}", rpcError.getMessage()); } } } @Override public void onFailure(Throwable t) { LOG.info("SHIM RELAY: failure on communication with switch"); } }); } }
public void collectGetFeaturesOuput(Future<RpcResult<GetFeaturesOutput>> switchReply, final ConnectionAdapter connectionAdapter) { Futures.addCallback(JdkFutureAdapters.listenInPoolThread(switchReply), new FutureCallback<RpcResult<GetFeaturesOutput>>() { @Override public void onSuccess(RpcResult<GetFeaturesOutput> rpcFeatures) { if (rpcFeatures.isSuccessful()) { GetFeaturesOutput featureOutput = rpcFeatures.getResult(); // Register Switch connection/DatapathId to registry connectionRegistry.registerConnectionAdapter(connectionAdapter, featureOutput); NodeUpdated nodeUpdated = nodeAdded(connectionAdapter); notificationProviderService.offerNotification(nodeUpdated); } else { // Handshake failed for (RpcError rpcError : rpcFeatures.getErrors()) { LOG.info("handshake - features failure [{}]: i:{} | m:{} | s:{}", rpcError.getInfo(), rpcError.getMessage(), rpcError.getSeverity(), rpcError.getCause()); } } } @Override public void onFailure(Throwable t) { LOG.info("getting feature failed seriously [addr:{}]: {}", connectionAdapter.getRemoteAddress(), t.getMessage()); } }); }
/** * Creates a promise from the given future. * * @param future The future delegate for the new promise * @return The new promise */ public static <A> Promise<A> forFuture(Future<A> future) { return new Of<A>(JdkFutureAdapters.listenInPoolThread(future)); }
/** * Creates Will object from JKS's {@link java.util.concurrent.Future} * * @param future JKS's Future * @param <A> Type of Future and Will to be created * @return Created Will */ public static <A> Will<A> forFuture(Future<A> future) { return new Of<A>(JdkFutureAdapters.listenInPoolThread(future)); }
/** * @param sessionContext switch session context * @return generationId from future RpcResult */ public static Future<BigInteger> readGenerationIdFromDevice(SessionContext sessionContext) { Future<RpcResult<RoleRequestOutput>> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE, BigInteger.ZERO); final SettableFuture<BigInteger> result = SettableFuture.create(); Futures.addCallback(JdkFutureAdapters.listenInPoolThread(roleReply), new FutureCallback<RpcResult<RoleRequestOutput>>() { @Override public void onSuccess(RpcResult<RoleRequestOutput> input) { if(input != null && input.getResult() != null) { result.set(input.getResult().getGenerationId()); } } @Override public void onFailure(Throwable t) { //TODO } }); return result; }
@Override public ListenableFuture<HttpResponse> submit(final HttpCommand command) { HTTPRequest nativeRequest = filterLogAndConvertRe(command.getCurrentRequest()); ListenableFuture<HttpResponse> response = transform( listenInPoolThread(urlFetchService.fetchAsync(nativeRequest)), convertToJcloudsResponse); return transform(response, new Function<HttpResponse, HttpResponse>() { public HttpResponse apply(HttpResponse response) { return receiveResponse(command, response); } }, ioExecutor); }
@Override public ListenableFuture<RpcResult<Void>> apply(final Optional<AddressEndpoint> input) throws Exception { final ListenableFuture<RpcResult<Void>> nextResult; if (input == null || !input.isPresent() || !isSameEpg(epInput, input.get())) { // invoke service return JdkFutureAdapters.listenInPoolThread(l3EndpointService.registerEndpoint(epInput)); } else { final String existingL3EpMsg = String.format("address-endpoint for given key already exists: %s | %s", addressEndpoint.getContextId(), addressEndpoint.getAddress() ); nextResult = Futures.immediateFailedFuture(new IllegalStateException(existingL3EpMsg)); } return nextResult; } });
private ListenableFuture<RpcResult<?>> invoke(final SchemaPath schemaPath, final DataObject input) { return JdkFutureAdapters.listenInPoolThread(invoker.invokeRpc(delegate, schemaPath.getLastComponent(), input)); }