Java Code Examples for com.google.common.util.concurrent.SettableFuture#create()

The following examples show how to use com.google.common.util.concurrent.SettableFuture#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DaprClientGrpcTest.java    From java-sdk with MIT License 6 votes vote down vote up
@Test
public void invokeServiceNoRequestNoClassBodyObjectTest() throws Exception {
  MyObject resultObj = new MyObject(1, "Value");
  SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();

  MockCallback<CommonProtos.InvokeResponse> callback =
      new MockCallback<CommonProtos.InvokeResponse>(CommonProtos.InvokeResponse.newBuilder()
          .setData(getAny(resultObj)).build());
  addCallback(settableFuture, callback, directExecutor());
  settableFuture.set(CommonProtos.InvokeResponse.newBuilder().setData(getAny(resultObj)).build());
  when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
      .thenReturn(settableFuture);
  Mono<Void> result = adapter.invokeService(Verb.GET, "appId", "method", null);
  result.block();
  assertTrue(callback.wasCalled);
}
 
Example 2
Source File: TestMultiMaster.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Return the result of the first future to complete
 *
 * @param futures
 * @return
 */
private static <T> ListenableFuture<T> any(Iterable<ListenableFuture<T>> futures) {
  final SettableFuture<T> promise = SettableFuture.create();
  for(final ListenableFuture<T> future: futures) {
    Futures.addCallback(future, new FutureCallback<T>() {
      @Override
      public void onSuccess(T result) {
        promise.set(result);
      }

      @Override
      public void onFailure(Throwable t) {
        promise.setException(t);
      }
    }, MoreExecutors.directExecutor());
  }
  return promise;
}
 
Example 3
Source File: MockSplitSource.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<SplitBatch> getNextBatch(ConnectorPartitionHandle partitionHandle, Lifespan lifespan, int maxSize)
{
    if (partitionHandle != NOT_PARTITIONED) {
        throw new UnsupportedOperationException();
    }
    checkArgument(Lifespan.taskWide().equals(lifespan));

    checkState(nextBatchFuture.isDone(), "concurrent getNextBatch invocation");
    nextBatchFuture = SettableFuture.create();
    nextBatchMaxSize = maxSize;
    nextBatchInvocationCount++;
    doGetNextBatch();

    return Futures.transform(nextBatchFuture, splits -> new SplitBatch(splits, isFinished()), directExecutor());
}
 
Example 4
Source File: DDLStatementDispatcher.java    From Elasticsearch with Apache License 2.0 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 5
Source File: InstructionImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
synchronized ListenableFuture<ExecutionResult<Details>> ready() {
    Preconditions.checkState(this.status == InstructionStatus.Queued);
    Preconditions.checkState(this.executionFuture == null);
    /*
     * Check all vertices we depend on. We start off as ready for
     * scheduling. If we encounter a cancelled/failed/unknown
     * dependency, we cancel this instruction (and cascade). If we
     * encounter an executing/queued/scheduled dependency, we hold
     * of scheduling this one.
     */
    if (!checkDependencies()) {
        return null;
    }
    LOG.debug("Instruction {} is ready for execution", this.id);
    setStatus(InstructionStatus.Scheduled, null);
    this.executionFuture = SettableFuture.create();
    this.schedulingFuture.set(this);
    return this.executionFuture;
}
 
Example 6
Source File: BeaconService.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<NodeInfoReply> getNodeInfo(long nodeId, ModuleType module) {
  SettableFuture<NodeInfoReply> future = SettableFuture.create();
  fiber.execute(() -> {
    NodeInfo peer = peerNodeInfoMap.get(nodeId);
    if (peer == null) {
      future.set(NodeInfoReply.NO_REPLY);
    } else {
      Integer servicePort = peer.modules.get(module);
      if (servicePort == null) {
        future.set(NodeInfoReply.NO_REPLY);
      } else {
        List<String> peerAddresses = peer.availability.getAddressesList();
        future.set(new NodeInfoReply(true, peerAddresses, servicePort));
      }
    }
  });
  return future;
}
 
