org.eclipse.microprofile.context.ThreadContext Java Examples

The following examples show how to use org.eclipse.microprofile.context.ThreadContext. 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: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Request scoped bean and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesRequestScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(RequestScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-REQUEST", propagateCDI,
                selectedInstance.get());
    } 
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #2
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Session scoped bean and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesSessionScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(SessionScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-SESSION", propagateCDI,
                selectedInstance.get());
    }
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #3
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Conversation scoped beans and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesConversationScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(ConversationScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<ConversationScopedBean> selectedInstance = instance.select(ConversationScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-CONVERSATION", propagateCDI,
                selectedInstance.get());
    }
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #4
Source File: MPConfigBean.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
@Inject
protected void setContextSnapshot(@Named("producedThreadContext") ThreadContext contextPropagator) {
    int originalPriority = Thread.currentThread().getPriority();
    int newPriority = originalPriority == 4 ? 3 : 4;
    Thread.currentThread().setPriority(newPriority);
    Label.set("setContextSnapshot-test-label");
    Buffer.set(new StringBuffer("setContextSnapshot-test-buffer"));
    try {
        contextSnapshot = contextPropagator.currentContextExecutor();
    }
    finally {
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #5
Source File: CdiBeanProducer.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
@Produces
@ApplicationScoped
@CDIBean.Priority3Executor
public Executor createPriority3Executor(@CDIBean.PriorityContext ThreadContext ctx) {
    int originalPriority = Thread.currentThread().getPriority();
    try {
        Thread.currentThread().setPriority(3);
        Label.set("do-not-propagate-this-label");
        Buffer.set(new StringBuffer("do-not-propagate-this-buffer"));

        return ctx.currentContextExecutor();
    } finally {
        // restore previous values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #6
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Request scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsRequestScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(RequestScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-REQUEST", propagatedNone,
                selectedInstance.get());
    } 
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #7
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Session scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsSessionScopedBeans() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(SessionScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class);
    assertTrue(selectedInstance.isResolvable());

    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-SESSION", propagatedNone,
                selectedInstance.get());
    }
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #8
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
private boolean callServiceExpectFailure(String txType,
                                      TransactionalServiceCall<TransactionalService> op,
                                      TransactionalService ts) {
    try {
        ThreadContext.builder()
                .propagated()
                .cleared(ThreadContext.TRANSACTION)
                .unchanged(ThreadContext.ALL_REMAINING)
                .build().contextualRunnable(() -> callServiceWithoutContextExpectFailure(op, ts)).run();

        return true;
    }
    catch (IllegalStateException e) {
        System.out.printf("Skipping testTransactionPropagation for %s. Transaction context propagation is not supported.%n",
                txType);
        return false;
    }
}
 
Example #9
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Conversation scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsConversationScopedBeans() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(ConversationScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<ConversationScopedBean> selectedInstance = instance.select(ConversationScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-CONVERSATION", propagatedNone,
                selectedInstance.get());
    }
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #10
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on a request scoped bean, then verify a contextualized callable
 * has the state cleared from it when ran on the same thread.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDITCCtxClear() throws Exception {
    ThreadContext clearAllCtx = ThreadContext.builder()
                    .propagated() // propagate nothing
                    .cleared(ThreadContext.ALL_REMAINING)
                    .unchanged()
                    .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    RequestScopedBean requestBean = selectedInstance.get();
    requestBean.setState("testCDIThreadCtxClear-STATE1");
    Callable<String> getState = clearAllCtx.contextualCallable(() -> {
        String state = requestBean.getState();
        return state;
    });
    assertEquals(getState.call(), "UNINITIALIZED");
}
 
Example #11
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on a request scoped bean, then verify a contextualized callable
 * has the state propagated to it when ran on the same thread.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDITCCtxPropagate() throws Exception {
    ThreadContext defaultTC = ThreadContext.builder()
                                           .propagated(ThreadContext.CDI)
                                           .cleared(ThreadContext.ALL_REMAINING)
                                           .unchanged()
                                           .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    RequestScopedBean requestBean = selectedInstance.get();
    requestBean.setState("testCDIContextPropagate-STATE2");
    Callable<String> getState = defaultTC.contextualCallable(() -> {
        String state = requestBean.getState();
        return state;
    });
    assertEquals(getState.call(), "testCDIContextPropagate-STATE2");
}
 
Example #12
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that thread context is cleared per the configuration of the ManagedExecutor builder
 * for all tasks that are executed via the execute method. This test supplies the ManagedExecutor
 * to a Java SE CompletableFuture, which invokes the execute method to run tasks asynchronously.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void executedTaskRunsWithClearedContext() throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        Buffer.set(new StringBuffer("executed-task-test-buffer-A"));
        Label.set("executed-task-test-label-A");

        CompletableFuture<Integer> cf1 = new CompletableFuture<Integer>();

        CompletableFuture<Void> cf2 = cf1.thenAcceptAsync(i -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

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

            Label.set("executed-task-test-label-B");
        }, executor);

        cf1.complete(1000);

        cf2.join();

        Assert.assertEquals(Buffer.get().toString(), "executed-task-test-buffer-A",
                "Context unexpectedly changed on thread.");
        Assert.assertEquals(Label.get(), "executed-task-test-label-A",
                "Context unexpectedly changed on thread.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #13
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that dependent stages created via withContextCapture can be completed independently
 * of the original stage.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 */
@Test
public void withContextCaptureDependentStageForcedCompletion() throws ExecutionException, InterruptedException {
    ThreadContext contextPropagator = ThreadContext.builder()
            .propagated()
            .unchanged()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    CompletableFuture<String> stage1 = new CompletableFuture<String>();
    CompletableFuture<String> stage2 = contextPropagator.withContextCapture(stage1);

    Assert.assertTrue(stage2.complete("stage_2_done"),
            "It should be possible to complete a CompletableFuture created via withContextCapture without completing the original stage.");

    Assert.assertFalse(stage1.isDone(),
            "Completion of the dependent stage must not imply completion of the original stage.");

    Assert.assertTrue(stage1.complete("stage_1_done"),
            "It should be possible to complete the original stage with a different result after dependent stage was forcibly completed.");

    Assert.assertEquals(stage1.get(), "stage_1_done",
            "Completion stage result does not match the result with which it was forcibly completed.");

    Assert.assertEquals(stage2.get(), "stage_2_done",
            "Completion stage result does not match the result with which it was forcibly completed.");
}
 
Example #14
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunWithTxnOfExecutingThread() throws SystemException, NotSupportedException {
    ThreadContext threadContext = ThreadContext.builder()
            .propagated()
            .unchanged(ThreadContext.TRANSACTION)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    UserTransaction ut = getUserTransaction("testRunWithTxnOfExecutingThread");

    if (threadContext == null || ut == null) {
        return; // the implementation does not support transaction propagation
    }

    Callable<Boolean> isInTransaction =
            threadContext.contextualCallable(() -> ut.getStatus() == Status.STATUS_ACTIVE);

    ut.begin();

    try {
        Assert.assertTrue(isInTransaction.call());
    }
    catch (Exception e) {
        Assert.fail("testRunWithTxnOfExecutingThread: a transaction should have been active");
    }
    finally {
        ut.rollback();
    }
}
 
Example #15
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that the ThreadContext's contextualCallable
 * method can be used to wrap a Callable instance with the context that is captured from the
 * current thread per the configuration of the ThreadContext builder, and that the context is
 * applied when the Callable call method runs. This test case aligns with use case of
 * supplying a contextual Callable to an unmanaged executor that is otherwise not context-aware.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void contextualCallableRunsWithContext()
        throws ExecutionException, InterruptedException, TimeoutException {
    ThreadContext priorityContext = ThreadContext.builder()
            .propagated(THREAD_PRIORITY)
            .unchanged()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    int originalPriority = Thread.currentThread().getPriority();
    try {
        // Set non-default values
        int newPriority = originalPriority == 4 ? 3 : 4;
        Thread.currentThread().setPriority(newPriority);
        Buffer.get().append("contextualCallable-test-buffer");
        Label.set("contextualCallable-test-label");

        Future<Integer> future = unmanagedThreads.submit(priorityContext.contextualCallable(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type (Buffer) that is configured to be cleared was not cleared.");

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

            return Thread.currentThread().getPriority();
        }));

        Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(newPriority),
                "Callable returned incorrect value.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #16
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
private ManagedExecutor createExecutor(String testName) {
    try {
        return ManagedExecutor.builder()
                .maxAsync(2)
                .propagated(ThreadContext.TRANSACTION)
                .cleared(ThreadContext.ALL_REMAINING)
                .build();
    }
    catch (IllegalStateException x) {
        System.out.printf("Skipping test %s. Transaction context propagation is not supported.%n",
                testName);
        return null;
    }
}
 
Example #17
Source File: CdiBeanProducer.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
@CDIBean.AppProducedExecutor
public ManagedExecutor createExec() {
    return ManagedExecutor.builder().cleared(ThreadContext.TRANSACTION).propagated(ThreadContext.ALL_REMAINING).build();
}
 
Example #18
Source File: ProducerBean.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public ThreadContext getAllThreadContext() {
    return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
 
Example #19
Source File: ArcContextProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public String getThreadContextType() {
    return ThreadContext.CDI;
}
 
Example #20
Source File: SmallRyeContextPropagationProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Produces
@Singleton
@DefaultBean
public ThreadContext getAllThreadContext() {
    return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
}
 
Example #21
Source File: MPConfigTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the cleared and propagated attributes of a ThreadContext are defaulted
 * according to the defaults specified by the application in MicroProfile Config.
 */
@Test
public void defaultContextPropagationForThreadContextViaMPConfig() {
    // Expected config is propagated={}; cleared=Buffer; unchanged=Remaining
    ThreadContext threadContext = ThreadContext.builder().build();

    int originalPriority = Thread.currentThread().getPriority();
    try {
        // Set non-default value
        Buffer.set(new StringBuffer("defaultContextPropagationForThreadContextViaMPConfig-test-buffer-A"));
        int newPriority = originalPriority == 3 ? 2 : 3;

        Runnable task = threadContext.contextualRunnable(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that MicroProfile config defaults to be cleared was not cleared.");

            Assert.assertEquals(Thread.currentThread().getPriority(), newPriority,
                    "Context type (ThreadPriority) that MicroProfile Config defaults to remain unchanged was changed.");

            Assert.assertEquals(Label.get(), "defaultContextPropagationForThreadContextViaMPConfig-test-label-B",
                    "Context type (Label) that MicroProfile Config defaults to remain unchanged was changed.");

            Label.set("defaultContextPropagationForThreadContextViaMPConfig-test-label-A");
        });

        // Set non-default values
        Thread.currentThread().setPriority(newPriority);
        Label.set("defaultContextPropagationForThreadContextViaMPConfig-test-label-B");

        task.run();

        Assert.assertEquals(Label.get(), "defaultContextPropagationForThreadContextViaMPConfig-test-label-A",
                "Context type that MicroProfile Config defaults to remain unchanged was changed when task completed.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #22
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 one or more tasks that are submitted via the ManagedExecutor's
 * untimed invokeAny operation. Thread context is captured at the point where invokeAny is
 * invoked, rather than upon creation of the executor or construction of the builder.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void untimedInvokeAnyRunsTasksWithContext()
        throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .maxAsync(1)
            .propagated(Label.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        // Set non-default values
        Buffer.set(new StringBuffer("untimed-invokeAny-test-buffer-A"));
        Label.set("untimed-invokeAny-test-label-A");

        String result = executor.invokeAny(Arrays.<Callable<String>>asList(
                () -> {
                    Assert.assertEquals(Label.get(), "untimed-invokeAny-test-label-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("untimed-invokeAny-test-label-B");
                    Buffer.set(new StringBuffer("untimed-invokeAny-test-buffer-B"));
                    return "Bb";
                },
                () -> {
                    Assert.assertEquals(Label.get(), "untimed-invokeAny-test-label-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("untimed-invokeAny-test-label-C");
                    Buffer.set(new StringBuffer("uninvokeAny-test-buffer-C"));
                    return "Cc";
                },
                () -> {
                    Assert.assertEquals(Label.get(), "untimed-invokeAny-test-label-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("untimed-invokeAny-test-label-D");
                    Buffer.set(new StringBuffer("untimed-invokeAny-test-buffer-D"));
                    return "Dd";
                }),
                MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        Assert.assertTrue("Bb".equals(result) || "Cc".equals(result) || "Dd".equals(result),
                "Result of invokeAny, " + result + ", does not match the result of any of the tasks.");

        Assert.assertEquals(Label.get(), "untimed-invokeAny-test-label-A",
                "Previous context was not restored after context was propagated for managed executor tasks.");
        Assert.assertEquals(Buffer.get().toString(), "untimed-invokeAny-test-buffer-A",
                "Previous context was not restored after context was cleared for managed executor tasks.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #23
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 one or more tasks that are submitted via the ManagedExecutor's
 * timed invokeAny operation. Thread context is captured at the point where invokeAny is
 * invoked, rather than upon creation of the executor or construction of the builder.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void timedInvokeAnyRunsTaskWithContext()
        throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        // Set non-default values
        Buffer.set(new StringBuffer("timed-invokeAny-test-buffer-A"));
        Label.set("timed-invokeAny-test-label-A");

        Character result = executor.invokeAny(Arrays.<Callable<Character>>asList(
                () -> {
                    Assert.assertEquals(Buffer.get().toString(), "timed-invokeAny-test-buffer-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("timed-invokeAny-test-label-B");
                    Buffer.set(new StringBuffer("timed-invokeAny-test-buffer-B"));
                    return 'b';
                },
                () -> {
                    Assert.assertEquals(Buffer.get().toString(), "timed-invokeAny-test-buffer-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("timed-invokeAny-test-label-C");
                    Buffer.set(new StringBuffer("invokeAny-test-buffer-C"));
                    return 'c';
                }),
                MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        Assert.assertTrue(Character.valueOf('b').equals(result) || Character.valueOf('c').equals(result),
                "Result of invokeAny, " + result + ", does not match the result of either of the tasks.");

        Assert.assertEquals(Label.get(), "timed-invokeAny-test-label-A",
                "Previous context was not restored after context was propagated for managed executor tasks.");
        Assert.assertEquals(Buffer.get().toString(), "timed-invokeAny-test-buffer-A",
                "Previous context was not restored after context was cleared for managed executor tasks.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #24
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 tasks that are submitted via the ManagedExecutor's
 * timed invokeAll operation. Thread context is captured at the point where invokeAll is
 * invoked, rather than upon creation of the executor or construction of the builder.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void timedInvokeAllRunsTasksWithContext()
        throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        // Set non-default values
        Buffer.set(new StringBuffer("timed-invokeAll-test-buffer-A"));
        Label.set("timed-invokeAll-test-label-A");

        List<Future<String>> futures = executor.invokeAll(Arrays.<Callable<String>>asList(
                () -> {
                    Assert.assertEquals(Buffer.get().toString(), "timed-invokeAll-test-buffer-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("timed-invokeAll-test-label-B");
                    Buffer.set(new StringBuffer("timed-invokeAll-test-buffer-B"));
                    return "B";
                },
                () -> {
                    Assert.assertEquals(Buffer.get().toString(), "timed-invokeAll-test-buffer-A",
                            "Context type was not propagated to contextual action.");

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

                    Label.set("timed-invokeAll-test-label-C");
                    Buffer.set(new StringBuffer("invokeAll-test-buffer-C"));
                    return "C";
                }),
                MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        Assert.assertEquals(futures.size(), 2,
                "Number of futures does not match the number of tasks. " + futures);

        Assert.assertTrue(futures.get(0).isDone(),
                "Future for first task does not indicate it is done after invokeAll.");
        Assert.assertEquals(futures.get(0).get(), "B",
                "Future for first task returned wrong value.");

        Assert.assertTrue(futures.get(1).isDone(),
                "Future for second task does not indicate it is done after invokeAll.");
        Assert.assertEquals(futures.get(1).get(1, TimeUnit.SECONDS), "C",
                "Future for second task returned wrong value.");

        Assert.assertEquals(Label.get(), "timed-invokeAll-test-label-A",
                "Previous context was not restored after context was propagated for managed executor tasks.");
        Assert.assertEquals(Buffer.get().toString(), "timed-invokeAll-test-buffer-A",
                "Previous context was not restored after context was cleared for managed executor tasks.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #25
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 tasks that are submitted via the submit(Callable),
 * submit(Runnable) and submit(Runnable, result) methods.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void submittedTasksRunWithContext() throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Label.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    try {
        Buffer.set(new StringBuffer("submitted-tasks-test-buffer-A"));
        Label.set("submitted-tasks-test-label-A");

        Future<?> futureA = executor.submit(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

            Assert.assertEquals(Label.get(), "submitted-tasks-test-label-A",
                    "Context type was not correctly propagated to contextual action.");

            throw new Error("Fake error intentionally raised by test Runnable.");
        });

        Label.set("submitted-tasks-test-label-B");

        Future<String> futureB = executor.submit(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

            Assert.assertEquals(Label.get(), "submitted-tasks-test-label-B",
                    "Context type was not correctly propagated to contextual action.");
        }, "Task-B-Result");

        Label.set("submitted-tasks-test-label-C");

        Future<String> futureC = executor.submit(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");

            Assert.assertEquals(Label.get(), "submitted-tasks-test-label-C",
                    "Context type was not correctly propagated to contextual action.");

            return "Task-C-Result";
        });

        try {
            Object result = futureA.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
            Assert.fail("Result of " + result + " returned for Runnable that throws an Error.");
        }
        catch (ExecutionException x) {
            if (x.getCause() == null
                    || (!(x.getCause() instanceof Error))
                    || (!"Fake error intentionally raised by test Runnable.".equals(x.getCause().getMessage()))) {
                throw x;
            }
        }

        Assert.assertEquals("Task-B-Result", futureB.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
                "Result does not match the predetermined result that was specified when submitting the Runnable.");

        Assert.assertEquals("Task-C-Result", futureC.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
                "Result does not match the result returned by the Callable.");

        Assert.assertTrue(futureA.isDone(),
                "Future for first Runnable should report being done after test case awaits its completion.");

        Assert.assertTrue(futureB.isDone(),
                "Future for second Runnable should report being done after test case awaits its completion.");

        Assert.assertTrue(futureC.isDone(),
                "Future for Callable should report being done after test case awaits its completion.");

        Assert.assertFalse(futureA.isCancelled(),
                "Future for first Runnable should not be canceled because the test case did not cancel it.");

        Assert.assertFalse(futureB.isCancelled(),
                "Future for second Runnable should not be canceled because the test case did not cancel it.");

        Assert.assertFalse(futureC.isCancelled(),
                "Future for Callable should not be canceled because the test case did not cancel it.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #26
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);
    }
}
 
Example #27
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the ManagedExecutor implementation starts 2 async tasks/actions, and no more,
 * when maxAsync is configured to 2.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void maxAsync2() throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .maxAsync(2)
            .propagated()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Phaser barrier = new Phaser(2);
    try {
        // Use up both maxAsync slots on blocking operations and wait for them to start
        Future<Integer> future1 = executor.submit(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
        CompletableFuture<Integer> future2 = executor.supplyAsync(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
        barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        // This data structure holds the results of tasks which shouldn't be able to run yet
        LinkedBlockingQueue<String> results = new LinkedBlockingQueue<String>();

        // Submit additional tasks/actions for async execution.
        // These should queue, but otherwise be unable to start yet due to maxAsync=2.
        CompletableFuture<Void> future3 = executor.runAsync(() -> results.offer("Result3"));
        CompletableFuture<Boolean> future4 = executor.supplyAsync(() -> results.offer("Result4"));
        Future<Boolean> future5 = executor.submit(() -> results.offer("Result5"));
        CompletableFuture<Boolean> future6 = executor.completedFuture("6")
                .thenApplyAsync(s -> results.offer("Result" + s));

        // Detect whether any of the above tasks/actions run within the next 5 seconds
        Assert.assertNull(results.poll(5, TimeUnit.SECONDS),
                "Should not be able start more than 2 async tasks when maxAsync is 2.");

        // unblock and allow tasks to finish
        barrier.arrive();
        barrier.arrive(); // there are 2 parties in each phase

        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "None of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 1 of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 2 of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 3 of the queued tasks ran.");

        Assert.assertEquals(future1.get(), Integer.valueOf(2), "Unexpected result of first task.");
        Assert.assertEquals(future2.get(), Integer.valueOf(2), "Unexpected result of second task.");
        Assert.assertNull(future3.join(), "Unexpected result of third task.");
        Assert.assertEquals(future4.join(), Boolean.TRUE, "Unexpected result of fourth task.");
        Assert.assertEquals(future5.get(), Boolean.TRUE, "Unexpected result of fifth task.");
        Assert.assertEquals(future6.get(), Boolean.TRUE, "Unexpected result of sixth task.");
    }
    finally {
        barrier.forceTermination();
        executor.shutdownNow();
    }
}
 
Example #28
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * When an already-contextualized Supplier or BiFunction 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 contextOfContextualSuppplierAndBiConsumerOverrideContextOfManagedExecutor()
        throws ExecutionException, InterruptedException, TimeoutException {
    ThreadContext bufferContext = ThreadContext.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .unchanged()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Label.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();
    try {
        Supplier<String> getBuffer = () -> {
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");
            return Buffer.get().toString();
        };

        Buffer.set(new StringBuffer("contextualSupplierOverride-buffer-1"));
        Label.set("contextualSupplierOverride-label-1");

        Supplier<String> precontextualizedSupplier1 = bufferContext.contextualSupplier(getBuffer);

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

        Supplier<String> precontextualizedSupplier2 = bufferContext.contextualSupplier(getBuffer);

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

        BiConsumer<String, String> precontextualizedConsumer3 = bufferContext.contextualConsumer((b1, b2) -> {
            Assert.assertEquals(Buffer.get().toString(), "contextualBiConsumerOverride-buffer-3",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");

            Assert.assertEquals(b1, "contextualSupplierOverride-buffer-1",
                    "Previously captured context type not found on Supplier's thread.");

            Assert.assertEquals(b2, "contextualSupplierOverride-buffer-2",
                    "Previously captured context type not found on Supplier's thread.");
        });

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

        BiConsumer<Void, Throwable> precontextualizedConsumer4 = bufferContext.contextualConsumer((unused, failure) -> {
            Assert.assertEquals(Buffer.get().toString(), "contextualBiConsumerOverride-buffer-4",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");
        });

        Buffer.set(new StringBuffer("contextualSupplierAndBiConsumerOverride-buffer-5"));
        Label.set("contextualSupplierAndBiConsumerOverride-label-5");

        CompletableFuture<String> stage1 = executor.supplyAsync(precontextualizedSupplier1);
        CompletableFuture<String> stage2 = executor.supplyAsync(precontextualizedSupplier2);
        CompletableFuture<Void> stage3 = stage1.thenAcceptBoth(stage2, precontextualizedConsumer3);
        CompletableFuture<Void> stage4 = stage3.whenCompleteAsync(precontextualizedConsumer4);
        CompletableFuture<Void> stage5 = stage4.whenComplete((unused, failure) -> {
            Assert.assertEquals(Label.get(), "contextualSupplierAndBiConsumerOverride-label-5",
                    "Context type captured by managed executor not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
        });

        stage5.join();
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example #29
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * It is optional to specify the set of unchanged context. In absence of any specified value
 * and if MicroProfile Config is not used to override the default, the unchanged context list
 * defaults to empty.
 */
@Test
public void unchangedContextListDefaultsToEmpty() {
    ThreadContext labelContext = ThreadContext.builder()
            .propagated(Label.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    int originalPriority = Thread.currentThread().getPriority();
    int newPriority = originalPriority == 3 ? 2 : 3; // a non-default value
    try {
        // Set non-default values
        Buffer.get().append("test-unchangedContextListDefaultsToEmpty-buffer-A");
        Label.set("test-unchangedContextListDefaultsToEmpty-label-A");
        Thread.currentThread().setPriority(newPriority);

        Runnable testPropagateLabelContextAndClearOthers = labelContext.contextualRunnable(() -> {
            Assert.assertEquals(Label.get(), "test-unchangedContextListDefaultsToEmpty-label-A",
                    "Context type was not propagated to contextual action.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type (Buffer) that is defaulted to be cleared was not cleared.");
            Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
                    "Context type (ThreadContext) that is defaulted to be cleared was not cleared.");
        });

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

        testPropagateLabelContextAndClearOthers.run();

        // Has context been properly restored after the contextual operation?
        Assert.assertEquals(Buffer.get().toString(), "test-unchangedContextListDefaultsToEmpty-buffer-A",
                "Previous context (Buffer) was not restored after context was cleared for contextual action.");
        Assert.assertEquals(Label.get(), "test-unchangedContextListDefaultsToEmpty-label-B",
                "Previous context (Label) was not restored after context was propagated for contextual action.");
        Assert.assertEquals(Thread.currentThread().getPriority(), newPriority,
                "Previous context (ThreadPriority) was not restored after context was propagated for contextual action.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #30
Source File: ContextPropagatingScheduledExecutorService.java    From smallrye-fault-tolerance with Apache License 2.0 4 votes vote down vote up
ContextPropagatingScheduledExecutorService(ThreadContext threadContext, ScheduledExecutorService delegate) {
    this.threadContext = threadContext;
    this.delegate = delegate;
}