當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。