Java Code Examples for com.google.common.util.concurrent.SettableFuture

The following are top voted examples for showing how to use com.google.common.util.concurrent.SettableFuture. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Elasticsearch   File: UpsertByIdTask.java   Source Code and License 6 votes vote down vote up
private void createIndexAndExecuteUpsertRequest(final UpsertByIdNode.Item item,
                                                final SettableFuture<TaskResult> futureResult) {
    transportCreateIndexAction.execute(
            new CreateIndexRequest(item.index()).cause("upsert single item"),
            new ActionListener<CreateIndexResponse>() {
        @Override
        public void onResponse(CreateIndexResponse createIndexResponse) {
            executeUpsertRequest(item, futureResult);
        }

        @Override
        public void onFailure(Throwable e) {
            e = ExceptionsHelper.unwrapCause(e);
            if (e instanceof IndexAlreadyExistsException) {
                executeUpsertRequest(item, futureResult);
            } else {
                futureResult.setException(e);
            }

        }
    });
}
 
Example 2
Project: talchain   File: ExternalMinerTest.java   Source Code and License 6 votes vote down vote up
@Test
    public void externalMiner_shouldWork() throws Exception {

        final Block startBestBlock = bc.getBlockchain().getBestBlock();

        final SettableFuture<MinerIfc.MiningResult> futureBlock = SettableFuture.create();

        blockMiner.setExternalMiner(new MinerIfc() {
            @Override
            public ListenableFuture<MiningResult> mine(Block block) {
//                System.out.print("Mining requested");
                return futureBlock;
            }

            @Override
            public boolean validate(BlockHeader blockHeader) {
                return true;
            }
        });
        Block b = bc.getBlockchain().createNewBlock(startBestBlock, EMPTY_LIST, EMPTY_LIST);
        Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get();
        futureBlock.set(new MinerIfc.MiningResult(ByteUtil.byteArrayToLong(b.getNonce()), b.getMixHash(), b));

        assertThat(bc.getBlockchain().getBestBlock().getNumber(), is(startBestBlock.getNumber() + 1));
    }
 
Example 3
Project: hashsdn-controller   File: ShardedDOMDataBrokerDelegatingReadWriteTransaction.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 4
Project: java-red   File: TestRedFuture.java   Source Code and License 6 votes vote down vote up
/**
 * Test the conversion of successful {@link Future} to {@link RedFuture}
 * through {@link RedFuture#convert(Future)}
 */
@Test
public void ListenableFutureConversionSuccess() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    AtomicBoolean reachedTypedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean correctValueReturned = new AtomicBoolean(false);
    SettableFuture<String> settableFuture = SettableFuture.create();
    RedFutureOf<String> redFuture = RedFuture.convert(settableFuture);
    redFuture.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    redFuture.addSuccessCallback(s -> {
        reachedTypedSuccessBlock.set(true);
        correctValueReturned.set(s.equals("test"));
    });
    redFuture.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    redFuture.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    settableFuture.set("test");
    Thread.sleep(VALIDATION_SLEEP_TIME);
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertTrue(reachedSuccessBlock.get());
    Assert.assertTrue(reachedTypedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
}
 
Example 5
Project: hashsdn-controller   File: ShardProxyTransaction.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<Boolean> validate() {
    LOG.debug("Validating transaction for shard {}", shardRoot);

    checkTransactionReadied();
    final List<ListenableFuture<Boolean>> futures =
            cohorts.stream().map(DOMStoreThreePhaseCommitCohort::canCommit).collect(Collectors.toList());
    final SettableFuture<Boolean> ret = SettableFuture.create();

    Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<Boolean>>() {
        @Override
        public void onSuccess(final List<Boolean> result) {
            ret.set(true);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            ret.setException(throwable);
        }
    }, MoreExecutors.directExecutor());

    return ret;
}
 
Example 6
Project: hashsdn-controller   File: RemoteSchemaProvider.java   Source Code and License 6 votes vote down vote up
@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(SourceIdentifier sourceIdentifier) {
    LOG.trace("Getting yang schema source for {}", sourceIdentifier.getName());

    Future<YangTextSchemaSourceSerializationProxy> result = remoteRepo.getYangTextSchemaSource(sourceIdentifier);

    final SettableFuture<YangTextSchemaSource> res = SettableFuture.create();
    result.onComplete(new OnComplete<YangTextSchemaSourceSerializationProxy>() {
        @Override
        public void onComplete(Throwable throwable,
                YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) {
            if (yangTextSchemaSourceSerializationProxy != null) {
                res.set(yangTextSchemaSourceSerializationProxy.getRepresentation());
            }
            if (throwable != null) {
                res.setException(throwable);
            }
        }

    }, executionContext);

    return Futures.makeChecked(res, MAPPER);
}
 
