java.util.concurrent.CompletionException Java Examples
The following examples show how to use
java.util.concurrent.CompletionException.
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: AsyncExecutionAspectSupport.java From java-technology-stack with MIT License | 6 votes |
/** * Delegate for actually executing the given task with the chosen executor. * @param task the task to execute * @param executor the chosen executor * @param returnType the declared return type (potentially a {@link Future} variant) * @return the execution result (potentially a corresponding {@link Future} handle) */ @Nullable protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) { if (CompletableFuture.class.isAssignableFrom(returnType)) { return CompletableFuture.supplyAsync(() -> { try { return task.call(); } catch (Throwable ex) { throw new CompletionException(ex); } }, executor); } else if (ListenableFuture.class.isAssignableFrom(returnType)) { return ((AsyncListenableTaskExecutor) executor).submitListenable(task); } else if (Future.class.isAssignableFrom(returnType)) { return executor.submit(task); } else { executor.submit(task); return null; } }
Example #2
Source File: CompletableFuture.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Reports result using Future.get conventions. */ private static <T> T reportGet(Object r) throws InterruptedException, ExecutionException { if (r == null) // by convention below, null means interrupted throw new InterruptedException(); if (r instanceof AltResult) { Throwable x, cause; if ((x = ((AltResult)r).ex) == null) return null; if (x instanceof CancellationException) throw (CancellationException)x; if ((x instanceof CompletionException) && (cause = x.getCause()) != null) x = cause; throw new ExecutionException(x); } @SuppressWarnings("unchecked") T t = (T) r; return t; }
Example #3
Source File: CompletableConverter.java From smallrye-reactive-streams-operators with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public Completable fromCompletionStage(CompletionStage cs) { CompletionStage<?> future = Objects.requireNonNull(cs); return Completable .create(emitter -> future.<Void> whenComplete((Object res, Throwable err) -> { if (!emitter.isDisposed()) { if (err != null) { if (err instanceof CompletionException) { emitter.onError(err.getCause()); } else { emitter.onError(err); } } else { emitter.onComplete(); } } })); }
Example #4
Source File: ReactiveConnectionPoolTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void configureWithWrongCredentials(TestContext context) { // This test doesn't need to rotate across all DBs and has PG-specific logic in it assumeTrue( DatabaseConfiguration.dbType() == DBType.POSTGRESQL ); thrown.expect( CompletionException.class ); thrown.expectMessage( "io.vertx.pgclient.PgException:" ); thrown.expectMessage( "\"bogus\"" ); String url = DatabaseConfiguration.getJdbcUrl(); Map<String,Object> config = new HashMap<>(); config.put( Settings.URL, url ); config.put( Settings.USER, "bogus" ); config.put( Settings.PASS, "bogus" ); ReactiveConnectionPool reactivePool = configureAndStartPool( config ); verifyConnectivity( context, reactivePool ); }
Example #5
Source File: Task.java From loom-fiber with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") public T join() { try { virtualThread.join(); } catch (InterruptedException e) { throw new CompletionException(e); } Object result = this.result; if (result == CANCELLED) { throw new CancellationException(); } if (result instanceof $$$<?>) { throw (($$$<RuntimeException>)result).throwable; } return (T)result; }
Example #6
Source File: FutureUtilsTest.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Tests that we can retry an operation. */ @Test public void testRetrySuccess() throws Exception { final int retries = 10; final AtomicInteger atomicInteger = new AtomicInteger(0); CompletableFuture<Boolean> retryFuture = FutureUtils.retry( () -> CompletableFuture.supplyAsync( () -> { if (atomicInteger.incrementAndGet() == retries) { return true; } else { throw new CompletionException(new FlinkException("Test exception")); } }, TestingUtils.defaultExecutor()), retries, TestingUtils.defaultExecutor()); assertTrue(retryFuture.get()); assertEquals(retries, atomicInteger.get()); }
Example #7
Source File: AsyncLoadingCacheTest.java From fdb-record-layer with Apache License 2.0 | 6 votes |
@Test public void testGettingAsyncFailures() { AsyncLoadingCache<Integer, Boolean> cachedResult = new AsyncLoadingCache<>(30000); final AtomicInteger callCount = new AtomicInteger(); final Supplier<CompletableFuture<Boolean>> supplier = () -> MoreAsyncUtil.delayedFuture(1 + random.nextInt(5), TimeUnit.MILLISECONDS).thenApply(ignore -> { int count = callCount.getAndIncrement(); if (count == 0) { // fail on first call throw new RecordCoreException("this is only a test"); } return true; }); try { cachedResult.orElseGet(1, supplier).join(); fail("should throw exception"); } catch (CompletionException ex) { assertThat("we got the expected exception", ex.getCause(), is(instanceOf(RecordCoreException.class))); assertThat("it's the test exception", ex.getCause().getMessage(), containsString("this is only a test")); } assertThat("before future is ready we return the in progress cached future", callCount.get(), is(1)); cachedResult.orElseGet(1, supplier).join(); assertThat("after cached future completes exceptionally we attempt to get the value again", callCount.get(), is(2)); }
Example #8
Source File: JwtTokenValidationTests.java From botbuilder-java with MIT License | 6 votes |
/** * Tests with a valid Token and invalid service url; and ensures that Service url is NOT added to Trusted service url list. */ @Test public void ChannelMsaHeaderInvalidServiceUrlShouldNotBeTrusted() throws IOException, ExecutionException, InterruptedException { String header = getHeaderToken(); CredentialProvider credentials = new SimpleCredentialProvider("7f74513e-6f96-4dbc-be9d-9a81fea22b88", ""); try { JwtTokenValidation.authenticateRequest( new Activity() {{ setServiceUrl("https://webchat.botframework.com/"); }}, header, credentials, new SimpleChannelProvider()).join(); Assert.fail("Should have thrown AuthenticationException"); } catch (CompletionException e) { Assert.assertTrue(e.getCause() instanceof AuthenticationException); Assert.assertFalse(MicrosoftAppCredentials.isTrustedServiceUrl("https://webchat.botframework.com/")); } }
Example #9
Source File: MultiOnEventTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testInvokeUniOnFailure() { AtomicInteger res = new AtomicInteger(-1); AtomicInteger twoGotCalled = new AtomicInteger(); assertThatThrownBy(() -> failed.onItem().invokeUni( i -> { res.set(i); return sub.onItem().invoke(c -> twoGotCalled.incrementAndGet()); }) .collectItems().asList().await().indefinitely()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(IOException.class) .hasMessageContaining("boom"); assertThat(twoGotCalled).hasValue(2); assertThat(res).hasValue(2); }
Example #10
Source File: SingleConverter.java From smallrye-reactive-streams-operators with Apache License 2.0 | 6 votes |
@Override public <X> Single<X> fromCompletionStage(CompletionStage<X> cs) { CompletionStage<X> future = Objects.requireNonNull(cs); return Single .create(emitter -> future.<X> whenComplete((X res, Throwable err) -> { if (!emitter.isUnsubscribed()) { if (err != null) { if (err instanceof CompletionException) { emitter.onError(err.getCause()); } else { emitter.onError(err); } } else { emitter.onSuccess(res); } } })); }
Example #11
Source File: ClientCaOrTofuTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@Test void shouldRejectDifferentCertificate() { CompletableFuture<Integer> statusCode = new CompletableFuture<>(); client .post(foobarServer.actualPort(), "localhost", "/sample", response -> statusCode.complete(response.statusCode())) .exceptionHandler(statusCode::completeExceptionally) .end(); Throwable e = assertThrows(CompletionException.class, statusCode::join); e = e.getCause(); while (!(e instanceof CertificateException)) { assertTrue(e instanceof SSLException, "Expected SSLException, but got " + e.getClass()); e = e.getCause(); } assertTrue(e.getMessage().contains("Remote host identification has changed!!"), e.getMessage()); assertTrue(e.getMessage().contains("has fingerprint " + foobarFingerprint)); }
Example #12
Source File: ClientWhitelistTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@Test void shouldNotValidateUsingCertificate() { CompletableFuture<Integer> statusCode = new CompletableFuture<>(); client .post( caValidServer.actualPort(), "localhost", "/sample", response -> statusCode.complete(response.statusCode())) .exceptionHandler(statusCode::completeExceptionally) .end(); Throwable e = assertThrows(CompletionException.class, statusCode::join); e = e.getCause(); while (!(e instanceof CertificateException)) { assertTrue(e instanceof SSLException); e = e.getCause(); } assertTrue(e.getMessage().contains("has unknown fingerprint " + caValidFingerprint)); }
Example #13
Source File: FencedRpcEndpointTest.java From flink with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Acknowledge> triggerMainThreadExecutorComputation(Time timeout) { return CompletableFuture.supplyAsync( () -> { try { computationLatch.await(); } catch (InterruptedException e) { throw new CompletionException(new FlinkException("Waiting on latch failed.", e)); } return value; }, getRpcService().getExecutor()) .thenApplyAsync( (String v) -> Acknowledge.get(), getMainThreadExecutor()); }
Example #14
Source File: Alarms.java From remote-monitoring-services-java with MIT License | 6 votes |
/** * Delete list of alarms by id * @param ids * @throws Throwable */ @Override public void delete(ArrayList<String> ids) throws Throwable { CompletableFuture[] tasks = new CompletableFuture[ids.size()]; for (int i = 0; i < ids.size(); i++) { String id = ids.get(i); tasks[i] = CompletableFuture.runAsync(() -> { try { this.delete(id); } catch (Exception e) { throw new CompletionException(e); } }); } CompletableFuture result = CompletableFuture.allOf(tasks); try { result.get(); } catch (ExecutionException ex) { throw ex.getCause(); } }
Example #15
Source File: Dispatcher.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<JobStatus> requestJobStatus(JobID jobId, Time timeout) { final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId); final CompletableFuture<JobStatus> jobStatusFuture = jobMasterGatewayFuture.thenCompose( (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout)); return jobStatusFuture.exceptionally( (Throwable throwable) -> { final JobDetails jobDetails = archivedExecutionGraphStore.getAvailableJobDetails(jobId); // check whether it is a completed job if (jobDetails == null) { throw new CompletionException(ExceptionUtils.stripCompletionException(throwable)); } else { return jobDetails.getStatus(); } }); }
Example #16
Source File: AsyncExecutionAspectSupport.java From spring-analysis-note with MIT License | 6 votes |
/** * Delegate for actually executing the given task with the chosen executor. * @param task the task to execute * @param executor the chosen executor * @param returnType the declared return type (potentially a {@link Future} variant) * @return the execution result (potentially a corresponding {@link Future} handle) */ @Nullable protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) { if (CompletableFuture.class.isAssignableFrom(returnType)) { return CompletableFuture.supplyAsync(() -> { try { return task.call(); } catch (Throwable ex) { throw new CompletionException(ex); } }, executor); } else if (ListenableFuture.class.isAssignableFrom(returnType)) { return ((AsyncListenableTaskExecutor) executor).submitListenable(task); } else if (Future.class.isAssignableFrom(returnType)) { return executor.submit(task); } else { executor.submit(task); return null; } }
Example #17
Source File: Dispatcher.java From flink with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<JobStatus> requestJobStatus(JobID jobId, Time timeout) { final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId); final CompletableFuture<JobStatus> jobStatusFuture = jobMasterGatewayFuture.thenCompose( (JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout)); return jobStatusFuture.exceptionally( (Throwable throwable) -> { final JobDetails jobDetails = archivedExecutionGraphStore.getAvailableJobDetails(jobId); // check whether it is a completed job if (jobDetails == null) { throw new CompletionException(ExceptionUtils.stripCompletionException(throwable)); } else { return jobDetails.getStatus(); } }); }
Example #18
Source File: Rules.java From remote-monitoring-services-java with MIT License | 6 votes |
private ArrayList<JsonNode> getResultListFromJson(JsonNode response) { ArrayList<JsonNode> resultList = new ArrayList<>(); // ignore case when parsing items array String itemsKey = response.has("Items") ? "Items" : "items"; for (JsonNode item : response.withArray(itemsKey)) { try { resultList.add(item); } catch (Exception e) { log.error("Could not parse data from Key Value Storage"); throw new CompletionException( new ExternalDependencyException( "Could not parse data from Key Value Storage")); } } return resultList; }
Example #19
Source File: FlatMapCompletionStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testInjectingANullCompletionStage() { AtomicReference<Subscriber<? super String>> reference = new AtomicReference<>(); Publisher<String> publisher = s -> { reference.set(s); s.onSubscribe(Subscriptions.empty()); }; CompletableFuture<List<String>> future = ReactiveStreams.fromPublisher(publisher) .flatMapCompletionStage(s -> (CompletionStage<String>) null) .toList() .run() .toCompletableFuture(); reference.get().onNext("a"); try { future.join(); fail("exception expected"); } catch (CompletionException e) { assertThat(e).hasCauseInstanceOf(NullPointerException.class); } }
Example #20
Source File: JwtTokenValidationTests.java From botbuilder-java with MIT License | 6 votes |
@Test public void EmulatorMsaHeaderBotAppIdDiffersShouldNotValidate() throws IOException, ExecutionException, InterruptedException { String header = getHeaderToken(); CredentialProvider credentials = new SimpleCredentialProvider("00000000-0000-0000-0000-000000000000", ""); try { JwtTokenValidation.validateAuthHeader( header, credentials, new SimpleChannelProvider(), "", null).join(); } catch (CompletionException e) { Assert.assertTrue(e.getCause() instanceof AuthenticationException); } }
Example #21
Source File: ClusterClient.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Triggers a savepoint for the job identified by the job id. The savepoint will be written to the given savepoint * directory, or {@link org.apache.flink.configuration.CheckpointingOptions#SAVEPOINT_DIRECTORY} if it is null. * * @param jobId job id * @param savepointDirectory directory the savepoint should be written to * @return path future where the savepoint is located * @throws FlinkException if no connection to the cluster could be established */ public CompletableFuture<String> triggerSavepoint(JobID jobId, @Nullable String savepointDirectory) throws FlinkException { final ActorGateway jobManager = getJobManagerGateway(); Future<Object> response = jobManager.ask(new JobManagerMessages.TriggerSavepoint(jobId, Option.<String>apply(savepointDirectory)), new FiniteDuration(1, TimeUnit.HOURS)); CompletableFuture<Object> responseFuture = FutureUtils.toJava(response); return responseFuture.thenApply((responseMessage) -> { if (responseMessage instanceof JobManagerMessages.TriggerSavepointSuccess) { JobManagerMessages.TriggerSavepointSuccess success = (JobManagerMessages.TriggerSavepointSuccess) responseMessage; return success.savepointPath(); } else if (responseMessage instanceof JobManagerMessages.TriggerSavepointFailure) { JobManagerMessages.TriggerSavepointFailure failure = (JobManagerMessages.TriggerSavepointFailure) responseMessage; throw new CompletionException(failure.cause()); } else { throw new CompletionException( new IllegalStateException("Unknown JobManager response of type " + responseMessage.getClass())); } }); }
Example #22
Source File: Rules.java From remote-monitoring-services-java with MIT License | 6 votes |
public CompletionStage<RuleServiceModel> upsertIfNotDeletedAsync(RuleServiceModel rule) { // Ensure dates are correct // Get the existing rule so we keep the created date correct; update the modified date to now RuleServiceModel savedRule = null; try { CompletableFuture<RuleServiceModel> savedRuleFuture = getAsync(rule.getId()).toCompletableFuture(); savedRule = savedRuleFuture.get(); } catch (Exception e) { log.error("Rule not found and will create new rule for Id:" + rule.getId(), e); } if (savedRule != null && savedRule.getDeleted()) { throw new CompletionException( new ResourceNotFoundException(String.format("Rule {%s} not found", rule.getId()))); } return upsertAsync(rule, savedRule); }
Example #23
Source File: JournalStoreClient.java From journalkeeper with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<List<JournalEntry>> get(int partition, long index, int size) { ReservedPartition.validatePartition(partition); return raftClient.query(querySerializer.serialize(JournalStoreQuery.createQueryEntries(partition, index, size))) .thenApply(queryResultSerializer::parse) .thenApply(result -> { if (result.getCode() == JournalStoreQueryResult.CODE_SUCCESS) { return result; } else if (result.getCode() == JournalStoreQueryResult.CODE_UNDERFLOW) { throw new CompletionException(new IndexUnderflowException()); } else if (result.getCode() == JournalStoreQueryResult.CODE_OVERFLOW) { throw new CompletionException(new IndexOverflowException()); } else { throw new CompletionException(new QueryJournalStoreException("Unknown exception")); } }) .thenApply(JournalStoreQueryResult::getEntries); }
Example #24
Source File: RestClusterClient.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
private CompletableFuture<String> triggerSavepoint( final JobID jobId, final @Nullable String savepointDirectory, final boolean cancelJob) { final SavepointTriggerHeaders savepointTriggerHeaders = SavepointTriggerHeaders.getInstance(); final SavepointTriggerMessageParameters savepointTriggerMessageParameters = savepointTriggerHeaders.getUnresolvedMessageParameters(); savepointTriggerMessageParameters.jobID.resolve(jobId); final CompletableFuture<TriggerResponse> responseFuture = sendRequest( savepointTriggerHeaders, savepointTriggerMessageParameters, new SavepointTriggerRequestBody(savepointDirectory, cancelJob)); return responseFuture.thenCompose(savepointTriggerResponseBody -> { final TriggerId savepointTriggerId = savepointTriggerResponseBody.getTriggerId(); return pollSavepointAsync(jobId, savepointTriggerId); }).thenApply(savepointInfo -> { if (savepointInfo.getFailureCause() != null) { throw new CompletionException(savepointInfo.getFailureCause()); } return savepointInfo.getLocation(); }); }
Example #25
Source File: Dispatcher.java From flink with Apache License 2.0 | 6 votes |
private CompletableFuture<JobMasterGateway> getJobMasterGatewayFuture(JobID jobId) { final CompletableFuture<JobManagerRunner> jobManagerRunnerFuture = jobManagerRunnerFutures.get(jobId); if (jobManagerRunnerFuture == null) { return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId)); } else { final CompletableFuture<JobMasterGateway> leaderGatewayFuture = jobManagerRunnerFuture.thenCompose(JobManagerRunner::getLeaderGatewayFuture); return leaderGatewayFuture.thenApplyAsync( (JobMasterGateway jobMasterGateway) -> { // check whether the retrieved JobMasterGateway belongs still to a running JobMaster if (jobManagerRunnerFutures.containsKey(jobId)) { return jobMasterGateway; } else { throw new CompletionException(new FlinkJobNotFoundException(jobId)); } }, getMainThreadExecutor()); } }
Example #26
Source File: JwtTokenValidationTests.java From botbuilder-java with MIT License | 6 votes |
@Test public void GovernmentChannelValidation_NoServiceClaimValue_Fails() { String appId = "1234567890"; String serviceUrl = "https://webchat.botframework.com/"; CredentialProvider credentials = new SimpleCredentialProvider(appId, ""); Map<String, String> claims = new HashMap<String, String>() {{ put(AuthenticationConstants.AUDIENCE_CLAIM, appId); put(AuthenticationConstants.SERVICE_URL_CLAIM, ""); }}; ClaimsIdentity identity = new ClaimsIdentity(GovernmentAuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER, claims); try { GovernmentChannelValidation.validateIdentity(identity, credentials, serviceUrl).join(); Assert.fail("Should have thrown an Authorization exception"); } catch (CompletionException e) { Assert.assertTrue(e.getCause() instanceof AuthenticationException); } }
Example #27
Source File: ExampleRpcClient.java From fastjgame with Apache License 2.0 | 5 votes |
@Nullable @Override public <V> V syncCall(@Nonnull RpcServerSpec serverSpec, @Nonnull RpcMethodSpec<V> request) throws CompletionException { if (serverSpec instanceof Session) { return invoker.syncCall((Session) serverSpec, request); } final FluentFuture<V> failedRpcFuture = newSessionNotFoundFuture(serverSpec); return failedRpcFuture.join(); }
Example #28
Source File: TeamsMessagingExtensionsSearchAuthConfigBot.java From botbuilder-java with MIT License | 5 votes |
private CompletableFuture<List<String[]>> findPackages(String text) { return CompletableFuture.supplyAsync(() -> { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url( String.format( "https://azuresearch-usnc.nuget.org/query?q=id:%s&prerelease=true", text ) ).build(); List<String[]> filteredItems = new ArrayList<String[]>(); try { Response response = client.newCall(request).execute(); JSONObject obj = new JSONObject(response.body().string()); JSONArray dataArray = (JSONArray) obj.get("data"); dataArray.forEach(i -> { JSONObject item = (JSONObject) i; filteredItems.add( new String[]{ item.getString("id"), item.getString("version"), item.getString("description"), item.has("projectUrl") ? item.getString("projectUrl") : "", item.has("iconUrl") ? item.getString("iconUrl") : "" } ); }); } catch (IOException e) { LoggerFactory.getLogger(TeamsMessagingExtensionsSearchAuthConfigBot.class) .error("findPackages", e); throw new CompletionException(e); } return filteredItems; }, ExecutorFactory.getExecutor()); }
Example #29
Source File: UniOnFailureRecoveryTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testWithPredicateOnClass() { Integer value = failed.onFailure(IOException.class).recoverWithItem(23).await().indefinitely(); assertThat(value).isEqualTo(23); assertThatExceptionOfType(CompletionException.class) .isThrownBy(() -> failed.onFailure(IllegalStateException.class).recoverWithItem(23).await() .indefinitely()) .withCauseExactlyInstanceOf(IOException.class); }
Example #30
Source File: UniOnItemInvokeTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testInvokeOnFailure() { AtomicInteger res = new AtomicInteger(-1); assertThatThrownBy(() -> failed.onItem().invoke(res::set).await().indefinitely()) .isInstanceOf(CompletionException.class).hasCauseInstanceOf(IOException.class) .hasMessageContaining("boom"); assertThat(res).hasValue(-1); }