Example 7
Source File: TestStateMachine.java    From presto with Apache License 2.0 6 votes vote down vote up
private static SettableFuture<State> addTestListener(StateMachine<State> stateMachine)
{
    State initialState = stateMachine.get();
    SettableFuture<Boolean> initialStateNotified = SettableFuture.create();
    SettableFuture<State> stateChanged = SettableFuture.create();
    Thread addingThread = Thread.currentThread();
    stateMachine.addStateChangeListener(newState -> {
        Thread callbackThread = Thread.currentThread();
        if (callbackThread == addingThread) {
            stateChanged.setException(new AssertionError("Listener was not called back on a different thread"));
            return;
        }

        if (newState == initialState) {
            initialStateNotified.set(true);
        }
        else {
            stateChanged.set(newState);
        }
    });

    assertTrue(tryGetFutureValue(initialStateNotified, 10, SECONDS).isPresent(), "Initial state notification not fired");

    return stateChanged;
}
 
Example 8
Source File: DaprClientGrpcTest.java    From java-sdk with MIT License 6 votes vote down vote up
@Test
public void saveStateTestNoHotMono() {
  String key = "key1";
  String etag = "ETag1";
  String value = "State value";
  SettableFuture<Empty> settableFuture = SettableFuture.create();
  MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
  addCallback(settableFuture, callback, directExecutor());
  when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenAnswer(c -> {
    settableFuture.set(Empty.newBuilder().build());
    return settableFuture;
  });
  StateOptions options = buildStateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.FIRST_WRITE,
    Duration.ofDays(100), 1, StateOptions.RetryPolicy.Pattern.LINEAR);
  Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
  // No call to result.block(), so nothing should happen.
  assertFalse(callback.wasCalled);
}
 