Example 7
Project: amazon-gamelift-serversdk-java   File: AuxProxyMessageSender.java   Source Code and License 6 votes vote down vote up
private Ack createAckFunction(final SettableFuture<GenericOutcome> future) {
    return new Ack() {
        @Override
        public void call(Object... objects) {
            if (objects.length == 0 || objects[0] == null) {
                future.set(new GenericOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }

            boolean value = (boolean) objects[0];

            if (value) {
                future.set(new GenericOutcome());
            } else {
                future.set(new GenericOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }
        }
    };
}
 
Example 8
Project: Elasticsearch   File: ESDeleteTask.java   Source Code and License 6 votes vote down vote up
public ESDeleteTask(UUID jobId,
                    ESDeleteNode node,
                    TransportDeleteAction transport,
                    JobContextService jobContextService) {
    super(jobId, node.executionPhaseId(), node.docKeys().size(), jobContextService);
    List<DeleteRequest> requests = new ArrayList<>(node.docKeys().size());
    List<ActionListener> listeners = new ArrayList<>(node.docKeys().size());
    for (DocKeys.DocKey docKey : node.docKeys()) {
        DeleteRequest request = new DeleteRequest(
                ESGetTask.indexName(node.tableInfo(), docKey.partitionValues()),
                Constants.DEFAULT_MAPPING_TYPE, docKey.id());
        request.routing(docKey.routing());
        if (docKey.version().isPresent()) {
            request.version(docKey.version().get());
        }
        requests.add(request);
        SettableFuture<TaskResult> result = SettableFuture.create();
        results.add(result);
        listeners.add(new DeleteResponseListener(result));
    }

    createContext("delete", requests, listeners, transport, null);
}
 
Example 9
Project: creacoinj   File: PaymentChannelClient.java   Source Code and License 6 votes vote down vote up
private void receivePaymentAck(Protos.PaymentAck paymentAck) {
    SettableFuture<PaymentIncrementAck> future;
    Coin value;

    lock.lock();
    try {
        if (increasePaymentFuture == null) return;
        checkNotNull(increasePaymentFuture, "Server sent a PAYMENT_ACK with no outstanding payment");
        log.info("Received a PAYMENT_ACK from the server");
        future = increasePaymentFuture;
        value = lastPaymentActualAmount;
    } finally {
        lock.unlock();
    }

    // Ensure the future runs without the client lock held.
    future.set(new PaymentIncrementAck(value, paymentAck.getInfo()));
}
 
Example 10
Project: Elasticsearch   File: ESClusterUpdateSettingsTask.java   Source Code and License 6 votes vote down vote up
public ESClusterUpdateSettingsTask(UUID jobId,
                                   TransportClusterUpdateSettingsAction transport,
                                   ESClusterUpdateSettingsNode node) {
    super(jobId);
    this.transport = transport;

    final SettableFuture<TaskResult> result = SettableFuture.create();
    results = Collections.<ListenableFuture<TaskResult>>singletonList(result);

    request = new ClusterUpdateSettingsRequest();
    request.persistentSettings(node.persistentSettings());
    request.transientSettings(node.transientSettings());
    if (node.persistentSettingsToRemove() != null) {
        request.persistentSettingsToRemove(node.persistentSettingsToRemove());
    }
    if (node.transientSettingsToRemove() != null) {
        request.transientSettingsToRemove(node.transientSettingsToRemove());
    }
    listener = ActionListeners.wrap(result, Functions.constant(TaskResult.ONE_ROW));
}
 
Example 11
Project: creacoinj   File: Peer.java   Source Code and License 6 votes vote down vote up
/**
 * Sends a query to the remote peer asking for the unspent transaction outputs (UTXOs) for the given outpoints.
 * The result should be treated only as a hint: it's possible for the returned outputs to be fictional and not
 * exist in any transaction, and it's possible for them to be spent the moment after the query returns.
 * <b>Most peers do not support this request. You will need to connect to Bitcoin XT peers if you want
 * this to work.</b>
 *
 * @param includeMempool If true (the default) the results take into account the contents of the memory pool too.
 * @throws ProtocolException if this peer doesn't support the protocol.
 */
public ListenableFuture<UTXOsMessage> getUTXOs(List<TransactionOutPoint> outPoints, boolean includeMempool) {
    lock.lock();
    try {
        VersionMessage peerVer = getPeerVersionMessage();
        if (peerVer.clientVersion < GetUTXOsMessage.MIN_PROTOCOL_VERSION)
            throw new ProtocolException("Peer does not support getutxos protocol version");
        if ((peerVer.localServices & GetUTXOsMessage.SERVICE_FLAGS_REQUIRED) != GetUTXOsMessage.SERVICE_FLAGS_REQUIRED)
            throw new ProtocolException("Peer does not support getutxos protocol flag: find Bitcoin XT nodes.");
        SettableFuture<UTXOsMessage> future = SettableFuture.create();
        // Add to the list of in flight requests.
        if (getutxoFutures == null)
            getutxoFutures = new LinkedList<>();
        getutxoFutures.add(future);
        sendMessage(new GetUTXOsMessage(params, outPoints, includeMempool));
        return future;
    } finally {
        lock.unlock();
    }
}
 
Example 12
Project: hashsdn-controller   File: ClusterAdminRpcService.java   Source Code and License 6 votes vote down vote up
@Override
public Future<RpcResult<Void>> backupDatastore(final BackupDatastoreInput input) {
    LOG.debug("backupDatastore: {}", input);

    if (Strings.isNullOrEmpty(input.getFilePath())) {
        return newFailedRpcResultFuture("A valid file path must be specified");
    }

    final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
    ListenableFuture<List<DatastoreSnapshot>> future = sendMessageToShardManagers(GetSnapshot.INSTANCE);
    Futures.addCallback(future, new FutureCallback<List<DatastoreSnapshot>>() {
        @Override
        public void onSuccess(List<DatastoreSnapshot> snapshots) {
            saveSnapshotsToFile(new DatastoreSnapshotList(snapshots), input.getFilePath(), returnFuture);
        }

        @Override
        public void onFailure(Throwable failure) {
            onDatastoreBackupFailure(input.getFilePath(), returnFuture, failure);
        }
    }, MoreExecutors.directExecutor());

    return returnFuture;
}
 
Example 13
Project: twister2   File: SharedFileSystemStateManager.java   Source Code and License 6 votes vote down vote up
@Override
protected ListenableFuture<Boolean> deleteNode(String path, boolean deleteChildrenIfNecessary) {
  final SettableFuture<Boolean> future = SettableFuture.create();
  boolean ret = true;
  if (FileUtils.isFileExists(path)) {
    if (!deleteChildrenIfNecessary && FileUtils.hasChildren(path)) {
      LOG.severe("delete called on a path with children but deleteChildrenIfNecessary is false: "
          + path);
      ret = false;
    } else {
      ret = FileUtils.deleteFile(path);
    }
  }
  future.set(ret);

  return future;
}
 
Example 14
Project: azure-libraries-for-java   File: TestBatch.java   Source Code and License 6 votes vote down vote up
@Override
public BatchAccount createResource(BatchAccounts resources) throws Exception {
    final String batchAccountName = "batch" + this.testId;
    final BatchAccount[] batchAccounts = new BatchAccount[1];
    final SettableFuture<BatchAccount> future = SettableFuture.create();


    Observable<Indexable> resourceStream = resources.define(batchAccountName)
            .withRegion(Region.INDIA_CENTRAL)
            .withNewResourceGroup()
            .withTag("mytag", "testtag")
            .createAsync();

    Utils.<BatchAccount>rootResource(resourceStream)
            .subscribe(new Action1<BatchAccount>() {
                @Override
                public void call(BatchAccount batchAccount) {
                    future.set(batchAccount);
                }
            });

    batchAccounts[0] = future.get();
    Assert.assertNull(batchAccounts[0].autoStorage());

    return batchAccounts[0];
}
 
Example 15
Project: Elasticsearch   File: DDLStatementDispatcher.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<Long> visitRevokePrivilegeAnalyzedStatement(RevokePrivilegeAnalyzedStatement analysis, SingleJobTask jobId) {
    String tableName = analysis.getTable();
    boolean isDBPrivilege = true;
    if (tableName.contains(".")) {
        isDBPrivilege = false;
    }
    GrantOrRevokeUserPrivilegeRequest grantRequest = new GrantOrRevokeUserPrivilegeRequest(analysis.getUsername(),
            tableName, PrivilegeType.valueOf(analysis.getPrivilege().toUpperCase()),
            isDBPrivilege, false);
    grantRequest.putHeader(LoginUserContext.USER_INFO_KEY, analysis.getParameterContext().getLoginUserContext());
    final SettableFuture<Long> future = SettableFuture.create();
    ActionListener<GrantOrRevokeUserPrivilegeResponse> listener = ActionListeners.wrap(future, Functions.<Long>constant(ONE));
    transportActionProvider.transportGrantOrRevokeUserPrivilegeAction().execute(grantRequest, listener);
    return future;
}
 
Example 16
Project: Elasticsearch   File: TableCreator.java   Source Code and License 6 votes vote down vote up
private void setException(SettableFuture<Long> result, Throwable e, CreateTableAnalyzedStatement statement) {
    e = Exceptions.unwrap(e);
    String message = e.getMessage();
    // sometimes message is empty
    if ("mapping [default]".equals(message) && e.getCause() != null) {
        // this is a generic mapping parse exception,
        // the cause has usually a better more detailed error message
        result.setException(e.getCause());
    } else if (statement.ifNotExists() &&
               (e instanceof IndexAlreadyExistsException
                || (e instanceof IndexTemplateAlreadyExistsException && statement.templateName() != null))) {
        result.set(null);
    } else {
        result.setException(e);
    }
}
 
Example 17
Project: Elasticsearch   File: SnapshotRestoreDDLDispatcher.java   Source Code and License 6 votes vote down vote up
public ListenableFuture<Long> dispatch(final DropSnapshotAnalyzedStatement statement) {
    final SettableFuture<Long> future = SettableFuture.create();
    final String repositoryName = statement.repository();
    final String snapshotName = statement.snapshot();

    transportActionProvider.transportDeleteSnapshotAction().execute(
            new DeleteSnapshotRequest(repositoryName, snapshotName),
            new ActionListener<DeleteSnapshotResponse>() {
                @Override
                public void onResponse(DeleteSnapshotResponse response) {
                    if (!response.isAcknowledged()) {
                        LOGGER.info("delete snapshot '{}.{}' not acknowledged", repositoryName, snapshotName);
                    }
                    future.set(1L);
                }

                @Override
                public void onFailure(Throwable e) {
                    future.setException(e);
                }
            }
    );
    return future;

}
 
Example 18
Project: hadoop   File: TestQuorumJournalManagerUnit.java   Source Code and License 6 votes vote down vote up
@Test
public void testWriteEditsOneSlow() throws Exception {
  EditLogOutputStream stm = createLogSegment();
  writeOp(stm, 1);
  stm.setReadyToFlush();
  
  // Make the first two logs respond immediately
  futureReturns(null).when(spyLoggers.get(0)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  futureReturns(null).when(spyLoggers.get(1)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  
  // And the third log not respond
  SettableFuture<Void> slowLog = SettableFuture.create();
  Mockito.doReturn(slowLog).when(spyLoggers.get(2)).sendEdits(
      anyLong(), eq(1L), eq(1), Mockito.<byte[]>any());
  stm.flush();
  
  Mockito.verify(spyLoggers.get(0)).setCommittedTxId(1L);
}
 
Example 19
Project: Elasticsearch   File: AlterTableOperation.java   Source Code and License 6 votes vote down vote up
private void addColumnToTable(AddColumnAnalyzedStatement analysis, final SettableFuture<Long> result) {
    boolean updateTemplate = analysis.table().isPartitioned();
    List<ListenableFuture<Long>> results = new ArrayList<>(2);
    final Map<String, Object> mapping = analysis.analyzedTableElements().toMapping();

    if (updateTemplate) {
        results.add(updateTemplate(mapping, Settings.EMPTY, analysis.table().ident(), analysis));
    }

    String[] indexNames = getIndexNames(analysis.table(), null);
    if (indexNames.length > 0) {
        results.add(updateMapping(mapping, indexNames));
    }

    applyMultiFutureCallback(result, results);
}
 
Example 20
Project: hadoop   File: AbstractYarnScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized void moveAllApps(String sourceQueue, String destQueue)
    throws YarnException {
  // check if destination queue is a valid leaf queue
  try {
    getQueueInfo(destQueue, false, false);
  } catch (IOException e) {
    LOG.warn(e);
    throw new YarnException(e);
  }
  // check if source queue is a valid
  List<ApplicationAttemptId> apps = getAppsInQueue(sourceQueue);
  if (apps == null) {
    String errMsg = "The specified Queue: " + sourceQueue + " doesn't exist";
    LOG.warn(errMsg);
    throw new YarnException(errMsg);
  }
  // generate move events for each pending/running app
  for (ApplicationAttemptId app : apps) {
    SettableFuture<Object> future = SettableFuture.create();
    this.rmContext
        .getDispatcher()
        .getEventHandler()
        .handle(new RMAppMoveEvent(app.getApplicationId(), destQueue, future));
  }
}
 
Example 21
Project: bench   File: MetricsRepository.java   Source Code and License 5 votes vote down vote up
private void setExpectedActorFutures(final ActorKey actor, final MetricValuesMessage currentActorMetrics) {
    List<SettableFuture<MetricValuesMessage>> futures = expectedActors.remove(actor);
    if (futures != null) {
        for (SettableFuture<MetricValuesMessage> future : futures) {
            future.set(currentActorMetrics);
        }
    }
}
 
Example 22
Project: bench   File: MetricsRepository.java   Source Code and License 5 votes vote down vote up
private SettableFuture<MetricValuesMessage> registerExpectedActor(final ActorKey actor) {
    List<SettableFuture<MetricValuesMessage>> futures = expectedActors.get(actor);
    SettableFuture<MetricValuesMessage> future = SettableFuture.create();
    if (futures != null) {
        futures.add(future);
    } else {
        List<SettableFuture<MetricValuesMessage>> list = new ArrayList<>();
        list.add(future);
        expectedActors.put(actor, list);
    }
    return future;
}
 
Example 23
Project: bench   File: MetricsRepository.java   Source Code and License 5 votes vote down vote up
private Optional<Future<MetricValuesMessage>> immediateResult(final ActorKey actor) {
    MetricValuesMessage metricValues = actorValues.get(actor);
    if (metricValues == null) {
        return Optional.empty();
    }

    SettableFuture<MetricValuesMessage> future = SettableFuture.create();
    future.set(metricValues);
    return Optional.of(future);
}
 
Example 24
Project: TakinRPC   File: Leader.java   Source Code and License 5 votes vote down vote up
@Nonnull
@Override
public ListenableFuture<Boolean> commitOperation(@Nonnull RaftStateContext ctx, @Nonnull byte[] operation) throws RaftException {

    resetTimeout(ctx);
    long index = log.append(operation);
    SettableFuture<Boolean> f = SettableFuture.create();
    requests.put(index, f);
    return commit(ctx);

}
 
Example 25
Project: memory-graph   File: Elasticsearch5SearchIndex.java   Source Code and License 5 votes vote down vote up
private void addActionRequestBuilderForFlush(String elementId, UpdateRequestBuilder updateRequestBuilder) {
    Future future;
    try {
        future = updateRequestBuilder.execute();
    } catch (Exception ex) {
        LOGGER.debug("Could not execute update: %s", ex.getMessage());
        future = SettableFuture.create();
        ((SettableFuture) future).setException(ex);
    }
    getFlushObjectQueue().add(new FlushObject(elementId, updateRequestBuilder, future));
}
 
Example 26
Project: xrpc   File: Call.java   Source Code and License 5 votes vote down vote up
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;
  }
}
 
Example 27
Project: hashsdn-controller   File: RemoteProxyTransaction.java   Source Code and License 5 votes vote down vote up
private void completeExists(final SettableFuture<Boolean> future, final Response<?, ?> response) {
    LOG.debug("Exists request completed with {}", response);

    if (response instanceof ExistsTransactionSuccess) {
        future.set(((ExistsTransactionSuccess) response).getExists());
    } else {
        failFuture(future, response);
    }

    recordFinishedRequest(response);
}
 
Example 28
Project: talchain   File: Eth62.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized ListenableFuture<List<Block>> sendGetBlockBodies(List<BlockHeaderWrapper> headers) {
    if (peerState != IDLE) return null;

    peerState = BLOCK_RETRIEVING;
    sentHeaders.clear();
    sentHeaders.addAll(headers);

    if(logger.isTraceEnabled()) logger.trace(
            "Peer {}: send GetBlockBodies, hashes.count [{}]",
            channel.getPeerIdShort(),
            sentHeaders.size()
    );

    List<byte[]> hashes = new ArrayList<>(headers.size());
    for (BlockHeaderWrapper header : headers) {
        hashes.add(header.getHash());
    }

    GetBlockBodiesMessage msg = new GetBlockBodiesMessage(hashes);

    sendMessage(msg);
    lastReqSentTime = System.currentTimeMillis();

    futureBlocks = SettableFuture.create();
    return futureBlocks;
}
 
Example 29
Project: apollo-custom   File: ReleaseMessageScannerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testScanMessageAndNotifyMessageListener() throws Exception {
  SettableFuture<ReleaseMessage> someListenerFuture = SettableFuture.create();
  ReleaseMessageListener someListener = (message, channel) -> someListenerFuture.set(message);
  releaseMessageScanner.addMessageListener(someListener);

  String someMessage = "someMessage";
  long someId = 100;
  ReleaseMessage someReleaseMessage = assembleReleaseMessage(someId, someMessage);

  when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(0L)).thenReturn(
      Lists.newArrayList(someReleaseMessage));

  ReleaseMessage someListenerMessage =
      someListenerFuture.get(5000, TimeUnit.MILLISECONDS);

  assertEquals(someMessage, someListenerMessage.getMessage());
  assertEquals(someId, someListenerMessage.getId());

  SettableFuture<ReleaseMessage> anotherListenerFuture = SettableFuture.create();
  ReleaseMessageListener anotherListener = (message, channel) -> anotherListenerFuture.set(message);
  releaseMessageScanner.addMessageListener(anotherListener);

  String anotherMessage = "anotherMessage";
  long anotherId = someId + 1;
  ReleaseMessage anotherReleaseMessage = assembleReleaseMessage(anotherId, anotherMessage);

  when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(someId)).thenReturn(
      Lists.newArrayList(anotherReleaseMessage));

  ReleaseMessage anotherListenerMessage =
      anotherListenerFuture.get(5000, TimeUnit.MILLISECONDS);

  assertEquals(anotherMessage, anotherListenerMessage.getMessage());
  assertEquals(anotherId, anotherListenerMessage.getId());

}
 
