net.javacrumbs.futureconverter.java8guava.FutureConverter Java Examples

The following examples show how to use net.javacrumbs.futureconverter.java8guava.FutureConverter. 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: DataLoaderModule.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Provides
DataLoaderRegistry dataLoaderRegistry(BookServiceGrpc.BookServiceFutureStub bookService) {

  // TODO: Use multibinder to modularize this, or automate this somehow
  BatchLoader<String, Book> bookBatchLoader =
      keys -> {
        ListenableFuture<List<Book>> listenableFuture =
            Futures.transform(
                bookService.listBooks(
                    ListBooksRequest.newBuilder()
                        .addAllIds(keys)
                        .setPageSize(keys.size())
                        .build()),
                resp -> resp.getBooksList(),
                MoreExecutors.directExecutor());
        return FutureConverter.toCompletableFuture(listenableFuture);
      };

  DataLoaderRegistry registry = new DataLoaderRegistry();
  registry.register("books", new DataLoader<>(bookBatchLoader));
  return registry;
}
 
Example #2
Source File: FuturesConverter.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Instrumentation apiFutureInstrumentation() {
  return new SimpleInstrumentation() {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
        DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
      return (DataFetcher<Object>)
          dataFetchingEnvironment -> {
            Object data = dataFetcher.get(dataFetchingEnvironment);
            if (data instanceof ApiFuture) {
              return FutureConverter.toCompletableFuture(
                  apiFutureToListenableFuture((ApiFuture<?>) data));
            }
            return data;
          };
    }
  };
}
 
Example #3
Source File: LibrarySchemaModule.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@SchemaModification(addField = "books", onType = Shelf.class)
ListenableFuture<List<Book>> shelfToBooks(Shelf shelf, DataFetchingEnvironment environment) {
  return FutureConverter.toListenableFuture(
      environment
          .<DataLoaderRegistry>getContext()
          .<String, Book>getDataLoader("books")
          .loadMany(shelf.getBookIdsList()));
}
 
Example #4
Source File: BookSchemaModule.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Query("getBook")
@RelayNode
ListenableFuture<Book> getBook(
    GetBookRequest request, DataFetchingEnvironment dataFetchingEnvironment) {
  return FutureConverter.toListenableFuture(
      dataFetchingEnvironment
          .<DataLoaderRegistry>getContext()
          .<String, Book>getDataLoader("books")
          .load(request.getId()));
}
 
Example #5
Source File: ExampleCassandraAsyncEndpoint.java    From riposte-microservice-template with Apache License 2.0 5 votes vote down vote up
@Override
public @NotNull CompletableFuture<ResponseInfo<String>> execute(
    @NotNull RequestInfo<Void> request,
    @NotNull Executor longRunningTaskExecutor,
    @NotNull ChannelHandlerContext ctx
) {
    Session session = EmbeddedCassandraUtils.cassandraSession(disableCassandra);
    if (session == null) {
        ApiError apiErrorToThrow = (disableCassandra)
                                   ? EXAMPLE_EMBEDDED_CASSANDRA_DISABLED
                                   : SampleCoreApiError.GENERIC_SERVICE_ERROR;

        throw ApiException.newBuilder()
                          .withApiErrors(apiErrorToThrow)
                          .withExceptionMessage("Unable to get cassandra session.")
                          .build();
    }

    ResultSetFuture cassandraResultFuture = session.executeAsync(basicCassandraQuery);

    // Convert the cassandra result future to a CompletableFuture, then add a listener that turns the result of the
    //      Cassandra call into the ResponseInfo<String> we need to return. Note that we're not doing
    //      thenApplyAsync() because the work done to translate the Cassandra result to our ResponseInfo object is
    //      trivial and doesn't need it's own thread. If you had more complex logic that was time consuming (or more
    //      blocking calls) you would want to do the extra work with CompletableFuture.*Async() calls.
    return FutureConverter
        .toCompletableFuture(cassandraResultFuture)
        .thenApply(functionWithTracingAndMdc(this::buildResponseFromCassandraQueryResult, ctx));
}
 
