Java Code Examples for java.util.concurrent.CompletableFuture.completedFuture()

The following are Jave code examples for showing how to use completedFuture() of the java.util.concurrent.CompletableFuture class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: commercetools-sync-java   File: ProductServiceImpl.java   View Source Code Vote up 6 votes
@Nonnull
@Override
public CompletionStage<Map<String, String>> cacheKeysToIds() {
    if (isCached) {
        return CompletableFuture.completedFuture(keyToIdCache);
    }

    final Consumer<List<Product>> productPageConsumer = productsPage ->
        productsPage.forEach(product -> {
            final String key = product.getKey();
            final String id = product.getId();
            if (StringUtils.isNotBlank(key)) {
                keyToIdCache.put(key, id);
            } else {
                syncOptions.applyWarningCallback(format(PRODUCT_KEY_NOT_SET, id));
            }
        });

    return CtpQueryUtils.queryAll(syncOptions.getCtpClient(), ProductQuery.of(), productPageConsumer)
                        .thenAccept(result -> isCached = true)
                        .thenApply(result -> keyToIdCache);
}
 
Example 2
Project: commercetools-sync-java   File: BaseService.java   View Source Code Vote up 6 votes
/**
 * Applies the BeforeCreateCallback function on a supplied draft, then attempts to create it on CTP if it's not
 * empty, then applies the supplied handler on the response from CTP. If the draft was empty after applying the
 * callback an empty optional is returned as the resulting future.
 *
 * @param resourceDraft         draft to apply callback on and then create on CTP.
 * @param draftKey              draft key.
 * @param createCommandFunction the create command query to create the resource on CTP.
 * @return a future containing an optional which might contain the resource if successfully created or empty
 *         otherwise.
 */
@Nonnull
CompletionStage<Optional<U>> applyCallbackAndCreate(
    @Nonnull final V resourceDraft,
    @Nullable final String draftKey,
    @Nonnull final Function<V, DraftBasedCreateCommand<U, V>> createCommandFunction) {
    if (isBlank(draftKey)) {
        syncOptions.applyErrorCallback(format(CREATE_FAILED, draftKey, "Draft key is blank!"));
        return CompletableFuture.completedFuture(Optional.empty());
    } else {
        final BiFunction<U, Throwable, Optional<U>> responseHandler =
            (createdResource, sphereException) ->
                handleResourceCreation(draftKey, createdResource, sphereException);
        return syncOptions.applyBeforeCreateCallBack(resourceDraft)
                          .map(mappedDraft ->
                              syncOptions.getCtpClient()
                                         .execute(createCommandFunction.apply(mappedDraft))
                                         .handle(responseHandler)
                          )
                          .orElseGet(() -> CompletableFuture.completedFuture(Optional.empty()));
    }
}
 
Example 3
Project: device-telemetry-java   File: AlarmsByRuleController.java   View Source Code Vote up 6 votes
/**
 * Return a list of alarms grouped by the rule from which the alarm is
 * created. The list can be paginated, and filtered by device, period of
 * time, status. The list is sorted chronologically, by default starting
 * from the oldest alarm, and optionally from the most recent.
 * <p>
 * The list can also contain zero alarms and only a count of occurrences,
 * for instance to know how many alarms are generated for each rule.
 *
 * @return List of alarms.
 */
public CompletionStage<Result> listAsync(String from, String to, String order, int skip,
                                         int limit, String devices) throws Exception {
    // TODO: move this logic to the storage engine, depending on the
    // storage type the limit will be different. 200 is DocumentDb
    // limit for the IN clause.
    String[] deviceIds = new String[0];
    if (devices != null) {
        deviceIds = devices.split(",");
    }
    if (deviceIds.length > 200) {
        log.warn("The client requested too many devices: {}", deviceIds.length);
        return CompletableFuture.completedFuture(
            badRequest("The number of devices cannot exceed 200"));
    }

    return this.rulesService.getAlarmCountForList(
        DateHelper.parseDate(from),
        DateHelper.parseDate(to),
        order,
        skip,
        limit,
        deviceIds)
        .thenApply(alarmByRuleList -> ok(toJson(
            new AlarmByRuleListApiModel(alarmByRuleList))));
}
 
Example 4
Project: commercetools-sync-java   File: VariantReferenceResolver.java   View Source Code Vote up 6 votes
CompletionStage<AttributeDraft> resolveAttributeReference(@Nonnull final AttributeDraft attributeDraft) {
    final JsonNode attributeDraftValue = attributeDraft.getValue();
    if (attributeDraftValue == null) {
        return CompletableFuture.completedFuture(attributeDraft);
    }
    if (attributeDraftValue.isArray()) {
        return resolveAttributeSetReferences(attributeDraft);
    } else {
        if (isProductReference(attributeDraftValue)) {
            return getResolvedIdFromKeyInReference(attributeDraftValue)
                .thenApply(productIdOptional ->
                    productIdOptional.map(productId ->
                        AttributeDraft.of(attributeDraft.getName(), createProductReferenceJson(productId)))
                                     .orElse(attributeDraft));
        }
        return CompletableFuture.completedFuture(attributeDraft);
    }
}
 