Example 30
Project: guava-mock   File: GcFinalizationTest.java   Source Code and License 5 votes vote down vote up
public void testAwaitDone_Future_Cancel() {
  final SettableFuture<Void> future = SettableFuture.create();
  Object x = new Object() {
    @Override protected void finalize() { future.cancel(false); }
  };
  x = null;  // Hint to the JIT that x is unreachable
  GcFinalization.awaitDone(future);
  assertTrue(future.isDone());
  assertTrue(future.isCancelled());
}
 
Example 31
Project: guava-mock   File: GcFinalizationTest.java   Source Code and License 5 votes vote down vote up
public void testAwaitDone_Future_Interrupted_Interrupted() {
  Interruptenator interruptenator = new Interruptenator(Thread.currentThread());
  try {
    final SettableFuture<Void> future = SettableFuture.create();
    try {
      GcFinalization.awaitDone(future);
      fail("should throw");
    } catch (RuntimeException expected) {
      assertWrapsInterruptedException(expected);
    }
  } finally {
    interruptenator.shutdown();
    Thread.interrupted();
  }
}
 
Example 32
Project: ProjectAres   File: UserFinder.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 33
Project: CustomWorldGen   File: ResourcePackRepository.java   Source Code and License 5 votes vote down vote up
public ListenableFuture<Object> downloadResourcePack(String url, String hash)
{
    String s = DigestUtils.sha1Hex(url);
    final String s1 = SHA1.matcher(hash).matches() ? hash : "";
    final File file1 = new File(this.dirServerResourcepacks, s);
    this.lock.lock();

    try
    {
        this.clearResourcePack();

        if (file1.exists())
        {
            if (this.checkHash(s1, file1))
            {
                ListenableFuture listenablefuture1 = this.setResourcePackInstance(file1);
                return listenablefuture1;
            }

            LOGGER.warn("Deleting file {}", new Object[] {file1});
            FileUtils.deleteQuietly(file1);
        }

        this.deleteOldServerResourcesPacks();
        final GuiScreenWorking guiscreenworking = new GuiScreenWorking();
        Map<String, String> map = getDownloadHeaders();
        final Minecraft minecraft = Minecraft.getMinecraft();
        Futures.getUnchecked(minecraft.addScheduledTask(new Runnable()
        {
            public void run()
            {
                minecraft.displayGuiScreen(guiscreenworking);
            }
        }));
        final SettableFuture<Object> settablefuture = SettableFuture.<Object>create();
        this.downloadingPacks = HttpUtil.downloadResourcePack(file1, url, map, 52428800, guiscreenworking, minecraft.getProxy());
        Futures.addCallback(this.downloadingPacks, new FutureCallback<Object>()
        {
            public void onSuccess(@Nullable Object p_onSuccess_1_)
            {
                if (ResourcePackRepository.this.checkHash(s1, file1))
                {
                    ResourcePackRepository.this.setResourcePackInstance(file1);
                    settablefuture.set((Object)null);
                }
                else
                {
                    ResourcePackRepository.LOGGER.warn("Deleting file {}", new Object[] {file1});
                    FileUtils.deleteQuietly(file1);
                }
            }
            public void onFailure(Throwable p_onFailure_1_)
            {
                FileUtils.deleteQuietly(file1);
                settablefuture.setException(p_onFailure_1_);
            }
        });
        ListenableFuture listenablefuture = this.downloadingPacks;
        return listenablefuture;
    }
    finally
    {
        this.lock.unlock();
    }
}
 
