當前位置: 首頁>>代碼示例>>Java>>正文


Java CompletionException類代碼示例

本文整理匯總了Java中java.util.concurrent.CompletionException的典型用法代碼示例。如果您正苦於以下問題:Java CompletionException類的具體用法?Java CompletionException怎麽用?Java CompletionException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CompletionException類屬於java.util.concurrent包,在下文中一共展示了CompletionException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testSetReturnsBeforeInlinedContinuations

import java.util.concurrent.CompletionException; //導入依賴的package包/類
/**
 * Verifies that inlining continuations do not have to complete execution before {@link AsyncAutoResetEvent#set()}
 * returns.
 */
@Test
public void testSetReturnsBeforeInlinedContinuations() throws Exception {
	CompletableFuture<Void> setReturned = new CompletableFuture<>();
	CompletableFuture<Void> inlinedContinuation = event.waitAsync().whenComplete((result, exception) -> {
		try {
			// Arrange to synchronously block the continuation until set() has returned,
			// which would deadlock if set() does not return until inlined continuations complete.
			setReturned.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
		} catch (InterruptedException | ExecutionException | TimeoutException ex) {
			throw new CompletionException(ex);
		}
	});

	event.set();
	setReturned.complete(null);
	inlinedContinuation.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:22,代碼來源:AsyncAutoResetEventTest.java

示例2: testAuthorizerThrowsRequiresHttpAction

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test(timeout = 1000)
public void testAuthorizerThrowsRequiresHttpAction(final TestContext testContext) throws Exception {
    simulatePreviousAuthenticationSuccess();
    final AsyncClient<TestCredentials, TestProfile> indirectClient = getMockIndirectClient(NAME);
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, indirectClient);
    when(config.getClients()).thenReturn(clients);
    final String authorizers = NAME;
    addSingleAuthorizerToConfig((context, prof) -> { throw HttpAction.status("bad request", 400, context); });
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);
    final Async async = testContext.async();
    final CompletableFuture<Object> result = simulatePreviousAuthenticationSuccess()
            .thenCompose(v -> asyncSecurityLogic.perform(webContext, accessGrantedAdapter, null, authorizers, null));
    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(HttpAction.class),
            hasProperty("message", is("bad request")),
            hasProperty("code", is(400))));
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        assertThat(status.get(), is(400));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:23,代碼來源:DefaultAsyncSecurityLogicTest.java

示例3: getResultListFromJson

import java.util.concurrent.CompletionException; //導入依賴的package包/類
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;
    }
 
開發者ID:Azure,項目名稱:device-telemetry-java,代碼行數:21,代碼來源:Rules.java

示例4: testDoubleDirectClientChooseBadDirectClient

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testDoubleDirectClientChooseBadDirectClient(final TestContext testContext) throws Exception {
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = doubleDirectClients();
    when(config.getClients()).thenReturn(clients);
    final String clientNames = NAME;
    when(webContext.getRequestParameter(eq(Clients.DEFAULT_CLIENT_NAME_PARAMETER))).thenReturn(VALUE);
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, true, config, httpActionAdapter);
    final Async async = testContext.async();

    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(TechnicalException.class),
            hasProperty("message", is("Client not allowed: " + VALUE))));
    final CompletableFuture<Object> result = asyncSecurityLogic.perform(webContext, accessGrantedAdapter, clientNames, null, null);
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);

}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:20,代碼來源:DefaultAsyncSecurityLogicTest.java

示例5: testAlreadyAuthenticatedNotAuthorized

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test(timeout = 1000)
public void testAlreadyAuthenticatedNotAuthorized(final TestContext testContext) throws Exception {
    simulatePreviousAuthenticationSuccess();
    final AsyncClient<TestCredentials, TestProfile> indirectClient = getMockIndirectClient(NAME);
    final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = new Clients<>(CALLBACK_URL, indirectClient);
    when(config.getClients()).thenReturn(clients);
    final String authorizers = NAME;
    addSingleAuthorizerToConfig((context, prof) -> prof.get(0).getId().equals(BAD_USERNAME));
    asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, false, config, httpActionAdapter);
    final Async async = testContext.async();
    final CompletableFuture<Object> result = simulatePreviousAuthenticationSuccess()
            .thenCompose(v -> asyncSecurityLogic.perform(webContext, accessGrantedAdapter, null, authorizers, null));

    exception.expect(CompletionException.class);
    exception.expectCause(allOf(IsInstanceOf.instanceOf(HttpAction.class),
            hasProperty("message", is("forbidden")),
            hasProperty("code", is(403))));
    assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
        assertThat(o, is(nullValue()));
        assertThat(status.get(), is(403));
        verify(accessGrantedAdapter, times(0)).adapt(webContext);
    }), async);
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:24,代碼來源:DefaultAsyncSecurityLogicTest.java