Example 9
Source File: AbstractConfiguredObject.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
protected ListenableFuture<Void> deleteNoChecks()
{
    final String simpleClassName = AbstractConfiguredObject.this.getClass().getSimpleName();
    final SettableFuture<Void> returnFuture = SettableFuture.create();
    final State currentDesiredState = getDesiredState();

    final ChainedListenableFuture<Void> future =
            doAfter(beforeDelete(), this::deleteChildren).then(this::onDelete)
                                                         .then(() -> {
                                                             final State currentState = getState();
                                                             setState(State.DELETED);
                                                             notifyStateChanged(currentState, State.DELETED);
                                                             changeAttribute(ConfiguredObject.DESIRED_STATE, State.DELETED);
                                                             attributeSet(ConfiguredObject.DESIRED_STATE, currentDesiredState, State.DELETED);
                                                             unregister(true);

                                                             LOGGER.debug("Delete {} : {}",
                                                                          simpleClassName,
                                                                          getName());
                                                             return Futures.immediateFuture(null);
                                                                   });
    addFutureCallback(future, new FutureCallback<Void>()
    {
        @Override
        public void onSuccess(final Void result)
        {
            returnFuture.set(null);
        }

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

    return returnFuture;
}
 
Example 10
Source File: CascadingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeadlinePropagation() throws Exception {
  final AtomicInteger recursionDepthRemaining = new AtomicInteger(3);
  final SettableFuture<Deadline> finalDeadline = SettableFuture.create();
  class DeadlineSaver extends TestServiceGrpc.TestServiceImplBase {
    @Override
    public void unaryCall(final SimpleRequest request,
        final StreamObserver<SimpleResponse> responseObserver) {
      Context.currentContextExecutor(otherWork).execute(new Runnable() {
        @Override
        public void run() {
          try {
            if (recursionDepthRemaining.decrementAndGet() == 0) {
              finalDeadline.set(Context.current().getDeadline());
              responseObserver.onNext(SimpleResponse.getDefaultInstance());
            } else {
              responseObserver.onNext(blockingStub.unaryCall(request));
            }
            responseObserver.onCompleted();
          } catch (Exception ex) {
            responseObserver.onError(ex);
          }
        }
      });
    }
  }

  server = InProcessServerBuilder.forName("channel").executor(otherWork)
      .addService(new DeadlineSaver())
      .build().start();

  Deadline initialDeadline = Deadline.after(1, TimeUnit.MINUTES);
  blockingStub.withDeadline(initialDeadline).unaryCall(SimpleRequest.getDefaultInstance());
  assertNotSame(initialDeadline, finalDeadline);
  // Since deadline is re-calculated at each hop, some variance is acceptable and expected.
  assertAbout(deadline())
      .that(finalDeadline.get()).isWithin(1, TimeUnit.SECONDS).of(initialDeadline);
}
 
Example 11
Source File: MemoryPerUserWaveViewHandlerImpl.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> onWaveInit(WaveletName waveletName) {
  // No op.
  SettableFuture<Void> task = SettableFuture.create();
  task.set(null);
  return task;
}
 
Example 12
Source File: RemoteSpawnRunnerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testHumanReadableServerLogsSavedForFailingActionWithStatus() throws Exception {
  RemoteSpawnRunner runner = newSpawnRunner();
  Digest logDigest = digestUtil.computeAsUtf8("bla");
  Path logPath = logDir.getRelative(simpleActionId).getRelative("logname");
  com.google.rpc.Status timeoutStatus =
      com.google.rpc.Status.newBuilder().setCode(Code.DEADLINE_EXCEEDED.getNumber()).build();
  ExecuteResponse resp =
      ExecuteResponse.newBuilder()
          .putServerLogs(
              "logname", LogFile.newBuilder().setHumanReadable(true).setDigest(logDigest).build())
          .setStatus(timeoutStatus)
          .build();
  when(executor.executeRemotely(any(ExecuteRequest.class)))
      .thenThrow(new IOException(new ExecutionStatusException(resp.getStatus(), resp)));
  SettableFuture<Void> completed = SettableFuture.create();
  completed.set(null);
  when(cache.downloadFile(eq(logPath), eq(logDigest))).thenReturn(completed);

  Spawn spawn = newSimpleSpawn();
  SpawnExecutionContext policy = getSpawnContext(spawn);

  SpawnResult res = runner.exec(spawn, policy);
  assertThat(res.status()).isEqualTo(Status.TIMEOUT);

  verify(executor).executeRemotely(any(ExecuteRequest.class));
  verify(cache).downloadFile(eq(logPath), eq(logDigest));
}
 
Example 13
Source File: LinkImpl.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<LinkEndpoint<S, T>> doStealLink(final Session_1_0 session, final Attach attach)
{
    final SettableFuture<LinkEndpoint<S, T>> returnFuture = SettableFuture.create();
    final LinkEndpoint<S, T> linkEndpoint = _linkEndpoint;

    // check whether linkEndpoint has been closed in the mean time
    if (linkEndpoint != null)
    {
        linkEndpoint.getSession().doOnIOThreadAsync(
                () ->
                {
                    // check whether linkEndpoint has been closed in the mean time
                    LinkEndpoint<S, T> endpoint = _linkEndpoint;
                    if (endpoint != null)
                    {
                        endpoint.close(new Error(LinkError.STOLEN,
                                                      String.format("Link is being stolen by connection '%s'",
                                                                    session.getConnection())));
                    }
                    doLinkStealAndHandleExceptions(session, attach, returnFuture);
                });
    }
    else
    {
        doLinkStealAndHandleExceptions(session, attach, returnFuture);
    }

    return returnFuture;
}
 
Example 14
Source File: BillingTestCase.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private static ListenableFuture<Account> createAccountFuture(Account account) {
   SettableFuture<Account> future = SettableFuture.create();
   future.set(account.copy());
   return future;
}
 
Example 15
Source File: MobileServiceJsonTable.java    From azure-mobile-apps-android-client with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves a set of rows using the Next Link Url (Continuation Token)
 *
 * @param nextLink The Next Link to make the request
 */
public ListenableFuture<JsonElement> execute(final String nextLink) {
    final SettableFuture<JsonElement> future = SettableFuture.create();

    return executeUrlQuery(nextLink, mFeatures.clone());
}
 
Example 16
Source File: TFutureImpl.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public TFutureImpl(Operation operation) {
  this.future = SettableFuture.create();
  this.operation = operation;
}
 
Example 17
Source File: DownloadFileControllerTest.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
    WebSocketClient client = null;
    final SettableFuture<Integer> future = SettableFuture.create();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        client = new WebSocketClient(new URI("ws://100.80.128.181:9881/ws")) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                System.out.println("web socket open");
                //System.out.println(this);
                this.send("{\"0\":\"Hk/Ue+DxkKe8FhLktTbfIwh6m9gjC0NJieyZCW8Zleau/37qmrfkinjX4zpEEcklb1p8JpoliDbDuTegvjdUjdcIhaRu/2qWeh+ebG/ufmi+fCqzSYbxl3hdrdkNekR5Akc+YtqbPhBUj5qdnPsrk6l4Qfh4H0BiaddpOxbHv6Y=\",\"1\":\"HX9LpFWgrTUt7yBqS6+Gjc4ftPHi1+kj/W+XqTq0vdCp1SmKGGLTdHFzMLgeJyiaJl2bCyCoDeSsfvpWEWxi8Nk/sUCkaaid164zR80mAc+uvg55Cc/KkdHsMF2UJwIPHJghucJgUg+MqYt04j8na+n7ZWEYxFuz6jZhVQOspZueZvkvyEH2Cb5EoU5yt2gcOWciX+K7T/iG1j0z5Oc5ovaejuBurwwL/ompvD0vI4plPdTXqqfuQAPy3pQ6pwhq53cGBVk56U0=\"}");

                future.set(0);
            }

            @Override
            public void onMessage(String message) {
                //proxy netty返回的是二进制数据,不走这个逻辑
            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                handleResult(bytes, latch);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("close");
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
                future.setException(ex);
            }
        };
        client.connect();
        while (!client.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("正在连接");
        }

        latch.await();
    } catch (Exception e) {

    } finally {
        if (client != null) {
            client.close();
        }
    }
}
 