Example 34
Project: wall-t   File: ApiController.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<Void> loadBuildTypeList( ) {
    if ( !getApiVersion( ).isSupported( ApiFeature.BUILD_TYPE_STATUS ) )
        return Futures.immediateFuture( null );

    final SettableFuture<Void> ackFuture = SettableFuture.create( );

    runInWorkerThread( ( ) -> {
        final ListenableFuture<BuildTypeList> buildListFuture = _apiRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class );
        addCallback( buildListFuture, new FutureCallback<BuildTypeList>( ) {
            @Override
            public void onSuccess( final BuildTypeList result ) {
                final List<BuildTypeData> buildTypes = result.getBuildTypes( ).stream( )
                        .map( ( btype ) -> _buildTypeProvider.get( getApiVersion( ) ).apply( btype ) )
                        .collect( Collectors.toList( ) );
                _buildManager.registerBuildTypes( buildTypes );
                _eventBus.post( _buildManager );

                for ( final BuildTypeData buildType : _buildManager.getBuildTypes( ) ) {
                    final Optional<ProjectData> project = _projectManager.getProject( buildType.getProjectId( ) );
                    if ( project.isPresent( ) ) {
                        project.get( ).registerBuildType( buildType );
                        _eventBus.post( project.get( ) );
                    }
                    LOGGER.info( "Discovering build type " + buildType.getId( ) + " (" + buildType.getName( ) + ") on project " + buildType.getProjectId( ) + " (" + buildType.getProjectName( ) + ")" );
                }

                ackFuture.set( null );
            }

            @Override
            public void onFailure( final Throwable t ) {
                LOGGER.error( "Error during loading build type list:", t );
                ackFuture.setException( t );
            }
        } );
    } );

    return ackFuture;
}
 
