Java Code Examples for org.eclipse.microprofile.context.ThreadContext#contextualCallable()

The following examples show how to use org.eclipse.microprofile.context.ThreadContext#contextualCallable() . 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 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 2
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 3
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 4
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the ThreadContext implementation clears context
 * types that are not configured under propagated, unchanged, or cleared.
 *
 * @throws Exception indicates test failure 
 */
@Test
public void clearUnspecifiedContexts() throws Exception {
    ThreadContext threadContext = ThreadContext.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .unchanged(Label.CONTEXT_NAME)
            .cleared()
            .build();
    
    int originalPriority = Thread.currentThread().getPriority();     
    try {
        // Set non-default values
        int newPriority = originalPriority == 3 ? 2 : 3;
        Thread.currentThread().setPriority(newPriority);
        Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-A"));
        Label.set("clearUnspecifiedContexts-test-label-A");

        Callable<Integer> callable = threadContext.contextualCallable(() -> {
                Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-A",
                        "Context type was not propagated to contextual action.");

                Assert.assertEquals(Label.get(), "clearUnspecifiedContexts-test-label-C",
                        "Context type was not left unchanged by contextual action.");

                Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-B"));
                Label.set("clearUnspecifiedContexts-test-label-B");

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

        Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-C"));
        Label.set("clearUnspecifiedContexts-test-label-C");

        Assert.assertEquals(callable.call(), Integer.valueOf(Thread.NORM_PRIORITY),
                "Context type that remained unspecified was not cleared by default.");
        
        Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-C",
                "Previous context (Buffer) was not restored after context was propagated for contextual action.");
        
        Assert.assertEquals(Label.get(), "clearUnspecifiedContexts-test-label-B",
                "Context type was not left unchanged by contextual action.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example 5
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the ThreadContext.Builder can be used to create multiple ThreadContexts with 
 * different configured contexts.
 *
 * @throws Exception indicates test failure
 */
@Test
public void reuseThreadContextBuilder() throws Exception {
    ThreadContext.Builder builder = ThreadContext.builder()
            .propagated()
            .cleared(Buffer.CONTEXT_NAME, THREAD_PRIORITY)
            .unchanged();
    
    ThreadContext clearingContext = builder.build();
    
    ThreadContext propagatingContext = builder.propagated(Buffer.CONTEXT_NAME, THREAD_PRIORITY)
            .cleared()
            .build();

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

        Callable<Integer> clearedCallable = clearingContext.contextualCallable(() -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type that is configured to be cleared was not cleared.");
            
            Buffer.set(new StringBuffer("reuseBuilder-test-buffer-B"));
            
            return Thread.currentThread().getPriority();
        });

        Callable<Integer> propagatedCallable = propagatingContext.contextualCallable(() -> {
            Assert.assertEquals(Buffer.get().toString(), "reuseBuilder-test-buffer-A",
                    "Context type was not propagated to contextual action.");

            Buffer.set(new StringBuffer("reuseBuilder-test-buffer-C"));
            
            return Thread.currentThread().getPriority();
            
        });
        
        Buffer.set(new StringBuffer("reuseBuilder-test-buffer-D"));
        Thread.currentThread().setPriority(newPriority - 1);
        
        Assert.assertEquals(propagatedCallable.call(), Integer.valueOf(newPriority),
                "Context type was not propagated to contextual action.");
        
        Assert.assertEquals(clearedCallable.call(), Integer.valueOf(Thread.NORM_PRIORITY),
                "Context type that is configured to be cleared was not cleared.");

        Assert.assertEquals(Buffer.get().toString(), "reuseBuilder-test-buffer-D",
                "Previous context (Buffer) was not restored after context was propagated for contextual action.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example 6
Source File: ThreadContextTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify the MicroProfile Context Propagation implementation of propagate(), cleared(), and unchanged()
 * for ThreadContext.Builder.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void contextControlsForThreadContextBuilder() throws InterruptedException, ExecutionException, TimeoutException {
    ThreadContext bufferContext = ThreadContext.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .cleared(Label.CONTEXT_NAME)
            .unchanged(THREAD_PRIORITY)
            .build();

    try {
        ThreadContext.builder()
        .propagated(Buffer.CONTEXT_NAME)
        .cleared(Label.CONTEXT_NAME, Buffer.CONTEXT_NAME)
        .unchanged(THREAD_PRIORITY)
        .build();
        Assert.fail("ThreadContext.Builder.build() should throw an IllegalStateException for set overlap between propagated and cleared");
    }
    catch (IllegalStateException ISE) {
        //expected.
    }

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

        Callable<Integer> callable = bufferContext.contextualCallable(() -> {
            Assert.assertEquals(Buffer.get().toString(), "contextControls-test-buffer-A-B",
                    "Context type was not propagated to contextual action.");

            Buffer.get().append("-C");

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

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

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

        Buffer.get().append("-B");
        Label.set("contextControls-test-label-B");

        Future<Integer> future = unmanagedThreads.submit(() -> {
            try {
                Buffer.get().append("unpropagated-buffer");
                Label.set("unpropagated-label");
                Thread.currentThread().setPriority(newPriority);
                
                Integer returnedPriority = callable.call();
                
                Assert.assertEquals(Buffer.get().toString(), "unpropagated-buffer",
                        "Context type was not left unchanged by contextual action.");
                
                Assert.assertEquals(Label.get(), "unpropagated-label",
                        "Context type was not left unchanged by contextual action.");
                
                return returnedPriority;
            }
            finally {
                // Restore original values
                Buffer.set(null);
                Label.set(null);
                Thread.currentThread().setPriority(originalPriority);
            }
        });

        Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(newPriority),
                "Callable returned incorrect value.");

        Assert.assertEquals(Buffer.get().toString(), "contextControls-test-buffer-A-B-C",
                "Context type was not propagated to contextual action.");
    }
    finally {
        // Restore original values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example 7
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * When an already-contextualized Callable 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 contextOfContextualCallableOverridesContextOfManagedExecutor() 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 {
        Callable<String> getBuffer = () -> {
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");
            return Buffer.get().toString();
        };

        Callable<String> getLabel = () -> {
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
            return Label.get();
        };

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

        Callable<String> precontextualizedTask1 = bufferContext.contextualCallable(getBuffer);

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

        Callable<String> precontextualizedTask2 = bufferContext.contextualCallable(getBuffer);

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

        Future<String> future = executor.submit(precontextualizedTask1);
        Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "contextualCallableOverride-buffer-1",
                "Previously captured context type not found on thread.");

        List<Future<String>> futures = executor.invokeAll(
                Arrays.asList(precontextualizedTask2, getLabel, precontextualizedTask1, precontextualizedTask2),
                MAX_WAIT_NS,
                TimeUnit.NANOSECONDS);

        future = futures.get(0);
        Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-2",
                "Previously captured context type not found on thread.");

        future = futures.get(1);
        Assert.assertEquals(future.get(), "contextualCallableOverride-label-3",
                "Context type captured by managed executor not found on thread.");

        future = futures.get(2);
        Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-1",
                "Previously captured context type not found on thread.");

        future = futures.get(3);
        Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-2",
                "Previously captured context type not found on thread.");

        String result = executor.invokeAny(
                Arrays.asList(precontextualizedTask1, precontextualizedTask1),
                MAX_WAIT_NS,
                TimeUnit.NANOSECONDS);
        Assert.assertEquals(result, "contextualCallableOverride-buffer-1",
                "Previously captured context type not found on thread.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}