当前位置: 首页>>代码示例>>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;未经允许,请勿转载。