Example 35
Project: creacoinj   File: PaymentChannelClient.java   Source Code and License 5 votes vote down vote up
/**
 * Increments the total value which we pay the server. Note that the amount of money sent may not be the same as the
 * amount of money actually requested. It can be larger if the amount left over in the channel would be too small to
 * be accepted by the Bitcoin network. ValueOutOfRangeException will be thrown, however, if there's not enough money
 * left in the channel to make the payment at all. Only one payment can be in-flight at once. You have to ensure
 * you wait for the previous increase payment future to complete before incrementing the payment again.
 *
 * @param size How many satoshis to increment the payment by (note: not the new total).
 * @param info Information about this update, used to extend this protocol.
 * @param userKey Key derived from a user password, needed for any signing when the wallet is encrypted.
 *                The wallet KeyCrypter is assumed.
 * @return a future that completes when the server acknowledges receipt and acceptance of the payment.
 * @throws ValueOutOfRangeException If the size is negative or would pay more than this channel's total value
 *                                  ({@link PaymentChannelClientConnection#state()}.getTotalValue())
 * @throws IllegalStateException If the channel has been closed or is not yet open
 *                               (see {@link PaymentChannelClientConnection#getChannelOpenFuture()} for the second)
 * @throws ECKey.KeyIsEncryptedException If the keys are encrypted and no AES key has been provided,
 */
