当前位置: 首页>>代码示例>>Java>>正文


Java CompletableFuture.thenApply方法代码示例

本文整理汇总了Java中java.util.concurrent.CompletableFuture.thenApply方法的典型用法代码示例。如果您正苦于以下问题:Java CompletableFuture.thenApply方法的具体用法?Java CompletableFuture.thenApply怎么用?Java CompletableFuture.thenApply使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.CompletableFuture的用法示例。


在下文中一共展示了CompletableFuture.thenApply方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: multiResponseAsync

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
CompletableFuture<U> multiResponseAsync() {
    CompletableFuture<Void> start = new MinimalFuture<>();
    CompletableFuture<HttpResponseImpl<T>> cf = responseAsync0(start);
    CompletableFuture<HttpResponse<T>> mainResponse =
            cf.thenApply((HttpResponseImpl<T> b) -> {
                  multiResponseHandler.onResponse(b);
                  return (HttpResponse<T>)b;
               });

    pushGroup.setMainResponse(mainResponse);
    // set up house-keeping related to multi-response
    mainResponse.thenAccept((r) -> {
        // All push promises received by now.
        pushGroup.noMorePushes(true);
    });
    CompletableFuture<U> res = multiResponseHandler.completion(pushGroup.groupResult(), pushGroup.pushesCF());
    start.completeAsync( () -> null, executor); // trigger execution
    return res;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:MultiExchange.java

示例2: sendRequestForData

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
 * Make a request to get the data of the authenticated user for the provider.
 *
 * @param accessToken the access token
 * @param dataUrl     url of the data
 * @param verb        method used to request data
 * @return the user data response
 */
protected CompletableFuture<String> sendRequestForData(final T accessToken, final String dataUrl, Verb verb) {
    logger.debug("accessToken: {} / dataUrl: {}", accessToken, dataUrl);
    final long t0 = System.currentTimeMillis();
    final OAuthRequestAsync request = createOAuthRequest(dataUrl, verb);
    signRequest(accessToken, request);
    final CompletableFuture<Response> responseFuture = new CompletableFuture<>();
    request.sendAsync(ScribeCallbackAdapter.toScribeOAuthRequestCallback(responseFuture));
    return responseFuture.thenApply(response -> {
        final int code = response.getCode();
        final String body;
        try {
            body = response.getBody();
        } catch (final IOException ex) {
            throw new HttpCommunicationException("Error getting body: " + ex.getMessage());
        }
        final long t1 = System.currentTimeMillis();
        logger.debug("Request took: " + (t1 - t0) + " ms for: " + dataUrl);
        logger.debug("response code: {} / response body: {}", code, body);
        if (code != 200) {
            throw new HttpCommunicationException(code, body);
        }
        return body;
    });
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:33,代码来源:AsyncOAuthProfileCreator.java

示例3: sequence

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private <T> CompletionStage<List<T>> sequence(final List<CompletionStage<T>> stages) {
    //noinspection SuspiciousToArrayCall
    final CompletableFuture<Void> done = CompletableFuture.allOf(stages.toArray(new CompletableFuture[stages.size()]));
    
    return done.thenApply(v -> stages.stream()
        .map(CompletionStage::toCompletableFuture)
        .map(CompletableFuture::join)
        .collect(Collectors.<T>toList())
    );
}
 
开发者ID:hantsy,项目名称:javaee8-jaxrs-sample,代码行数:11,代码来源:AggregateResource.java

示例4: mapPromiseN

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String mapPromiseN() throws InterruptedException, ExecutionException {
  CompletableFuture<String> p = new CompletableFuture<String>();
  CompletableFuture<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.thenApply(mapF);
  p.complete(string);
  return f.get();
}
 
开发者ID:traneio,项目名称:future,代码行数:10,代码来源:JavaSyncFutureBenchmark.java

示例5: applyOnExecutor

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private <R, T> CompletableFuture<R> applyOnExecutor(CompletableFuture<T> eventLoopFuture, Function<T, R> mapper) {
  if (executor == SmtpSessionFactoryConfig.DIRECT_EXECUTOR) {
    return eventLoopFuture.thenApply(mapper);
  }

  // use handleAsync to ensure exceptions and other callbacks are completed on the ExecutorService thread
  return eventLoopFuture.handleAsync((rs, e) -> {
    if (e != null) {
      throw Throwables.propagate(e);
    }

    return mapper.apply(rs);
  }, executor);
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:15,代码来源:SmtpSession.java

示例6: getCompletions

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<List<CompletionItem>> getCompletions(CompletableFuture<CamelCatalog> camelCatalog, int positionInCamelUri) {
	if(getStartPosition() <= positionInCamelUri && positionInCamelUri <= getEndPosition()) {
		return camelCatalog.thenApply(new CamelComponentSchemaCompletionsFuture());
	} else {
		return CompletableFuture.completedFuture(Collections.emptyList());
	}
}
 
开发者ID:lhein,项目名称:camel-language-server,代码行数:9,代码来源:PathParamURIInstance.java

示例7: getDiff

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public <T> CompletableFuture<Change<T>> getDiff(String projectName, String repositoryName,
                                                Revision from, Revision to, Query<T> query) {
    final CompletableFuture<DiffFileResult> future =
            run(callback -> client.diffFile(projectName, repositoryName,
                                            RevisionConverter.TO_DATA.convert(from),
                                            RevisionConverter.TO_DATA.convert(to),
                                            QueryConverter.TO_DATA.convert(query), callback));
    return future.thenApply(r -> {
        if (r == null) {
            return null;
        }

        final Change<T> converted;
        switch (r.getType()) {
            case UPSERT_JSON:
                converted = unsafeCast(Change.ofJsonUpsert(query.path(), r.getContent()));
                break;
            case UPSERT_TEXT:
                converted = unsafeCast(Change.ofTextUpsert(query.path(), r.getContent()));
                break;
            case REMOVE:
                converted = unsafeCast(Change.ofRemoval(query.path()));
                break;
            case RENAME:
                converted = unsafeCast(Change.ofRename(query.path(), r.getContent()));
                break;
            case APPLY_JSON_PATCH:
                converted = unsafeCast(Change.ofJsonPatch(query.path(), r.getContent()));
                break;
            case APPLY_TEXT_PATCH:
                converted = unsafeCast(Change.ofTextPatch(query.path(), r.getContent()));
                break;
            default:
                throw new Error("unknown change type: " + r.getType());
        }

        return converted;
    });
}
 
开发者ID:line,项目名称:centraldogma,代码行数:41,代码来源:DefaultCentralDogma.java

示例8: getDiffs

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<List<Change<?>>> getDiffs(String projectName, String repositoryName,
                                                   Revision from, Revision to, String pathPattern) {
    CompletableFuture<List<com.linecorp.centraldogma.internal.thrift.Change>> future =
            run(callback -> client.getDiffs(projectName, repositoryName,
                                            RevisionConverter.TO_DATA.convert(from),
                                            RevisionConverter.TO_DATA.convert(to), pathPattern, callback));
    return future.thenApply(list -> convertToList(list, ChangeConverter.TO_MODEL::convert));
}
 
开发者ID:line,项目名称:centraldogma,代码行数:10,代码来源:DefaultCentralDogma.java

示例9: setValueN

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String setValueN() throws InterruptedException, ExecutionException {
  CompletableFuture<String> p = new CompletableFuture<>();
  CompletableFuture<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.thenApply(mapF);
  p.complete(string);
  return f.get();
}
 
开发者ID:traneio,项目名称:future,代码行数:10,代码来源:JavaSyncFutureBenchmark.java

示例10: mapPromise

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Benchmark
public String mapPromise() throws InterruptedException, ExecutionException {
  CompletableFuture<String> p = new CompletableFuture<String>();
  CompletableFuture<String> f = p.thenApply(mapF);
  p.complete(string);
  return f.get();
}
 
开发者ID:traneio,项目名称:future,代码行数:8,代码来源:JavaSyncFutureBenchmark.java

示例11: load

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
 * Requests to load the data with the specified key asynchronously, and returns a future of the resulting value.
 * <p>
 * If batching is enabled (the default), you'll have to call {@link DataLoader#dispatch()} at a later stage to
 * start batch execution. If you forget this call the future will never be completed (unless already completed,
 * and returned from cache).
 *
 * @param key the key to load
 *
 * @return the future of the value
 */
public CompletableFuture<V> load(K key) {
    Object cacheKey = getCacheKey(nonNull(key));
    synchronized (futureCache) {
        if (loaderOptions.cachingEnabled() && futureCache.containsKey(cacheKey)) {
            return futureCache.get(cacheKey);
        }
    }

    CompletableFuture<V> future = new CompletableFuture<>();
    if (loaderOptions.batchingEnabled()) {
        synchronized (loaderQueue) {
            loaderQueue.put(key, future);
        }
    } else {
        // immediate execution of batch function
        CompletableFuture<List<V>> batchedLoad = batchLoadFunction
                .load(singletonList(key))
                .toCompletableFuture();
        future = batchedLoad
                .thenApply(list -> list.get(0));
    }
    if (loaderOptions.cachingEnabled()) {
        synchronized (futureCache) {
            futureCache.set(cacheKey, future);
        }
    }
    return future;
}
 
开发者ID:bbakerman,项目名称:java-dataloader,代码行数:40,代码来源:DataLoader.java

示例12: sendRequest

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private CompletableFuture<RaftClientReply> sendRequest(
    RaftClientRequest request, RaftClientProtocolClient proxy) throws IOException {
  final RaftClientRequestProto requestProto =
      toRaftClientRequestProto(request);
  final CompletableFuture<RaftClientReplyProto> replyFuture =
      new CompletableFuture<>();
  // create a new grpc stream for each non-async call.
  final StreamObserver<RaftClientRequestProto> requestObserver =
      proxy.append(new StreamObserver<RaftClientReplyProto>() {
        @Override
        public void onNext(RaftClientReplyProto value) {
          replyFuture.complete(value);
        }

        @Override
        public void onError(Throwable t) {
          replyFuture.completeExceptionally(RaftGrpcUtil.unwrapIOException(t));
        }

        @Override
        public void onCompleted() {
          if (!replyFuture.isDone()) {
            replyFuture.completeExceptionally(
                new IOException(clientId + ": Stream completed but no reply for request " + request));
          }
        }
      });
  requestObserver.onNext(requestProto);
  requestObserver.onCompleted();

  return replyFuture.thenApply(replyProto -> toRaftClientReply(replyProto));
}
 
开发者ID:apache,项目名称:incubator-ratis,代码行数:33,代码来源:GrpcClientRpc.java

示例13: getCompletions

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<List<CompletionItem>> getCompletions(CompletableFuture<CamelCatalog> camelCatalog, int positionInCamelUri) {
	return camelCatalog.thenApply(new CamelOptionValuesCompletionsFuture(this));
}
 
开发者ID:lhein,项目名称:camel-language-server,代码行数:5,代码来源:OptionParamValueURIInstance.java

示例14: provideOrderGateway

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Provides
public CompletableFuture<GdaxOrderGateway> provideOrderGateway(GdaxExchangeSession session,
                                                               CompletableFuture<GdaxOrderManager> omFuture) {
    return omFuture.thenApply(om -> new GdaxOrderGateway(session, om));
}
 
开发者ID:cloudwall,项目名称:libcwfincore,代码行数:6,代码来源:ExchangeServiceModule.java

示例15: execute

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<OutputT> execute(CompletableFuture<InputT> inputFuture, RequestExecutionContext context)
        throws Exception {
    return inputFuture.thenApply(safeFunction(input -> delegate.execute(input, context)));
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:6,代码来源:RequestPipelineBuilder.java


注:本文中的java.util.concurrent.CompletableFuture.thenApply方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。