Java Code Examples for java.util.concurrent.CompletableFuture#failedFuture()

The following examples show how to use java.util.concurrent.CompletableFuture#failedFuture() . 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: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Delete user
 * This can only be done by the logged in user.
 * @param username The name that needs to be deleted (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> deleteUser(String username) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = deleteUserRequestBuilder(username);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "deleteUser call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 2
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 
 * @param query  (required)
 * @param body  (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testBodyWithQueryParams(String query, User body) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testBodyWithQueryParamsRequestBuilder(query, body);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testBodyWithQueryParams call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 3
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * For this test, the body for this request much reference a schema named &#x60;File&#x60;.
 * @param body  (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testBodyWithFileSchema(FileSchemaTestClass body) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testBodyWithFileSchemaRequestBuilder(body);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testBodyWithFileSchema call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 4
Source File: RemoteInterface.java    From turbo-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param methodId
 * @param timeout
 *            超时时间,millseconds
 * @param methodParam
 * @param failoverInvoker
 * @return
 */
default public CompletableFuture<?> $remote_execute(int methodId, long timeout, MethodParam methodParam,
		Invoker<CompletableFuture<?>> failoverInvoker) {
	try {
		return getApp().execute(methodId, timeout, methodParam, failoverInvoker);
	} catch (Exception e) {
		if (logger.isWarnEnabled()) {
			logger.warn("远程调用发生错误");
		}

		if (failoverInvoker == null) {
			return CompletableFuture.failedFuture(e);
		} else {
			if (logger.isInfoEnabled()) {
				logger.info("远程调用发生错误,使用本地回退方法执行");
			}

			return failoverInvoker.invoke(methodParam);
		}
	}
}
 
Example 5
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Updates a pet in the store with form data
 * 
 * @param petId ID of pet that needs to be updated (required)
 * @param name Updated name of the pet (optional)
 * @param status Updated status of the pet (optional)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> updatePetWithForm(Long petId, String name, String status) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = updatePetWithFormRequestBuilder(petId, name, status);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "updatePetWithForm call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 6
Source File: BatteryExternalStatsWorker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Schedule a sync {@param syncRunnable} with a delay. If there's already a scheduled sync, a
 * new sync won't be scheduled unless it is being scheduled to run immediately (delayMillis=0).
 *
 * @param lastScheduledSync the task which was earlier scheduled to run
 * @param syncRunnable the task that needs to be scheduled to run
 * @param delayMillis time after which {@param syncRunnable} needs to be scheduled
 * @return scheduled {@link Future} which can be used to check if task is completed or to
 *         cancel it if needed
 */
@GuardedBy("this")
private Future<?> scheduleDelayedSyncLocked(Future<?> lastScheduledSync, Runnable syncRunnable,
        long delayMillis) {
    if (mExecutorService.isShutdown()) {
        return CompletableFuture.failedFuture(new IllegalStateException("worker shutdown"));
    }

    if (lastScheduledSync != null) {
        // If there's already a scheduled task, leave it as is if we're trying to
        // re-schedule it again with a delay, otherwise cancel and re-schedule it.
        if (delayMillis == 0) {
            lastScheduledSync.cancel(false);
        } else {
            return lastScheduledSync;
        }
    }

    return mExecutorService.schedule(syncRunnable, delayMillis, TimeUnit.MILLISECONDS);
}
 
Example 7
Source File: RetainedMessageStoreImpl.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@NotNull
@Override
public CompletableFuture<Void> addOrReplace(@NotNull final RetainedPublish retainedPublish) {
    Preconditions.checkNotNull(retainedPublish, "A retained publish must never be null");
    if (pluginServiceRateLimitService.rateLimitExceeded()) {
        return CompletableFuture.failedFuture(PluginServiceRateLimitService.RATE_LIMIT_EXCEEDED_EXCEPTION);
    }
    if (!(retainedPublish instanceof RetainedPublishImpl)) {
        return CompletableFuture.failedFuture(new DoNotImplementException(RetainedPublish.class.getSimpleName()));
    }
    final ListenableFuture<Void> persist = retainedMessagePersistence.persist(
            retainedPublish.getTopic(),
            RetainedPublishImpl.convert((RetainedPublishImpl) retainedPublish));

    return ListenableFutureConverter.toCompletable(persist, globalManagedPluginExecutorService);
}
 
Example 8
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트
 * Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트
 * @param number None (required)
 * @param _double None (required)
 * @param patternWithoutDelimiter None (required)
 * @param _byte None (required)
 * @param integer None (optional)
 * @param int32 None (optional)
 * @param int64 None (optional)
 * @param _float None (optional)
 * @param string None (optional)
 * @param binary None (optional)
 * @param date None (optional)
 * @param dateTime None (optional)
 * @param password None (optional)
 * @param paramCallback None (optional)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testEndpointParametersRequestBuilder(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testEndpointParameters call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 9
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Logs out current logged in user session
 * 
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> logoutUser() throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = logoutUserRequestBuilder();
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "logoutUser call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 10
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Fake endpoint to test group parameters (optional)
 * Fake endpoint to test group parameters (optional)
 * @param requiredStringGroup Required String in group parameters (required)
 * @param requiredBooleanGroup Required Boolean in group parameters (required)
 * @param requiredInt64Group Required Integer in group parameters (required)
 * @param stringGroup String in group parameters (optional)
 * @param booleanGroup Boolean in group parameters (optional)
 * @param int64Group Integer in group parameters (optional)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testGroupParametersRequestBuilder(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testGroupParameters call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example 11
Source File: ClientServiceImpl.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public CompletableFuture<Optional<SessionInformation>> getSession(@NotNull final String clientId) {
    Preconditions.checkNotNull(clientId, "A client id must never be null");
    if (pluginServiceRateLimitService.rateLimitExceeded()) {
        return CompletableFuture.failedFuture(PluginServiceRateLimitService.RATE_LIMIT_EXCEEDED_EXCEPTION);
    }

    final ClientSession session = clientSessionPersistence.getSession(clientId, false);
    if (session == null) {
        return CompletableFuture.completedFuture(Optional.empty());
    }
    return CompletableFuture.completedFuture(Optional.of(
            new SessionInformationImpl(clientId, session.getSessionExpiryInterval(), session.isConnected())));
}
 
Example 12
Source File: BatteryExternalStatsWorker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public synchronized Future<?> scheduleWrite() {
    if (mExecutorService.isShutdown()) {
        return CompletableFuture.failedFuture(new IllegalStateException("worker shutdown"));
    }

    scheduleSyncLocked("write", UPDATE_ALL);
    // Since we use a single threaded executor, we can assume the next scheduled task's
    // Future finishes after the sync.
    return mExecutorService.submit(mWriteTask);
}
 
Example 13
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * failedFuture(null) throws NPE
 */
public void testFailedFuture_null() {
    try {
        CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 14
Source File: RetainedMessageStoreImpl.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@NotNull
@Override
public CompletableFuture<Optional<RetainedPublish>> getRetainedMessage(@NotNull final String topic) {
    Preconditions.checkNotNull(topic, "A topic must never be null");
    if (pluginServiceRateLimitService.rateLimitExceeded()) {
        return CompletableFuture.failedFuture(PluginServiceRateLimitService.RATE_LIMIT_EXCEEDED_EXCEPTION);
    }
    final ListenableFuture<RetainedMessage> retainedMessageFuture = retainedMessagePersistence.get(topic);
    return ListenableFutureConverter.toCompletable(retainedMessageFuture, (r) -> r == null ? Optional.empty() : Optional.of(new RetainedPublishImpl(topic, r)), false, globalManagedPluginExecutorService);
}
 
Example 15
Source File: SqlHttpHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<XContentBuilder> executeBulkRequest(Session session,
                                                              String stmt,
                                                              List<List<Object>> bulkArgs) {
    final long startTimeInNs = System.nanoTime();
    session.parse(UNNAMED, stmt, emptyList());
    final RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[bulkArgs.size()];
    for (int i = 0; i < bulkArgs.size(); i++) {
        session.bind(UNNAMED, UNNAMED, bulkArgs.get(i), null);
        ResultReceiver resultReceiver = new RestBulkRowCountReceiver(results, i);
        session.execute(UNNAMED, 0, resultReceiver);
    }
    if (results.length > 0) {
        DescribeResult describeResult = session.describe('P', UNNAMED);
        if (describeResult.getFields() != null) {
            return CompletableFuture.failedFuture(new UnsupportedOperationException(
                        "Bulk operations for statements that return result sets is not supported"));
        }
    }
    return session.sync()
        .thenApply(ignored -> {
            try {
                return ResultToXContentBuilder.builder(JsonXContent.contentBuilder())
                    .cols(emptyList())
                    .duration(startTimeInNs)
                    .bulkRows(results)
                    .build();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
}
 
Example 16
Source File: TransportDecommissionNodeAction.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<AcknowledgedResponse> nodeOperation(DecommissionNodeRequest request) {
    try {
        return decommissioningService.decommission().thenApply(aVoid -> new AcknowledgedResponse(true));
    } catch (Throwable t) {
        return CompletableFuture.failedFuture(t);
    }
}
 
Example 17
Source File: SubscriptionStoreImpl.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Override
public @NotNull CompletableFuture<Void> iterateAllSubscribersForTopic(final @NotNull String topic,
                                                                      final @NotNull SubscriptionType subscriptionType,
                                                                      final @NotNull IterationCallback<SubscriberForTopicResult> callback,
                                                                      final @NotNull Executor callbackExecutor) {

    Preconditions.checkNotNull(topic, "Topic cannot be null");
    Preconditions.checkNotNull(callback, "Callback cannot be null");
    Preconditions.checkNotNull(callbackExecutor, "Executor cannot be null");
    Preconditions.checkArgument(
            Topics.isValidTopicToPublish(topic),
            "Topic must be a valid topic and cannot contain wildcard characters, got '" + topic + "'");

    if (rateLimitService.rateLimitExceeded()) {
        return CompletableFuture.failedFuture(PluginServiceRateLimitService.RATE_LIMIT_EXCEEDED_EXCEPTION);
    }

    final ImmutableSet<String> subscribers = topicTree.getSubscribersForTopic(topic, new SubscriptionTypeItemFilter(subscriptionType), false);

    final SettableFuture<Void> iterationFinishedFuture = SettableFuture.create();

    callbackExecutor.execute(() -> {

        final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader();
        final IterationContextImpl iterationContext = new IterationContextImpl();
        try {
            Thread.currentThread().setContextClassLoader(callback.getClass().getClassLoader());

            for (final String subscriber : subscribers) {
                try {
                    callback.iterate(iterationContext, new SubscriberForTopicResultImpl(subscriber));
                    if (iterationContext.isAborted()) {
                        iterationFinishedFuture.set(null);
                        return;
                    }

                } catch (final Exception e) {
                    iterationFinishedFuture.setException(e);
                    return;
                }
            }
            iterationFinishedFuture.set(null);
        } finally {
            Thread.currentThread().setContextClassLoader(previousClassLoader);
        }
    });

    return ListenableFutureConverter.toCompletable(iterationFinishedFuture, managedExtensionExecutorService);
}
 
Example 18
Source File: DCLStatementDispatcher.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
protected CompletableFuture<Long> visitAnalyzedStatement(AnalyzedStatement analyzedStatement, UserManager userManager) {
    return CompletableFuture.failedFuture(new UnsupportedOperationException(String.format(Locale.ENGLISH, "Can't handle \"%s\"", analyzedStatement)));
}
 
Example 19
Source File: TransportDistributedResultAction.java    From crate with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<DistributedResultResponse> nodeOperation(final DistributedResultRequest request,
                                                                   @Nullable Iterator<TimeValue> retryDelay) {
    RootTask rootTask = tasksService.getTaskOrNull(request.jobId());
    if (rootTask == null) {
        if (tasksService.recentlyFailed(request.jobId())) {
            return CompletableFuture.failedFuture(JobKilledException.of(
                "Received result for job=" + request.jobId() + " but there is no context for this job due to a failure during the setup."));
        } else {
            return retryOrFailureResponse(request, retryDelay);
        }
    }

    DownstreamRXTask rxTask;
    try {
        rxTask = rootTask.getTask(request.executionPhaseId());
    } catch (ClassCastException e) {
        return CompletableFuture.failedFuture(new IllegalStateException(String.format(Locale.ENGLISH,
                                                                                      "Found execution rootTask for %d but it's not a downstream rootTask", request.executionPhaseId()), e));
    } catch (Throwable t) {
        return CompletableFuture.failedFuture(t);
    }

    PageBucketReceiver pageBucketReceiver = rxTask.getBucketReceiver(request.executionPhaseInputId());
    if (pageBucketReceiver == null) {
        return CompletableFuture.failedFuture(new IllegalStateException(String.format(Locale.ENGLISH,
                                                                                      "Couldn't find BucketReceiver for input %d", request.executionPhaseInputId())));
    }

    Throwable throwable = request.throwable();
    if (throwable == null) {
        SendResponsePageResultListener pageResultListener = new SendResponsePageResultListener();
        pageBucketReceiver.setBucket(
            request.bucketIdx(),
            request.readRows(pageBucketReceiver.streamers()),
            request.isLast(),
            pageResultListener
        );
        return pageResultListener.future;
    } else {
        pageBucketReceiver.kill(throwable);
        return CompletableFuture.completedFuture(new DistributedResultResponse(false));
    }
}
 
Example 20
Source File: CheckedValue.java    From yangtools with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Transform this object into an immediately-completed {@link CompletableFuture}. The future will be successful
 * if this object has a contained value or unsuccessful if this objects contains an exception.
 *
 * @return A {@link CompletableFuture}.
 */
public final CompletableFuture<T> toCompletableFuture() {
    return isFirst() ? CompletableFuture.completedFuture(first()) : CompletableFuture.failedFuture(second());
}