@Override
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey)
        throws ValueOutOfRangeException, IllegalStateException, ECKey.KeyIsEncryptedException {
    lock.lock();
    try {
        if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN)
            throw new IllegalStateException("Channel is not fully initialized/has already been closed");
        if (increasePaymentFuture != null)
            throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete.");
        if (wallet.isEncrypted() && userKey == null)
            throw new ECKey.KeyIsEncryptedException();

        PaymentChannelV1ClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey);
        Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder()
                .setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin()))
                .setClientChangeValue(state.getValueRefunded().getValue());
        if (info != null) updatePaymentBuilder.setInfo(info);

        increasePaymentFuture = SettableFuture.create();
        increasePaymentFuture.addListener(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                increasePaymentFuture = null;
                lock.unlock();
            }
        }, MoreExecutors.sameThreadExecutor());

        conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
                .setUpdatePayment(updatePaymentBuilder)
                .setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT)
                .build());
        lastPaymentActualAmount = payment.amount;
        return increasePaymentFuture;
    } finally {
        lock.unlock();
    }
}
 
Example 36
Project: Elasticsearch   File: UpsertByIdTask.java   Source Code and License 5 votes vote down vote up
private void executeUpsertRequest(final UpsertByIdNode.Item item, final SettableFuture<TaskResult> futureResult) {
    ShardId shardId;
    try {
        shardId = clusterService.operationRouting().indexShards(
                clusterService.state(),
                item.index(),
                Constants.DEFAULT_MAPPING_TYPE,
                item.id(),
                item.routing()
        ).shardId();
    } catch (IndexNotFoundException e) {
        if (PartitionName.isPartition(item.index())) {
            futureResult.set(TaskResult.ZERO);
            return;
        }
        throw e;
    }

    ShardUpsertRequest upsertRequest = new ShardUpsertRequest(
            shardId, node.updateColumns(), node.insertColumns(), item.routing(), jobId());
    upsertRequest.continueOnError(false);
    ShardUpsertRequest.Item requestItem = new ShardUpsertRequest.Item(
            item.id(), item.updateAssignments(), item.insertValues(), item.version());
    upsertRequest.add(0, requestItem);

    UpsertByIdContext upsertByIdContext = new UpsertByIdContext(
            node.executionPhaseId(), upsertRequest, item, futureResult, transportShardUpsertActionDelegate);
    createJobExecutionContext(upsertByIdContext);
    try {
        jobExecutionContext.start();
    } catch (Throwable throwable) {
        futureResult.setException(throwable);
    }
}
 