示例6: testRemoval

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testRemoval() throws Exception {
    // A removal should fail when there's no such entry.
    assertThatThrownBy(() -> repo
            .commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Change.ofRemoval(jsonPaths[0])).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);

    Revision revision = repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, jsonUpserts[0]).join();
    assertThat(repo.exists(revision, jsonPaths[0]).join()).isTrue();

    // A removal should succeed when there's an entry.
    revision = repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Change.ofRemoval(jsonPaths[0])).join();
    assertThat(repo.exists(revision, jsonPaths[0]).join()).isFalse();

    // A removal should fail when there's no such entry.
    assertThatThrownBy(() -> repo
            .commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Change.ofRemoval(jsonPaths[0])).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:22,代碼來源:GitRepositoryTest.java

示例7: testRecursiveRemoval

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testRecursiveRemoval() throws Exception {
    // A recursive removal should fail when there's no such entry.
    final String curDir = prefix.substring(0, prefix.length() - 1); // Remove trailing '/'.
    assertThatThrownBy(
            () -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Change.ofRemoval(curDir)).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);

    // Add some files
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, jsonUpserts).join();
    assertThat(repo.find(HEAD, allPattern).join()).hasSize(jsonUpserts.length);

    // Perform a recursive removal
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Change.ofRemoval(curDir)).join();
    assertThat(repo.find(HEAD, allPattern).join()).isEmpty();
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:18,代碼來源:GitRepositoryTest.java

示例8: testNoLockHeldForCancellationTokenContinuation

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testNoLockHeldForCancellationTokenContinuation() {
	CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
	CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync(cancellationTokenSource.getToken());
	CompletableFuture<Void> handled = pollFuture.handle((result, exception) -> {
		try {
			ForkJoinPool.commonPool().submit(ExecutionContext.wrap(() -> {
				// Add presumably requires a private lock internally.
				// Since we're calling it on a different thread than the
				// blocking cancellation continuation, this should deadlock
				// if and only if the queue is holding a lock while invoking
				// our cancellation continuation (which they shouldn't be doing).
				queue.add(new GenericParameterHelper(1));
			})).get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
			return null;
		} catch (InterruptedException | ExecutionException | TimeoutException ex) {
			throw new CompletionException(ex);
		}
	});

	cancellationTokenSource.cancel();

	handled.join();
	Assert.assertEquals(1, queue.size());
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:26,代碼來源:AsyncQueueTest.java

示例9: testRenameFailure

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testRenameFailure() throws Exception {
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY,
                                         jsonUpserts[0], jsonUpserts[1],
                                         Change.ofRename(jsonPaths[0], jsonPaths[1])).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);

    // Renaming to its own path.
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, jsonUpserts[0]).join();
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY,
                                         Change.ofRename(jsonPaths[0], jsonPaths[0])).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);

    // Renaming to its own path, when the file is not committed yet.
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY,
                                         jsonUpserts[1], Change.ofRename(jsonPaths[1], jsonPaths[1]))
                                 .join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(ChangeConflictException.class);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:23,代碼來源:GitRepositoryTest.java

示例10: connectAsync

