Java Code Examples for org.eclipse.microprofile.context.ManagedExecutor#newIncompleteFuture()

The following examples show how to use org.eclipse.microprofile.context.ManagedExecutor#newIncompleteFuture() . 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: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * When an already-contextualized Function is specified as the action/task,
 * the action/task runs with its already-captured context rather than
 * capturing and applying context per the configuration of the managed executor.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void contextOfContextualFunctionOverridesContextOfManagedExecutor() throws ExecutionException, InterruptedException, TimeoutException {
    ThreadContext labelContext = ThreadContext.builder()
            .propagated(Label.CONTEXT_NAME)
            .unchanged()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();
    try {
        Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-1"));
        Label.set("contextualFunctionOverride-label-1");

        Function<Integer, Integer> precontextualizedFunction1 = labelContext.contextualFunction(i -> {
            Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-1",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
            return i + 1;
        });

        Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-2"));
        Label.set("contextualFunctionOverride-label-2");

        Function<Integer, Integer> precontextualizedFunction2 = labelContext.contextualFunction(i -> {
            Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-2",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
            return i + 20;
        });

        Function<Throwable, Integer> precontextualizedErrorHandler = labelContext.contextualFunction(failure -> {
            Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-2",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
            return -1;
        });

        Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-3"));
        Label.set("contextualFunctionOverride-label-3");

        Function<Integer, Integer> normalFunction = i -> {
            Assert.assertEquals(Buffer.get().toString(), "contextualFunctionOverride-buffer-3",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");
            return i + 300;
        };

        CompletableFuture<Integer> stage0 = executor.newIncompleteFuture();
        CompletableFuture<Integer> stage1 = stage0.thenApplyAsync(precontextualizedFunction1);

        Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-4"));
        Label.set("contextualFunctionOverride-label-4");

        Function<Integer, CompletableFuture<Integer>> precontextualizedFunction4 = labelContext.contextualFunction(i -> {
            Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-4",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
            return stage1;
        });

        Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-3"));
        Label.set("contextualFunctionOverride-label-3");

        CompletableFuture<Integer> stage2 = stage0.thenComposeAsync(precontextualizedFunction4);
        CompletableFuture<Integer> stage3 = stage2.applyToEither(stage1, precontextualizedFunction2);
        CompletableFuture<Integer> stage4 = stage3.thenApply(normalFunction);
        CompletableFuture<Integer> stage5 = stage4.thenApply(i -> i / (i - 321)) // intentional ArithmeticException for division by 0
                .exceptionally(precontextualizedErrorHandler);

        stage0.complete(0);

        Assert.assertEquals(stage2.join(), Integer.valueOf(1),
                "Unexpected result for completion stage.");

        Assert.assertEquals(stage5.join(), Integer.valueOf(-1),
                "Unexpected result for completion stage.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example 2
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that thread context is captured and propagated per the configuration of the
 * ManagedExecutor builder for all dependent stages of the incomplete future that is created
 * by the ManagedExecutor's newIncompleteFuture implementation. Thread context is captured
 * at each point where a dependent stage is added, rather than solely upon creation of the
 * initial stage or construction of the builder.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 */
@Test
public void newIncompleteFutureDependentStagesRunWithContext() throws ExecutionException, InterruptedException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Label.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        CompletableFuture<Integer> stage1 = executor.newIncompleteFuture();

        Assert.assertFalse(stage1.isDone(),
                "Completable future created by newIncompleteFuture did not start out as incomplete.");

        // Set non-default values
        Buffer.get().append("newIncompleteFuture-test-buffer");
        Label.set("newIncompleteFuture-test-label-A");

        CompletableFuture<Integer> stage2 = stage1.thenApply(i -> {
            Assert.assertEquals(i, Integer.valueOf(10),
                    "Value supplied to second stage was lost or altered.");

            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

            Assert.assertEquals(Label.get(), "newIncompleteFuture-test-label-A",
                    "Context type was not correctly propagated to contextual action.");
            
            return i * 2;
        });

        Label.set("newIncompleteFuture-test-label-B");

        CompletableFuture<Integer> stage3 = stage2.thenApply(i -> {
            Assert.assertEquals(i, Integer.valueOf(20),
                    "Value supplied to third stage was lost or altered.");

            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

            Assert.assertEquals(Label.get(), "newIncompleteFuture-test-label-B",
                    "Context type was not correctly propagated to contextual action.");
            
            return i + 10;
        });

        Label.set("newIncompleteFuture-test-label-C");

        // To avoid the possibility that CompletableFuture.get might cause the action to run
        // on the current thread, which would bypass the intent of testing context propagation,
        // use a countdown latch to independently wait for completion.
        CountDownLatch completed = new CountDownLatch(1);
        stage3.whenComplete((result, failure) -> completed.countDown());

        Assert.assertTrue(stage1.complete(10),
                "Unable to complete the future that was created by newIncompleteFuture.");

        Assert.assertTrue(completed.await(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
                "Completable future did not finish in a reasonable amount of time.");

        Assert.assertTrue(stage1.isDone(), "First stage did not transition to done upon completion.");
        Assert.assertTrue(stage2.isDone(), "Second stage did not transition to done upon completion.");
        Assert.assertTrue(stage3.isDone(), "Third stage did not transition to done upon completion.");

        Assert.assertEquals(stage1.get(), Integer.valueOf(10),
                "Result of first stage does not match the value with which it was completed.");

        Assert.assertEquals(stage2.getNow(22), Integer.valueOf(20),
                "Result of second stage was lost or altered.");

        Assert.assertEquals(stage3.join(), Integer.valueOf(30),
                "Result of third stage was lost or altered.");

        Assert.assertFalse(stage1.isCompletedExceptionally(), "First stage should not report exceptional completion.");
        Assert.assertFalse(stage2.isCompletedExceptionally(), "Second stage should not report exceptional completion.");
        Assert.assertFalse(stage3.isCompletedExceptionally(), "Third stage should not report exceptional completion.");

        // Is context properly restored on current thread?
        Assert.assertEquals(Buffer.get().toString(), "newIncompleteFuture-test-buffer",
                "Previous context was not restored after context was cleared for managed executor tasks.");
        Assert.assertEquals(Label.get(), "newIncompleteFuture-test-label-C",
                "Previous context was not restored after context was propagated for managed executor tasks.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}