Example 5
Project: pac4j-async   File: VertxAsyncProfileManager.java   View Source Code Vote up 5 votes
public CompletableFuture<Void> save(boolean saveInSession, CommonProfile profile, boolean multiProfile) {

        String clientName = this.retrieveClientName(profile);
        Pac4jUser vertxUser = Optional.ofNullable(this.vertxWebContext.getVertxUser()).orElse(new Pac4jUser());
        vertxUser.setUserProfile(clientName, profile, multiProfile);
        this.vertxWebContext.setVertxUser(vertxUser);
        return CompletableFuture.completedFuture(null);
    }
 
Example 6
Project: athena   File: CopycatTransportConnection.java   View Source Code Vote up 5 votes
@Override
public CompletableFuture<Void> close() {
    closeListeners.forEach(listener -> listener.accept(this));
    if (mode == CopycatTransport.Mode.CLIENT) {
        messagingService.unregisterHandler(inboundMessageSubject);
    }
    return CompletableFuture.completedFuture(null);
}
 
Example 7
Project: Spring-5.0-Cookbook   File: DepartmentServiceImpl.java   View Source Code Vote up 5 votes
@Override
public CompletableFuture<List<Department>> readDepartments() {
	try {
		System.out.println("readDepartments CompletableFuture login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Thread.sleep(5000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	return CompletableFuture.completedFuture(departmentDaoImpl.getDepartments());
}
 
Example 8
Project: camel-language-server   File: CamelURIInstance.java   View Source Code Vote up 5 votes
@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());
	}
}
 
Example 9
Project: athena   File: AtomixLeaderElectorTest.java   View Source Code Vote up 5 votes
public CompletableFuture<Change<Leadership>> nextEvent() {
    synchronized (this) {
        if (eventQueue.isEmpty()) {
            if (pendingFuture == null) {
                pendingFuture = new CompletableFuture<>();
            }
            return pendingFuture;
        } else {
            return CompletableFuture.completedFuture(eventQueue.poll());
        }
    }
}
 
Example 10
Project: athena   File: TestDistributedSet.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Boolean> contains(E element) {
    return CompletableFuture.completedFuture(set.contains(element));
}
 
Example 11
Project: pac4j-async   File: VertxAsyncSessionStore.java   View Source Code Vote up 4 votes
@Override
public <T> CompletableFuture<Void> set(WebContext<AsyncSessionStore> context, String key, T value) {
    session.put(key, value);
    return CompletableFuture.completedFuture(null);
}
 
Example 12
Project: athena   File: TestDistributedSet.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Void> addListener(SetEventListener<E> listener) {
    listeners.add(listener);
    return CompletableFuture.completedFuture(null);
}
 
Example 13
Project: athena   File: StoragePartitionClient.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Void> close() {
    return client != null ? client.close() : CompletableFuture.completedFuture(null);
}
 
Example 14
Project: athena   File: TestAtomicCounter.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Long> getAndAdd(long delta) {
    return CompletableFuture.completedFuture(value.getAndAdd(delta));
}
 
Example 15
Project: NioSmtpClient   File: CompositeSendInterceptorTest.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<List<SmtpResponse>> aroundPipelinedSequence(List<SmtpRequest> requests, Supplier<CompletableFuture<List<SmtpResponse>>> next) {
  return CompletableFuture.completedFuture(DEFAULT_RESPONSE);
}
 
Example 16
Project: athena   File: TestDistributedSet.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Integer> size() {
    return CompletableFuture.completedFuture(set.size());
}
 
Example 17
Project: jetcache   File: CacheResult.java   View Source Code Vote up 4 votes
public CacheResult(Throwable ex) {
    future = CompletableFuture.completedFuture(new ResultData(ex));
}
 
Example 18
Project: athena   File: TestAtomicCounter.java   View Source Code Vote up 4 votes
@Override
public CompletableFuture<Long> getAndIncrement() {
    return CompletableFuture.completedFuture(value.getAndIncrement());
}
 
Example 19
Project: bitflyer4j   File: RealtimeServiceImpl.java   View Source Code Vote up 3 votes
@Override
public CompletableFuture<Boolean> addListener(RealtimeListener listener) {

    if (listener == null) {
        return CompletableFuture.completedFuture(Boolean.FALSE);
    }

    boolean result = listeners.add(listener);

    log.trace("Add listener : {} - {}", result, listener);

    return CompletableFuture.completedFuture(result);

}
 
Example 20
Project: pac4j-async   File: AsyncSessionStore.java   View Source Code Vote up 2 votes
/**
 * Destroy the web session.
 *
 * @param context the web context
 * @return whether the session has been destroyed
 */
default CompletableFuture<Boolean> destroySession(AsyncWebContext context) {
    // by default, the session has not been destroyed and this can be done immediately
    return CompletableFuture.completedFuture(false);
}