Example 37
Project: creacoinj   File: Peer.java   Source Code and License 5 votes vote down vote up
/** Sends a getdata with a single item in it. */
private ListenableFuture sendSingleGetData(GetDataMessage getdata) {
    // This does not need to be locked.
    Preconditions.checkArgument(getdata.getItems().size() == 1);
    GetDataRequest req = new GetDataRequest(getdata.getItems().get(0).hash, SettableFuture.create());
    getDataFutures.add(req);
    sendMessage(getdata);
    return req.future;
}
 
Example 38
Project: creacoinj   File: Peer.java   Source Code and License 5 votes vote down vote up
/** Sends a getaddr request to the peer and returns a future that completes with the answer once the peer has replied. */
public ListenableFuture<AddressMessage> getAddr() {
    SettableFuture<AddressMessage> future = SettableFuture.create();
    synchronized (getAddrFutures) {
        getAddrFutures.add(future);
    }
    sendMessage(new GetAddrMessage(params));
    return future;
}
 
Example 39
Project: hashsdn-controller   File: IdIntsListener.java   Source Code and License 5 votes vote down vote up
public Future<Void> tryFinishProcessing() {
    executorService = Executors.newSingleThreadScheduledExecutor();
    final SettableFuture<Void> settableFuture = SettableFuture.create();

    scheduledFuture = executorService.scheduleAtFixedRate(new CheckFinishedTask(settableFuture), 0, 1, TimeUnit.SECONDS);
    return settableFuture;
}
 
Example 40
Project: creacoinj   File: InboundMessageQueuer.java   Source Code and License 5 votes vote down vote up
@Override
protected void processMessage(Message m) throws Exception {
    if (m instanceof Ping) {
        SettableFuture<Void> future = mapPingFutures.get(((Ping) m).getNonce());
        if (future != null) {
            future.set(null);
            return;
        }
    }
    if (m instanceof BloomFilter) {
        lastReceivedFilter = (BloomFilter) m;
    }
    inboundMessages.offer(m);
}