Java Code Examples for java.util.concurrent.CompletionException

The following examples show how to use java.util.concurrent.CompletionException. These examples are extracted from open source projects. 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 Project: botbuilder-java   Source File: JwtTokenValidationTests.java    License: MIT License 6 votes vote down vote up
/**
 * 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 2
Source Project: fdb-record-layer   Source File: AsyncLoadingCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: loom-fiber   Source File: Task.java    License: MIT License 6 votes vote down vote up
@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 4
@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
@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 6
/**
 * 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 7
Source Project: incubator-tuweni   Source File: ClientCaOrTofuTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: incubator-tuweni   Source File: ClientWhitelistTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: flink   Source File: FencedRpcEndpointTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: botbuilder-java   Source File: JwtTokenValidationTests.java    License: MIT License 6 votes vote down vote up
@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 11
Source Project: Flink-CEPplus   Source File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: remote-monitoring-services-java   Source File: Alarms.java    License: MIT License 6 votes vote down vote up
/**
 * 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 13
Source Project: Flink-CEPplus   Source File: RestClusterClient.java    License: Apache License 2.0 6 votes vote down vote up
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 14
Source Project: journalkeeper   Source File: JournalStoreClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 15
Source Project: Flink-CEPplus   Source File: ClusterClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 16
Source Project: botbuilder-java   Source File: JwtTokenValidationTests.java    License: MIT License 6 votes vote down vote up
@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 17
/**
 * 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 18
Source Project: flink   Source File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
@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 19
Source Project: remote-monitoring-services-java   Source File: Rules.java    License: MIT License 6 votes vote down vote up
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 20
Source Project: flink   Source File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
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 21
@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 22
Source Project: Flink-CEPplus   Source File: FutureUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 23
Source Project: smallrye-mutiny   Source File: MultiOnEventTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 24
@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 25
Source Project: spring-analysis-note   Source File: AsyncExecutionAspectSupport.java    License: MIT License 6 votes vote down vote up
/**
 * 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 26
Source Project: remote-monitoring-services-java   Source File: Rules.java    License: MIT License 6 votes vote down vote up
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 27
@Override
@Nullable
public T get() throws CompletionException, InterruptedException {
  try {
    return get(10, TimeUnit.SECONDS);
  } catch (TimeoutException ex) {
    throw new RuntimeException("Default timeout triggered for blocking call to AsyncResult::get()", ex);
  }
}
 
Example 28
Source Project: joyqueue   Source File: StoreInitializer.java    License: Apache License 2.0 5 votes vote down vote up
protected void restore() throws Exception {
    Broker broker = clusterManager.getBroker();
    List<Replica> replicas = nameService.getReplicaByBroker(broker.getId());
    if (CollectionUtils.isEmpty(replicas)) {
        return;
    }
    // 并行恢复所有的PartitionGroup
    ExecutorService executor = Executors.newFixedThreadPool(32, new NamedThreadFactory("Store-recover-threads"));
    try {
        CompletableFuture.allOf(
                replicas.stream()
                        .map(replica -> CompletableFuture.runAsync(() -> {
                            try {
                                PartitionGroup group = clusterManager.getPartitionGroupByGroup(replica.getTopic(), replica.getGroup());
                                if (group == null) {
                                    logger.warn("group is null topic {},replica {}", replica.getTopic(), replica.getGroup());
                                    throw new RuntimeException(String.format("group is null topic %s,replica %s", replica.getTopic(), replica.getGroup()));
                                }
                                if (!group.getReplicas().contains(broker.getId())) {
                                    return;
                                }
                                doRestore(group, replica, broker);
                            } catch (Exception e) {
                                throw new CompletionException(e);
                            }
                                }, executor)
                        ).toArray(CompletableFuture[]::new)
        ).get();
    } finally {
        executor.shutdown();
    }
}
 
Example 29
@Test
public void testBatchMock() {
    String baseUrl = "http://" + server.getHostName() + ":" + server.getPort() + "/";
    System.setProperty("twitter4j.restBaseURL", baseUrl);

    Pipeline pipeline = Pipeline.create();
    String query = "Jet flies";
    BatchSource<Status> twitterSearch = TwitterSources.search(
            getCredentials(), query);
    BatchStage<String> tweets = pipeline
            .readFrom(twitterSearch)
            .map(status -> "@" + status.getUser().getName() + " - " + status.getText());

    tweets.writeTo(AssertionSinks.assertCollectedEventually(10,
            list -> assertGreaterOrEquals("Emits at least 30 tweets in 10 secs.",
                    list.size(), 30)));
    Job job = createJetMember().newJob(pipeline);

    sleepAtLeastSeconds(2);

    try {
        job.join();
        fail("Job should have completed with an AssertionCompletedException, but completed normally");
    } catch (CompletionException e) {
        String errorMsg = e.getCause().getMessage();
        assertTrue("Job was expected to complete with AssertionCompletedException, but completed with: "
                + e.getCause(), errorMsg.contains(AssertionCompletedException.class.getName()));
    }
}
 
Example 30
private void assertCompletedWithException(AsyncResult<?> asyncResult, Exception exception) throws Exception {
  try {
    asyncResult.get();
    fail("Expected exception not thrown");
  } catch (CompletionException ex) {
    assertThat(ex.getCause()).isSameAs(exception);
  }
}