import java.util.concurrent.CompletionException; //導入依賴的package包/類
private static void connectAsync(String server) throws Exception {
    try {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .build();
        HttpRequest request = HttpRequest.newBuilder(new URI(server))
                .timeout(Duration.ofMillis(TIMEOUT))
                .POST(fromString("body"))
                .build();
        HttpResponse<String> response = client.sendAsync(request, asString()).join();
        System.out.println("Received unexpected reply: " + response.statusCode());
        throw new RuntimeException("unexpected successful connection");
    } catch (CompletionException e) {
        if (e.getCause() instanceof HttpTimeoutException) {
            System.out.println("expected exception: " + e.getCause());
        } else {
            throw new RuntimeException("Unexpected exception received: " + e.getCause(), e);
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:Timeout.java

示例11: testEmptyCommitWithRedundantUpsert

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testEmptyCommitWithRedundantUpsert() throws Exception {
    assertThatThrownBy(
            () -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, Collections.emptyList()).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(RedundantChangeException.class);

    // Create a file to produce redundant changes.
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, jsonUpserts[0]).join();

    // Ensure redundant changes do not count as a valid change.
    assertThatThrownBy(
            () -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, jsonUpserts[0]).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(RedundantChangeException.class);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:17,代碼來源:GitRepositoryTest.java

示例12: testEmptyCommitWithRedundantUpsert2

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testEmptyCommitWithRedundantUpsert2() throws Exception {
    // Create files to produce redundant changes.
    final Change<JsonNode> change1 = Change.ofJsonUpsert("/redundant_upsert_2.json",
                                                         "{ \"foo\": 0, \"bar\": 1 }");
    final Change<String> change2 = Change.ofTextUpsert("/redundant_upsert_2.txt", "foo");
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, change1).join();
    repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, change2).join();

    // Ensure redundant changes do not count as a valid change.
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, change1).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(RedundantChangeException.class);
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, change2).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(RedundantChangeException.class);

    // Ensure a change only whose serialized form is different does not count.
    final Change<JsonNode> change1a = Change.ofJsonUpsert("/redundant_upsert_2.json",
                                                          "{ \"bar\": 1, \"foo\": 0 }");
    assertThatThrownBy(() -> repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, change1a).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(RedundantChangeException.class);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:25,代碼來源:GitRepositoryTest.java

示例13: assertSuccessfulEvaluation

import java.util.concurrent.CompletionException; //導入依賴的package包/類
protected <T> CompletableFuture<Void> assertSuccessfulEvaluation (final CompletableFuture<T> future,
                                                                  final Consumer<T> assertions,
                                                                  final Async async){
    return future.handle((v, t) -> {
        if (t != null) {
            executionContext.runOnContext(ExceptionSoftener.softenRunnable(() -> {
                if (t instanceof CompletionException) {throw t.getCause();
            }else {
                            throw t;
                        }
                    }));
        } else {
            executionContext.runOnContext(() -> {
                assertions.accept(v);
                async.complete();
            });
        }
        return null;
    });
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:21,代碼來源:VertxAsyncTestBase.java

示例14: testCreateProjectFailures

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testCreateProjectFailures() throws Exception {
    assertThatThrownByWithExpectedException(ProjectExistsException.class, "project: p", () ->
            rule.client().createProject(rule.project()).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == PROJECT_EXISTS);

    assertThatThrownByWithExpectedException(ProjectExistsException.class, "project: rp", () ->
            // It is not allowed to create a new project whose name is same with the removed project.
            rule.client().createProject(rule.removedProject()).join())
            .isInstanceOf(CompletionException.class)
            .hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == PROJECT_EXISTS);

    assertThatThrownByWithExpectedException(
            IllegalArgumentException.class, "invalid project name: ..", () ->
                    rule.client().createProject("..").join())
            .isInstanceOf(CompletionException.class).hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == BAD_REQUEST);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:22,代碼來源:ProjectManagementTest.java

示例15: testCreateRepositoryFailures

import java.util.concurrent.CompletionException; //導入依賴的package包/類
@Test
public void testCreateRepositoryFailures() throws Exception {
    assertThatThrownByWithExpectedException(RepositoryExistsException.class, "repository: r", () ->
            rule.client().createRepository(rule.project(), rule.repo1()).join())
            .isInstanceOf(CompletionException.class).hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == REPOSITORY_EXISTS);

    assertThatThrownByWithExpectedException(RepositoryExistsException.class, "repository: rr", () ->
            // It is not allowed to create a new repository whose name is same with the removed repository.
            rule.client().createRepository(rule.project(), rule.removedRepo()).join())
            .isInstanceOf(CompletionException.class).hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == REPOSITORY_EXISTS);

    assertThatThrownByWithExpectedException(
            IllegalArgumentException.class, "invalid repository name: ..", () ->
                    rule.client().createRepository(rule.project(), "..").join())
            .isInstanceOf(CompletionException.class).hasCauseInstanceOf(CentralDogmaException.class)
            .matches(e -> ((CentralDogmaException) e.getCause()).getErrorCode() == BAD_REQUEST);
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:20,代碼來源:RepositoryManagementTest.java


注:本文中的java.util.concurrent.CompletionException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。