Example 18
Source File: GetTransactionRequest.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public SettableFuture<Coin> request(String transactionId, BlockchainTxProvider provider) {
    final SettableFuture<Coin> resultFuture = SettableFuture.create();
    return request(transactionId, provider, resultFuture);
}
 
Example 19
Source File: ListingConnectorTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testIncrementalChangesBatches() throws Exception {
  setDefaultConfig();
  PushItem pushItem = new PushItem();
  ApiOperation pushOperation = new PushItems.Builder().addPushItem("pushedId", pushItem).build();
  ApiOperation deleteOperation = ApiOperations.deleteItem("deletedItem");
  Collection<ApiOperation> operations = Arrays.asList(pushOperation, deleteOperation);
  TestCloseableIterable delegate1 = new TestCloseableIterable(operations);
  TestCloseableIterable delegate2 = new TestCloseableIterable(Collections.emptyList());
  byte[] batchCheckpoint = "someCheckpoint".getBytes();
  when(mockCheckpointHandler.readCheckpoint(ListingConnector.CHECKPOINT_INCREMENTAL))
      .thenReturn(null, batchCheckpoint);
  CheckpointCloseableIterable<ApiOperation> testIterable1 =
      new CheckpointCloseableIterableImpl.Builder<>(delegate1)
          .setCheckpoint(batchCheckpoint)
          .setHasMore(true)
          .build();
  when(mockRepository.getChanges(null)).thenReturn(testIterable1);
  CheckpointCloseableIterable<ApiOperation> testIterable2 =
      new CheckpointCloseableIterableImpl.Builder<>(delegate2).build();
  when(mockRepository.getChanges(batchCheckpoint)).thenReturn(testIterable2);
  ListingConnector connector = new ListingConnector(mockRepository, mockCheckpointHandler);
  connector.init(mockConnectorContext);
  SettableFuture<Operation> deleteFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            deleteFuture.set(new Operation());
            return deleteFuture;
          })
      .when(mockIndexingService)
      .deleteItem("deletedItem", null, RequestMode.UNSPECIFIED);
  SettableFuture<Item> pushFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            pushFuture.set(new Item());
            return pushFuture;
          })
      .when(mockIndexingService)
      .push(eq("pushedId"), eq(pushItem));
  connector.handleIncrementalChanges();
  InOrder inOrder = Mockito.inOrder(mockIndexingService, mockCheckpointHandler);
  inOrder.verify(mockCheckpointHandler).readCheckpoint(ListingConnector.CHECKPOINT_INCREMENTAL);
  inOrder.verify(mockIndexingService).push("pushedId", pushItem);
  inOrder.verify(mockIndexingService).deleteItem("deletedItem", null, RequestMode.UNSPECIFIED);
  inOrder
      .verify(mockCheckpointHandler)
      .saveCheckpoint(ListingConnector.CHECKPOINT_INCREMENTAL, batchCheckpoint);
  inOrder
      .verify(mockCheckpointHandler)
      .saveCheckpoint(ListingConnector.CHECKPOINT_INCREMENTAL, null);
  assertTrue(delegate1.isClosed());
  assertTrue(delegate2.isClosed());
}
 
Example 20
Source File: PendingRequests.java    From kurento-java with Apache License 2.0 3 votes vote down vote up
public ListenableFuture<Response<JsonElement>> prepareResponse(Integer id) {

    Preconditions.checkNotNull(id, "The request id cannot be null");

    SettableFuture<Response<JsonElement>> responseFuture = SettableFuture.create();

    if (pendingRequests.putIfAbsent(id, responseFuture) != null) {
      throw new JsonRpcException("Can not send a request with the id '" + id
          + "'. There is already a pending request with this id");
    }

    return responseFuture;
  }