@Override public CheckedFuture<Void, TransactionCommitFailedException> submit( final DOMDataWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) { checkNotFailed(); checkNotClosed(); final CheckedFuture<Void, TransactionCommitFailedException> ret = broker.submit(transaction, cohorts); COUNTER_UPDATER.incrementAndGet(this); Futures.addCallback(ret, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { transactionCompleted(); } @Override public void onFailure(final Throwable t) { transactionFailed(transaction, t); } }); return ret; }
private CheckedFuture<Void, TransactionCommitFailedException> listenForFailure( final WriteTransaction tx, final CheckedFuture<Void, TransactionCommitFailedException> future) { Futures.addCallback(future, new FutureCallback<Void>() { @Override public void onFailure(final Throwable t) { failTransactionChain(tx,t); } @Override public void onSuccess(final Void result) { // Intentionally NOOP } }); return future; }
@Override public ListenableFuture<ApduResponse> apply(byte[] in) { // how to actually transmit to the card // here we just use the normal transmit stuff try { ByteBuffer command = ByteBuffer.wrap(in); ByteBuffer response = ByteBuffer.allocate(1024); // TODO is this reasonable? int size = card.getBasicChannel().transmit(command, response); byte[] out = new byte[size]; System.arraycopy(response.array(), 0, out, 0, size); return Futures.immediateFuture(new ApduResponse(out)); } catch (CardException e) { throw new RuntimeException(e); } }
@Nonnull @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final DOMRpcIdentifier rpc, @Nullable final NormalizedNode<?, ?> input) { LOG.debug("get-constant invoked, current value: {}", constant); final LeafNode<Object> value = ImmutableLeafNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(CONSTANT)) .withValue(constant) .build(); final ContainerNode result = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(OUTPUT)) .withChild(value) .build(); return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(result)); }
@Test public void handlesFailure() throws Exception { final AtomicReference<Object> value = new AtomicReference<>(); Exception ex = new Exception("This is bad"); ListenableFuture<String> future = Futures.immediateFailedFuture(ex); GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() { @Override protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception { value.set(deferredResult.getResult()); } }; handler.handleReturnValue(future, null, null, null); assertThat(value.get()).isEqualTo(ex); }
/** * Notify the {@link ReplicaManager} to send an update the next possible time it can * * @return futures with the result of the update */ @Nonnull @VisibleForTesting List<ListenableFuture<AppendEntriesResponse>> sendRequests(final RaftStateContext ctx) { List<ListenableFuture<AppendEntriesResponse>> responses = newArrayList(); for (ReplicaManager replicaManager : managers.values()) { ListenableFuture<AppendEntriesResponse> response = replicaManager.requestUpdate(); responses.add(response); Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() { @Override public void onSuccess(@Nullable AppendEntriesResponse result) { updateCommitted(); checkTermOnResponse(ctx, result); } @Override public void onFailure(Throwable t) { } }); } return responses; }
@Test public void testExecuteRpc() { new JavaTestKit(node1) { { final ContainerNode invokeRpcResult = makeRPCOutput("bar"); final DOMRpcResult rpcResult = new DefaultDOMRpcResult(invokeRpcResult); when(domRpcService1.invokeRpc(eq(TEST_RPC_TYPE), Mockito.<NormalizedNode<?, ?>>any())).thenReturn( Futures.<DOMRpcResult, DOMRpcException>immediateCheckedFuture(rpcResult)); final ExecuteRpc executeMsg = ExecuteRpc.from(TEST_RPC_ID, null); rpcInvoker1.tell(executeMsg, getRef()); final RpcResponse rpcResponse = expectMsgClass(duration("5 seconds"), RpcResponse.class); assertEquals(rpcResult.getResult(), rpcResponse.getResultNormalizedNode()); } }; }
private <T extends DataObject> void putData(final LogicalDatastoreType store, final InstanceIdentifier<T> path, final T data){ final WriteTransaction tx = getDataBroker().newWriteOnlyTransaction(); tx.put(store, path, data, true); Futures.addCallback( tx.submit(), new FutureCallback<Void>(){ @Override public void onSuccess(final Void result) { LOG.trace("Data has put into datastore {} {}", store, path); } @Override public void onFailure(final Throwable t) { LOG.error("Can not put data into datastore [store: {}] [path: {}] [exception: {}]",store,path, t); } }); }
@Override protected CheckedFuture<Void, TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) { Preconditions.checkArgument(transaction != null, "Transaction must not be null."); Preconditions.checkArgument(cohorts != null, "Cohorts must not be null."); LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier()); if (cohorts.isEmpty()) { return Futures.immediateCheckedFuture(null); } final AsyncNotifyingSettableFuture clientSubmitFuture = new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor); doCanCommit(clientSubmitFuture, transaction, cohorts); return MappingCheckedFuture.create(clientSubmitFuture, COMMIT_ERROR_MAPPER); }
@Test public void testSValue() throws Exception { // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability // issue that can allow someone to change a transaction [hash] without invalidating the signature. final int ITERATIONS = 10; ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS)); List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList(); final ECKey key = new ECKey(); for (byte i = 0; i < ITERATIONS; i++) { final byte[] hash = HashUtil.sha3(new byte[]{i}); sigFutures.add(executor.submit(new Callable<ECKey.ECDSASignature>() { @Override public ECKey.ECDSASignature call() throws Exception { return key.doSign(hash); } })); } List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get(); for (ECKey.ECDSASignature signature : sigs) { assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0); } final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s); assertEquals(sigs.get(0), duplicate); assertEquals(sigs.get(0).hashCode(), duplicate.hashCode()); }
@Command( aliases = {"hub", "lobby"}, desc = "Teleport to the lobby" ) public void hub(final CommandContext args, CommandSender sender) throws CommandException { if(sender instanceof ProxiedPlayer) { final ProxiedPlayer player = (ProxiedPlayer) sender; final Server server = Futures.getUnchecked(executor.submit(() -> serverTracker.byPlayer(player))); if(server.role() == ServerDoc.Role.LOBBY || server.role() == ServerDoc.Role.PGM) { // If Bukkit server is running Commons, let it handle the command throw new CommandBypassException(); } player.connect(proxy.getServerInfo("default")); player.sendMessage(new ComponentBuilder("Teleporting you to the lobby").color(ChatColor.GREEN).create()); } else { sender.sendMessage(new ComponentBuilder("Only players may use this command").color(ChatColor.RED).create()); } }
@Test public void loadProjectList_callback_registers_exception_on_ack_future( ) throws Exception { // Setup when( _mockRequestController.sendRequest( getApiVersion( ), "projects", ProjectList.class ) ) .thenReturn( Futures.immediateFailedFuture( new RuntimeException( "Unexpected test exception" ) ) ); // Exercise final ListenableFuture<Void> ackFuture = _apiController.loadProjectList( ); // Verify try { ackFuture.get( ); } catch ( ExecutionException e ) { if ( e.getCause( ).getClass( ) == RuntimeException.class && e.getCause( ).getMessage( ).equals( "Unexpected test exception" ) ) return; } TestCase.fail( ); }
/** * Process a ready transaction. The caller needs to ensure that * each transaction is seen only once by this method. * * @param tx Transaction which needs processing. */ @GuardedBy("this") private void processTransaction(@Nonnull final PingPongTransaction tx) { if (failed) { LOG.debug("Cancelling transaction {}", tx); tx.getTransaction().cancel(); return; } LOG.debug("Submitting transaction {}", tx); if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) { LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx); } Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { transactionSuccessful(tx, result); } @Override public void onFailure(final Throwable t) { transactionFailed(tx, t); } }, MoreExecutors.directExecutor()); }
@Override public ListenableFuture<List<OperationResult>> transactConfig(String dbName, List<Operation> operations) { if (dbName == null) { return null; } DatabaseSchema dbSchema = schema.get(dbName); if (dbSchema != null) { Function<List<JsonNode>, List<OperationResult>> rowFunction = (input -> { log.info("Get ovsdb operation result"); List<OperationResult> result = FromJsonUtil .jsonNodeToOperationResult(input, operations); if (result == null) { log.debug("The operation result is null"); return null; } return result; }); return Futures.transform(transact(dbSchema, operations), rowFunction); } return null; }
protected void watchCloseConfirmations() { // When we see the close transaction get enough confirmations, we can just delete the record // of this channel along with the refund tx from the wallet, because we're not going to need // any of that any more. final TransactionConfidence confidence = storedChannel.close.getConfidence(); int numConfirms = Context.get().getEventHorizon(); ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD); Futures.addCallback(future, new FutureCallback<TransactionConfidence>() { @Override public void onSuccess(TransactionConfidence result) { deleteChannelFromWallet(); } @Override public void onFailure(Throwable t) { Throwables.propagate(t); } }); }
/** * Kick a player from the server with a reason */ public void kickPlayerFromServer(String reason) { final TextComponentString textcomponentstring = new TextComponentString(reason); this.netManager.sendPacket(new SPacketDisconnect(textcomponentstring), new GenericFutureListener < Future <? super Void >> () { public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception { NetHandlerPlayServer.this.netManager.closeChannel(textcomponentstring); } }, new GenericFutureListener[0]); this.netManager.disableAutoRead(); Futures.getUnchecked(this.serverController.addScheduledTask(new Runnable() { public void run() { NetHandlerPlayServer.this.netManager.checkDisconnected(); } })); }
@Test public void testReadWriteOperations() throws Exception { doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(readTx) .read(any(), any()); rwTx.put(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(1, 2, 3)); verify(writeTx).put(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH), Matchers.eq(testNodeWithOuter(1, 2, 3))); verify(readTx).read(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH)); assertEquals(testNodeWithOuter(1, 2, 3), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get()); rwTx.merge(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(4, 5, 6)); assertEquals(testNodeWithOuter(1, 2, 3, 4, 5, 6), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get()); rwTx.delete(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH); verify(writeTx).delete(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH)); assertEquals(Optional.absent(), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet()); }
public <V> ListenableFuture<V> callFromMainThread(Callable<V> callable) { Validate.notNull(callable); if (!this.isCallingFromMinecraftThread() && !this.isServerStopped()) { ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callable); synchronized (this.futureTaskQueue) { this.futureTaskQueue.add(listenablefuturetask); return listenablefuturetask; } } else { try { return Futures.<V>immediateFuture(callable.call()); } catch (Exception exception) { return Futures.immediateFailedCheckedFuture(exception); } } }
/** * Run the job now. * The job must set its own state to DISABLED or PAUSED when failed, otherwise it is set to ACTIVE. * @param yadaJob * @return */ public void runJob(Long yadaJobId) { log.debug("Running job id {}", yadaJobId); YadaJob toRun = yadaJobRepository.findOne(yadaJobId); if (toRun==null) { log.info("Job not found when trying to run it, id={}", toRun); return; } yadaJobRepository.internalSetRunning(yadaJobId, YadaJobState.RUNNING.toId(), YadaJobState.ACTIVE.toId()); final YadaJob wiredYadaJob = (YadaJob) yadaUtil.autowire(toRun); // YadaJob instances can have @Autowire fields ListenableFuture<Void> jobHandle = jobScheduler.submit(wiredYadaJob); jobHandles.put(yadaJobId, jobHandle); Futures.addCallback(jobHandle, new FutureCallback<Void>() { // The callback is run in executor public void onSuccess(Void result) { // result is always null jobHandles.remove(yadaJobId); yadaJobSchedulerDao.internalJobSuccessful(wiredYadaJob); } public void onFailure(Throwable thrown) { jobHandles.remove(yadaJobId); yadaJobSchedulerDao.internalJobFailed(wiredYadaJob, thrown); } }, MoreExecutors.directExecutor()); }
@Override public ListenableFuture<TableUpdates> monitorTables(String dbName, String id) { if (dbName == null) { return null; } DatabaseSchema dbSchema = schema.get(dbName); if (dbSchema != null) { Function<JsonNode, TableUpdates> rowFunction = new Function<JsonNode, TableUpdates>() { @Override public TableUpdates apply(JsonNode input) { log.info("Get table updates"); TableUpdates updates = FromJsonUtil .jsonNodeToTableUpdates(input, dbSchema); if (updates == null) { log.debug("Get table updates error"); return null; } return updates; } }; return Futures.transform(monitor(dbSchema, id), rowFunction); } return null; }
public <V> ListenableFuture<V> addScheduledTask(Callable<V> callableToSchedule) { Validate.notNull(callableToSchedule); if (this.isCallingFromMinecraftThread()) { try { return Futures.<V>immediateFuture(callableToSchedule.call()); } catch (Exception exception) { return Futures.immediateFailedCheckedFuture(exception); } } else { ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callableToSchedule); synchronized (this.scheduledTasks) { this.scheduledTasks.add(listenablefuturetask); return listenablefuturetask; } } }
public <V> ListenableFuture<V> addScheduledTask(Callable<V> callableToSchedule) { Validate.notNull(callableToSchedule); if (!this.isCallingFromMinecraftThread()) { ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callableToSchedule); synchronized (this.scheduledTasks) { this.scheduledTasks.add(listenablefuturetask); return listenablefuturetask; } } else { try { return Futures.<V>immediateFuture(callableToSchedule.call()); } catch (Exception exception) { return Futures.immediateFailedCheckedFuture(exception); } } }
@Override public ListenableFuture<Void> commit() { LOG.debug("Committing transaction for shard {}", shardRoot); checkTransactionReadied(); final List<ListenableFuture<Void>> futures = cohorts.stream().map(DOMStoreThreePhaseCommitCohort::commit).collect(Collectors.toList()); final SettableFuture<Void> ret = SettableFuture.create(); Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<Void>>() { @Override public void onSuccess(final List<Void> result) { ret.set(null); } @Override public void onFailure(final Throwable throwable) { ret.setException(throwable); } }, MoreExecutors.directExecutor()); return ret; }
@Override public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { checkState(root != null, "A modify operation (put, merge or delete) must be performed prior to a read operation"); final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create(); final Queue<Modification> currentHistory = Lists.newLinkedList(modificationHistoryMap.get(store)); Futures.addCallback(initialReadMap.get(store), new FutureCallback<Optional<NormalizedNode<?, ?>>>() { @Override public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) { final DataTreeModification mod = snapshotMap.get(store).newModification(); if (result.isPresent()) { mod.write(path, result.get()); } applyModificationHistoryToSnapshot(mod, currentHistory); readResult.set(mod.readNode(path)); } @Override public void onFailure(final Throwable t) { readResult.setException(t); } }, MoreExecutors.directExecutor()); return Futures.makeChecked(readResult, ReadFailedException.MAPPER); }
@Nonnull @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull DOMRpcIdentifier rpc, @Nullable NormalizedNode<?, ?> input) { LOG.debug("get-singleton-constant invoked, current value: {}", constant); final LeafNode<Object> value = ImmutableLeafNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(CONSTANT)) .withValue(constant) .build(); final ContainerNode result = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new NodeIdentifier(OUTPUT)) .withChild(value) .build(); return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(result)); }
/** * This test method invokes and executes the remote rpc. */ @Test(expected = DOMRpcException.class) public void testInvokeRpcWithRemoteFailedFuture() throws Exception { final NormalizedNode<?, ?> invokeRpcInput = makeRPCInput("foo"); @SuppressWarnings({"unchecked", "rawtypes"}) final ArgumentCaptor<NormalizedNode<?, ?>> inputCaptor = (ArgumentCaptor) ArgumentCaptor.forClass(NormalizedNode.class); when(domRpcService2.invokeRpc(eq(TEST_RPC_TYPE), inputCaptor.capture())).thenReturn( Futures.<DOMRpcResult, DOMRpcException>immediateFailedCheckedFuture(new RemoteDOMRpcException( "Test Exception", null))); final CheckedFuture<DOMRpcResult, DOMRpcException> frontEndFuture = remoteRpcImpl1.invokeRpc(TEST_RPC_ID, invokeRpcInput); assertTrue(frontEndFuture instanceof RemoteDOMRpcFuture); frontEndFuture.checkedGet(5, TimeUnit.SECONDS); }
public ListenableFuture<?> requestRestart(String reason, int priority) { if(this.isRestartRequested(priority)) { return Futures.immediateCancelledFuture(); } else { final Instant now = Instant.now(); logger.info("Requesting restart at " + now + ", because " + reason); return minecraftService.updateLocalServer(new ServerDoc.Restart() { @Override public Instant restart_queued_at() { return now; } @Override public String restart_reason() { return reason; } @Override public int restart_priority() { return priority; } }); } }
public NestedLoopContext(ESLogger logger, NestedLoopPhase phase, FlatProjectorChain flatProjectorChain, NestedLoopOperation nestedLoopOperation, @Nullable PageDownstreamContext leftPageDownstreamContext, @Nullable PageDownstreamContext rightPageDownstreamContext) { super(phase.executionPhaseId(), logger); nestedLoopPhase = phase; this.flatProjectorChain = flatProjectorChain; this.leftPageDownstreamContext = leftPageDownstreamContext; this.rightPageDownstreamContext = rightPageDownstreamContext; leftRowReceiver = nestedLoopOperation.leftRowReceiver(); rightRowReceiver = nestedLoopOperation.rightRowReceiver(); if (leftPageDownstreamContext == null) { Futures.addCallback(leftRowReceiver.finishFuture(), new RemoveContextCallback()); } else { leftPageDownstreamContext.future.addCallback(new RemoveContextCallback()); } if (rightPageDownstreamContext == null) { Futures.addCallback(rightRowReceiver.finishFuture(), new RemoveContextCallback()); } else { rightPageDownstreamContext.future.addCallback(new RemoveContextCallback()); } }
private ListenableFuture<EntityRelationInfo> fetchRelationInfoAsync(EntityRelation relation, Function<EntityRelation, EntityId> entityIdGetter, BiConsumer<EntityRelationInfo, String> entityNameSetter) { ListenableFuture<String> entityName = entityService.fetchEntityNameAsync(entityIdGetter.apply(relation)); ListenableFuture<EntityRelationInfo> entityRelationInfo = Futures.transform(entityName, (Function<String, EntityRelationInfo>) entityName1 -> { EntityRelationInfo entityRelationInfo1 = new EntityRelationInfo(relation); entityNameSetter.accept(entityRelationInfo1, entityName1); return entityRelationInfo1; }); return entityRelationInfo; }
public ListenableFuture<PlayerSearchResponse> findPlayer(CommandSender sender, @Nullable String name, Scope scope, Default def) { try { final Player player = getLocalPlayer(sender, name); if(player != null) { return Futures.immediateFuture(localPlayerResponse(sender, player)); } if(scope.noGreaterThan(Scope.LOCAL)) { throw new TranslatableCommandException("command.playerNotFound"); } final SettableFuture<PlayerSearchResponse> playerResult = SettableFuture.create(); mainThreadExecutor.callback( findUser(sender, name, scope, def), new FutureCallback<UserSearchResponse>() { @Override public void onSuccess(@Nullable UserSearchResponse userResult) { playerResult.set(new PlayerSearchResponse(userResult, onlinePlayers.find(userResult.user))); } @Override public void onFailure(Throwable t) { playerResult.setException(t); } } ); return playerResult; } catch(CommandException e) { return Futures.immediateFailedFuture(e); } }
private void initializeDataTree(DataBroker db) { LOG.info("Preparing to initialize the greeting registry"); WriteTransaction transaction = db.newWriteOnlyTransaction(); InstanceIdentifier<GreetingRegistry> iid = InstanceIdentifier.create(GreetingRegistry.class); GreetingRegistry greetingRegistry = new GreetingRegistryBuilder() .build(); transaction.put(LogicalDatastoreType.OPERATIONAL, iid, greetingRegistry); CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit(); Futures.addCallback(future, new LoggingFuturesCallBack<>("Failed to create greeting registry", LOG)); }
@Override public void loadAttributes(EntityId entityId, String attributeType, Collection<String> attributeKeys, final PluginCallback<List<AttributeKvEntry>> callback) { validate(entityId, new ValidationCallback(callback, ctx -> { ListenableFuture<List<AttributeKvEntry>> future = pluginCtx.attributesService.find(entityId, attributeType, attributeKeys); Futures.addCallback(future, getCallback(callback, v -> v), executor); })); }
@Produces static ListenableFuture<Recipe> recipe( List<String> ingredients, SearchResponse searchResponse, Supplier<Random> randomSupplier, YummlyApi yummly) { int totalCount = searchResponse.totalMatchCount(); ListenableFuture<SearchResponse> future = Futures.immediateFuture(null); // Get a random recipe to return. Search request fails randomly so try a few times. Executor executor = RequestContext.current().contextAwareEventLoop(); Random random = randomSupplier.get(); for (int i = 0; i < 5; i++) { int resultIndex = random.nextInt(totalCount); future = Futures.transformAsync( future, result -> { if (result != null && !result.matches().isEmpty()) { return Futures.immediateFuture(result); } return yummly.search( EggworldConstants.EGG_QUERY, ingredients, resultIndex, 1, true, ImmutableList.of()); }, executor); } return Futures.transform(future, r -> r.matches().get(0), MoreExecutors.directExecutor()); }
@Test public void serverIsRunningAndSayHelloReturnsExpectedResponse() throws Exception { final String name = UUID.randomUUID().toString(); grpcServerHost.start(); ManagedChannel channel = ManagedChannelBuilder .forAddress("localhost", grpcServerHost.getPort()) .usePlaintext(true) .build(); GreeterGrpc.GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel); ListenableFuture<HelloResponse> responseFuture = stub.sayHello(HelloRequest.newBuilder().setName(name).build()); AtomicReference<HelloResponse> response = new AtomicReference<>(); Futures.addCallback( responseFuture, new FutureCallback<HelloResponse>() { @Override public void onSuccess(@Nullable HelloResponse result) { response.set(result); } @Override public void onFailure(Throwable t) { } }, MoreExecutors.directExecutor()); await().atMost(10, TimeUnit.SECONDS).until(responseFuture::isDone); channel.shutdownNow(); assertThat(response.get()).isNotNull(); assertThat(response.get().getMessage()).contains(name); }
public ListenableFuture<Boolean> commitAsync(final byte[] operation) throws RaftException { // Make sure this happens on the Barge thread ListenableFuture<ListenableFuture<Boolean>> response = executor.submit(new Callable<ListenableFuture<Boolean>>() { @Override public ListenableFuture<Boolean> call() throws Exception { // System.out.println("Sending operation"); return ctx.commitOperation(operation); } }); return Futures.dereference(response); }
private void notifyExistingNodes(final EventSourceTopology eventSourceTopology){ LOG.debug("Notify existing nodes"); final Pattern nodeRegex = this.nodeIdPattern; final ReadOnlyTransaction tx = eventSourceTopology.getDataBroker().newReadOnlyTransaction(); final CheckedFuture<Optional<Topology>, ReadFailedException> future = tx.read(LogicalDatastoreType.OPERATIONAL, EventSourceTopology.EVENT_SOURCE_TOPOLOGY_PATH); Futures.addCallback(future, new FutureCallback<Optional<Topology>>(){ @Override public void onSuccess(final Optional<Topology> data) { if(data.isPresent()) { final List<Node> nodes = data.get().getNode(); if(nodes != null){ for (final Node node : nodes) { if (nodeRegex.matcher(node.getNodeId().getValue()).matches()) { notifyNode(EventSourceTopology.EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, node.getKey())); } } } } tx.close(); } @Override public void onFailure(final Throwable t) { LOG.error("Can not notify existing nodes", t); tx.close(); } }); }
@Override public Future<RpcResult<EventDeregisterOutput>> eventDeregister(EventDeregisterInput input) { if (input == null) { return Futures.immediateFuture(eventDeregMissingBodyErr); } IetfDmmFpcagentService ifc = getStrategy(input.getClientId()); if (ifc != null) { return ifc.eventDeregister(input); } return Futures.immediateFuture(eventDeregUnknownClientErr); }
private ListenableFuture<?> quitFuture(Player player) { if(player.isOnline()) { final SettableFuture<?> future = SettableFuture.create(); player.setMetadata(METADATA_KEY, new FixedMetadataValue(plugin, future)); return future; } else { return Futures.immediateFuture(null); } }
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException { Preconditions.checkState(request != null); final SettableFuture<FullHttpResponse> error = SettableFuture.create(); final SettableFuture<FullHttpResponse> response = SettableFuture.create(); final ListenableFuture<ChannelFuture> connectFuture = connect(XUrl.getInetSocket(uri), client.getBootstrap(), buildRetryLoop()); Futures.addCallback( connectFuture, new FutureCallback<ChannelFuture>() { @Override public void onSuccess(ChannelFuture result) { try { Channel channel = result.await().channel(); channel.writeAndFlush(request); HttpResponseHandler responseHandler = (HttpResponseHandler) channel.pipeline().get("responseHandler"); response.setFuture(responseHandler.getResponse()); } catch (InterruptedException e) { response.cancel(true); error.setException(e); } } @Override public void onFailure(Throwable t) { response.cancel(true); error.setException(t); } }); if (response.isCancelled()) { return error; } else { return response; } }
@Override public Future<RpcResult<Void>> addShardReplica(final AddShardReplicaInput input) { final String shardName = input.getShardName(); if (Strings.isNullOrEmpty(shardName)) { return newFailedRpcResultFuture("A valid shard name must be specified"); } DataStoreType dataStoreType = input.getDataStoreType(); if (dataStoreType == null) { return newFailedRpcResultFuture("A valid DataStoreType must be specified"); } LOG.info("Adding replica for shard {}", shardName); final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create(); ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, new AddShardReplica(shardName)); Futures.addCallback(future, new FutureCallback<Success>() { @Override public void onSuccess(Success success) { LOG.info("Successfully added replica for shard {}", shardName); returnFuture.set(newSuccessfulResult()); } @Override public void onFailure(Throwable failure) { onMessageFailure(String.format("Failed to add replica for shard %s", shardName), returnFuture, failure); } }, MoreExecutors.directExecutor()); return returnFuture; }