java.util.concurrent.CompletableFuture#failedFuture ( )源码实例Demo

下面列出了java.util.concurrent.CompletableFuture#failedFuture ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openapi-generator   文件: FakeApi.java
/**
 * 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);
  }
}
 
源代码2 项目: openapi-generator   文件: UserApi.java
/**
 * 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);
  }
}
 
源代码3 项目: openapi-generator   文件: FakeApi.java
/**
 * 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);
  }
}
 
/**
 * @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);
}
 
源代码5 项目: openapi-generator   文件: UserApi.java
/**
 * 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);
  }
}
 
/**
 * 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);
}
 
源代码7 项目: openapi-generator   文件: PetApi.java
/**
 * 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);
  }
}
 
源代码8 项目: turbo-rpc   文件: RemoteInterface.java
/**
 * 
 * @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);
		}
	}
}
 
源代码9 项目: openapi-generator   文件: FakeApi.java
/**
 * 
 * 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);
  }
}
 
源代码10 项目: openapi-generator   文件: FakeApi.java
/**
 * 
 * 
 * @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);
  }
}
 
源代码11 项目: crate   文件: SqlHttpHandler.java
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);
            }
        });
}
 
源代码12 项目: openjdk-jdk9   文件: CompletableFutureTest.java
/**
 * failedFuture(null) throws NPE
 */
public void testFailedFuture_null() {
    try {
        CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
@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())));
}
 
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);
}
 
/**
 * @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);
}
 
源代码16 项目: crate   文件: TransportDecommissionNodeAction.java
@Override
public CompletableFuture<AcknowledgedResponse> nodeOperation(DecommissionNodeRequest request) {
    try {
        return decommissioningService.decommission().thenApply(aVoid -> new AcknowledgedResponse(true));
    } catch (Throwable t) {
        return CompletableFuture.failedFuture(t);
    }
}
 
源代码17 项目: crate   文件: TransportDistributedResultAction.java
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));
    }
}
 
@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);
}
 
源代码19 项目: crate   文件: DCLStatementDispatcher.java
@Override
protected CompletableFuture<Long> visitAnalyzedStatement(AnalyzedStatement analyzedStatement, UserManager userManager) {
    return CompletableFuture.failedFuture(new UnsupportedOperationException(String.format(Locale.ENGLISH, "Can't handle \"%s\"", analyzedStatement)));
}
 
源代码20 项目: yangtools   文件: CheckedValue.java
/**
 * 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());
}