Example #6
Source File: InternalBot.java    From java-bot-sdk with Apache License 2.0 4 votes vote down vote up
public CompletableFuture<Void> start() {
    CompletableFuture<Metadata> meta = new CompletableFuture<>();

    RequestRegisterDevice request = RequestRegisterDevice.newBuilder()
            .setAppId(APP_ID)
            .setAppTitle(config.getName())
            .setDeviceTitle(config.getName())
            .build();

    return FutureConverter.toCompletableFuture(
            RegistrationGrpc.newFutureStub(channel).registerDevice(request)
    ).whenComplete((res, t) -> {
        if (res == null) {
            meta.completeExceptionally(t);
            return;
        }

        Metadata header = new Metadata();
        Metadata.Key<String> key = Metadata.Key.of("x-auth-ticket", Metadata.ASCII_STRING_MARSHALLER);
        header.put(key, res.getToken());

        meta.complete(header);
        metadata = header;
        log.info("Bot registered with token = {}", res.getToken());

    }).thenCompose(res -> meta).thenCompose(m -> {
        if (anonymousAuth) {
            return FutureConverter.toCompletableFuture(withToken(m,
                    AuthenticationGrpc.newFutureStub(channel),
                    stub -> stub.startAnonymousAuth(
                            RequestStartAnonymousAuth.newBuilder()
                                    .setApiKey("BotSdk")
                                    .setAppId(APP_ID)
                                    .setDeviceTitle(config.getName())
                                    .addPreferredLanguages("RU")
                                    .setTimeZone(StringValue.newBuilder().setValue("+3").build())
                                    .build()
                    )
            )).thenApply(res -> new ImmutablePair<>(res.getUser(), m));
        } else if (config.getCredentials() != null) {
            BotCredentials credentials = config.getCredentials();

            switch (credentials.getMethod()) {
                case TOKEN:
                    return FutureConverter.toCompletableFuture(withToken(m,
                            AuthenticationGrpc.newFutureStub(channel),
                            stub -> stub.startTokenAuth(
                                    RequestStartTokenAuth.newBuilder()
                                            .setApiKey("BotSdk")
                                            .setAppId(APP_ID)
                                            .setDeviceTitle(config.getName())
                                            .addPreferredLanguages("RU")
                                            .setTimeZone(StringValue.newBuilder().setValue("+3").build())
                                            .setToken(credentials.getValue())
                                            .build()
                            )
                    )).thenApply(res -> new ImmutablePair<>(res.getUser(), m));
                case PASSWORD:
                    return FutureConverter.toCompletableFuture(withToken(m,
                            AuthenticationGrpc.newFutureStub(channel),
                            stub -> stub.startUsernameAuth(
                                    RequestStartUsernameAuth.newBuilder()
                                            .setUsername(config.getName())
                                            .setApiKey("BotSdk")
                                            .setAppId(APP_ID)
                                            .setDeviceTitle(config.getName())
                                            .addPreferredLanguages("RU")
                                            .setTimeZone(StringValue.newBuilder().setValue("+3").build())
                                            .build()
                            )))
                            .thenCompose(res -> FutureConverter.toCompletableFuture(withToken(m,
                                    AuthenticationGrpc.newFutureStub(channel),
                                    stub -> stub.validatePassword(
                                            RequestValidatePassword.newBuilder()
                                                    .setTransactionHash(res.getTransactionHash())
                                                    .setPassword(credentials.getValue())
                                                    .build()
                                    ))))
                            .thenApply(res -> new ImmutablePair<>(res.getUser(), m));
                default:
                    return null;
            }
        } else {
            return null;
        }
    }).thenApply(p -> {
        withToken(p.getRight(),
                SequenceAndUpdatesGrpc.newStub(channel),
                stub -> {
                    stub.seqUpdates(Empty.newBuilder().build(), stream);
                    return null;
                }
        );

        log.info("Bot authorized with id = {}", p.getLeft().getId());
        return null;
    });
}
 
Example #7
Source File: InternalBot.java    From java-bot-sdk with Apache License 2.0 4 votes vote down vote up
public <T extends AbstractStub<T>, R> CompletableFuture<R> withToken(T stub, Function<T, ListenableFuture<R>> f) {
    T newStub = MetadataUtils.attachHeaders(stub, metadata);
    TaskManager<R> task = new TaskManager<>(FutureConverter.toCompletableFuture(f.apply(newStub)), config.getRetryOptions());
    return task.scheduleTask(0);
}
 
Example #8
Source File: CassandraAsyncExecutor.java    From james-project with Apache License 2.0 4 votes vote down vote up
public Mono<ResultSet> execute(Statement statement) {
    return Mono.defer(() -> Mono.fromFuture(FutureConverter
            .toCompletableFuture(session.executeAsync(statement)))
            .publishOn(Schedulers.elastic()));
}
 
Example #9
Source File: RpcChannelFactory.java    From barge with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<NettyRpcChannel> makeObject(Object key) throws Exception {
  Preconditions.checkArgument(key instanceof NettyReplica);
  NettyReplica replica = (NettyReplica) key;
  return FutureConverter.toCompletableFuture(client.connectAsync(replica.address()));
}