From 4b79b4bd739c016773a34d7bd5cd108e5a1d8381 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 25 Oct 2024 12:03:04 +0200 Subject: [PATCH 01/41] Start a new branch for next major release Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 2 +- context-propagation-java8/pom.xml | 2 +- context-propagation-metrics/pom.xml | 2 +- context-propagation-micrometer/pom.xml | 2 +- context-propagation/pom.xml | 2 +- locale-context/pom.xml | 2 +- log4j2-propagation/pom.xml | 2 +- opentracing-span-propagation/pom.xml | 2 +- pom.xml | 2 +- readme.md | 8 ++++++++ servletrequest-propagation/pom.xml | 2 +- slf4j-propagation/pom.xml | 2 +- spring-security-context/pom.xml | 2 +- 13 files changed, 20 insertions(+), 12 deletions(-) diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 7c83b745..cbed04c5 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -22,7 +22,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT context-propagation-bom diff --git a/context-propagation-java8/pom.xml b/context-propagation-java8/pom.xml index a710147d..24c76822 100644 --- a/context-propagation-java8/pom.xml +++ b/context-propagation-java8/pom.xml @@ -24,7 +24,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/context-propagation-metrics/pom.xml b/context-propagation-metrics/pom.xml index fcd6e541..d6002514 100644 --- a/context-propagation-metrics/pom.xml +++ b/context-propagation-metrics/pom.xml @@ -24,7 +24,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/context-propagation-micrometer/pom.xml b/context-propagation-micrometer/pom.xml index 9b36cb10..ab00690e 100644 --- a/context-propagation-micrometer/pom.xml +++ b/context-propagation-micrometer/pom.xml @@ -24,7 +24,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/context-propagation/pom.xml b/context-propagation/pom.xml index b9af9506..1e8e6c4a 100644 --- a/context-propagation/pom.xml +++ b/context-propagation/pom.xml @@ -23,7 +23,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/locale-context/pom.xml b/locale-context/pom.xml index 327f220f..065d46f2 100644 --- a/locale-context/pom.xml +++ b/locale-context/pom.xml @@ -22,7 +22,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/log4j2-propagation/pom.xml b/log4j2-propagation/pom.xml index a4f05db9..5d467776 100644 --- a/log4j2-propagation/pom.xml +++ b/log4j2-propagation/pom.xml @@ -22,7 +22,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/opentracing-span-propagation/pom.xml b/opentracing-span-propagation/pom.xml index 959da659..f81e1464 100644 --- a/opentracing-span-propagation/pom.xml +++ b/opentracing-span-propagation/pom.xml @@ -24,7 +24,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/pom.xml b/pom.xml index fe1324da..a85e4f8f 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT pom diff --git a/readme.md b/readme.md index b2b901fb..b93007ee 100644 --- a/readme.md +++ b/readme.md @@ -3,6 +3,14 @@ [![Maven Version][maven-img]][maven] [![Javadoc][javadoc-img]][javadoc] +> [!IMPORTANT] +> This is the development branch for the v2 version of this library. +> All breaking changes and improvements to the library go in this branch +> - Java version bumped to Java8 mimimum +> - `ContextManager.getActiveContext()` replaced by `getActiveContextValue()`. +> - `ContextManager.clear()` will require an implementation. +> - All `@Deprecated(forRemoval=true)` is to be removed. + # Context propagation library Propagate a snapshot of one or more `ThreadLocal` values into another thread. diff --git a/servletrequest-propagation/pom.xml b/servletrequest-propagation/pom.xml index fb06865a..eb3d23ff 100644 --- a/servletrequest-propagation/pom.xml +++ b/servletrequest-propagation/pom.xml @@ -24,7 +24,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/slf4j-propagation/pom.xml b/slf4j-propagation/pom.xml index 49a860d9..136ecb39 100644 --- a/slf4j-propagation/pom.xml +++ b/slf4j-propagation/pom.xml @@ -22,7 +22,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT diff --git a/spring-security-context/pom.xml b/spring-security-context/pom.xml index 62d5ee55..8a6f2914 100644 --- a/spring-security-context/pom.xml +++ b/spring-security-context/pom.xml @@ -22,7 +22,7 @@ nl.talsmasoftware.context context-propagation-root - 1.1.1-SNAPSHOT + 2.0.0-SNAPSHOT From 64e9f2a74a098e3e58ce400ab01d2a3ddd5312c8 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 25 Oct 2024 13:53:40 +0200 Subject: [PATCH 02/41] Update readme.md --- readme.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index b93007ee..01230e98 100644 --- a/readme.md +++ b/readme.md @@ -4,8 +4,13 @@ [![Javadoc][javadoc-img]][javadoc] > [!IMPORTANT] +> Main focus of the 'v2' version is simplification of this library. +> In the past, many features have been added to the library. Some features introduced more complexity than technically needed. +> Due to the fact that we use semantic versioning and therefore can't break functionality for the sake of simplicity +> we must take advantage of the next major version to do some api redesign that will allow simpler implementations. +> > This is the development branch for the v2 version of this library. -> All breaking changes and improvements to the library go in this branch +> All breaking changes to the library must go in this branch. > - Java version bumped to Java8 mimimum > - `ContextManager.getActiveContext()` replaced by `getActiveContextValue()`. > - `ContextManager.clear()` will require an implementation. From 58c2b918ff95db1953a2f0320fa9d8575accc2f4 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 25 Oct 2024 13:57:05 +0200 Subject: [PATCH 03/41] Update readme.md --- readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 01230e98..395ebb2b 100644 --- a/readme.md +++ b/readme.md @@ -5,9 +5,9 @@ > [!IMPORTANT] > Main focus of the 'v2' version is simplification of this library. -> In the past, many features have been added to the library. Some features introduced more complexity than technically needed. -> Due to the fact that we use semantic versioning and therefore can't break functionality for the sake of simplicity -> we must take advantage of the next major version to do some api redesign that will allow simpler implementations. +> In the past, many features were added to the library. Some introduced more complexity than technically needed. +> Due to semantic versioning we can't break functionality for the sake of simplicity. +> So for v2 we must redesign some api elements that allow simpler implementation, reducing complexity. > > This is the development branch for the v2 version of this library. > All breaking changes to the library must go in this branch. From 8a47c52028038cc79993dbc90069d3ba51271600 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Sat, 2 Nov 2024 13:14:25 +0100 Subject: [PATCH 04/41] Remove deprecated Context interface. Signed-off-by: Sjoerd Talsma --- .../core/function/BiConsumerWithContext.java | 11 ++- .../core/function/BiFunctionWithContext.java | 11 ++- .../core/function/BiPredicateWithContext.java | 15 +++- .../function/BooleanSupplierWithContext.java | 7 +- .../core/function/ConsumerWithContext.java | 11 ++- .../core/function/FunctionWithContext.java | 15 +++- .../core/function/PredicateWithContext.java | 15 +++- .../core/function/RunnableWithContext.java | 7 +- .../core/function/SupplierWithContext.java | 7 +- .../context/DummyContextManager.java | 5 +- .../ContextAwareCompletableFutureTest.java | 2 +- .../functions/BiConsumerWithContextTest.java | 22 ++++-- .../functions/BiFunctionWithContextTest.java | 10 ++- .../functions/BiPredicateWithContextTest.java | 10 ++- .../BinaryOperatorWithContextTest.java | 10 ++- .../BooleanSupplierWithContextTest.java | 9 ++- .../functions/ConsumerWithContextTest.java | 22 ++++-- .../functions/FunctionWithContextTest.java | 10 ++- .../functions/PredicateWithContextTest.java | 10 ++- .../functions/RunnableWithContextTest.java | 10 ++- .../functions/SupplierWithContextTest.java | 10 ++- .../UnaryOperatorWithContextTest.java | 10 ++- .../ContextAwareCompletableFutureTest.java | 2 +- .../nl/talsmasoftware/context/Context.java | 73 ------------------- .../context/ContextManager.java | 2 + .../context/ContextManagers.java | 6 +- .../context/ContextSnapshot.java | 12 +-- .../talsmasoftware/context/api/Context.java | 2 +- .../context/api/ContextSnapshot.java | 1 - .../context/core/ContextManagers.java | 2 +- .../ContextAwareExecutorService.java | 6 +- .../AbstractThreadLocalContext.java | 2 +- .../context/observer/package-info.java | 6 +- .../talsmasoftware/context/package-info.java | 10 +-- .../AbstractThreadLocalContext.java | 2 +- .../context/ContextManagersTest.java | 13 ++-- .../context/ContextSnapshotTest.java | 12 +-- .../talsmasoftware/context/DummyContext.java | 3 +- .../context/DummyContextManager.java | 2 + .../context/NoContextManagersTest.java | 13 ++-- .../context/ThrowingContextManager.java | 3 +- .../AutoInitializingContextManager.java | 4 +- .../ClearableDummyContextManager.java | 4 +- .../DummyManagerOfClearableContext.java | 4 +- .../context/core/ContextObserversTest.java | 2 +- .../ContextAwareExecutorServiceTest.java | 4 +- .../observer/ContextObserversTest.java | 4 +- .../observer/DeprecatedContextManager.java | 4 +- .../observer/ThrowingContextObserverTest.java | 4 +- .../context/locale/LocaleContextManager.java | 4 +- .../locale/LocaleContextManagerTest.java | 4 +- .../Log4j2ThreadContextManager.java | 4 +- .../Log4j2ThreadContextManagerTest.java | 10 ++- .../opentracing/ContextScopeManager.java | 4 +- .../context/opentracing/SpanManager.java | 4 +- .../opentracing/ContextScopeManagerTest.java | 4 +- .../context/opentracing/SpanManagerTest.java | 4 +- .../servletrequest/ServletRequestContext.java | 4 +- .../ServletRequestContextManager.java | 4 +- .../ServletRequestContextManagerTest.java | 4 +- .../context/slf4j/mdc/Slf4jMdcManager.java | 4 +- .../slf4j/mdc/Slf4jMdcManagerTest.java | 7 +- .../SpringSecurityContextManager.java | 4 +- .../SpringSecurityContextManagerTest.java | 6 +- 64 files changed, 268 insertions(+), 244 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/Context.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java index 139c262b..54debbbd 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; @@ -50,7 +51,7 @@ protected BiConsumerWithContext(Supplier supplier, BiConsumer context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating accept method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(t, u); @@ -61,6 +62,8 @@ public void accept(T t, U u) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } @@ -68,7 +71,7 @@ public void accept(T t, U u) { public BiConsumer andThen(BiConsumer after) { requireNonNull(after, "Cannot post-process with after bi-consumer ."); return (l, r) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(l, r); @@ -80,6 +83,8 @@ public BiConsumer andThen(BiConsumer after) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java index d27b575e..82ec60a1 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; @@ -51,7 +52,7 @@ protected BiFunctionWithContext(Supplier supplier, BiFunction context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating apply method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().apply(in1, in2); @@ -62,6 +63,8 @@ public OUT apply(IN1 in1, IN2 in2) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } @@ -69,7 +72,7 @@ public OUT apply(IN1 in1, IN2 in2) { public BiFunction andThen(Function after) { requireNonNull(after, "Cannot post-process bi-function with after function ."); return (IN1 in1, IN2 in2) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); return after.apply(delegate().apply(in1, in2)); @@ -80,6 +83,8 @@ public BiFunction andThen(Function af contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java index a9b45d81..27a62d30 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Supplier; @@ -50,7 +51,7 @@ protected BiPredicateWithContext(Supplier supplier, BiPredicate @Override public boolean test(IN1 in1, IN2 in2) { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating test method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2); @@ -61,6 +62,8 @@ public boolean test(IN1 in1, IN2 in2) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } @@ -68,7 +71,7 @@ public boolean test(IN1 in1, IN2 in2) { public BiPredicate and(BiPredicate other) { requireNonNull(other, "Cannot combine bi-predicate with 'and' ."); return (IN1 in1, IN2 in2) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'and' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2) && other.test(in1, in2); @@ -79,6 +82,8 @@ public BiPredicate and(BiPredicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } @@ -87,7 +92,7 @@ public BiPredicate and(BiPredicate other) { public BiPredicate or(BiPredicate other) { requireNonNull(other, "Cannot combine bi-predicate with 'or' ."); return (IN1 in1, IN2 in2) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'or' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2) || other.test(in1, in2); @@ -98,6 +103,8 @@ public BiPredicate or(BiPredicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java index 1c1f64fe..1a892306 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -48,7 +49,7 @@ protected BooleanSupplierWithContext(Supplier supplier, Boolean @Override public boolean getAsBoolean() { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating getAsBoolean method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().getAsBoolean(); @@ -59,6 +60,8 @@ public boolean getAsBoolean() { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java index 16c5f363..f24d17ec 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -49,7 +50,7 @@ protected ConsumerWithContext(Supplier supplier, Consumer de @Override public void accept(T t) { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating accept method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(t); @@ -60,6 +61,8 @@ public void accept(T t) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new IllegalStateException("Error closing snapshot reactivation: " + e.getMessage(), e); } } @@ -67,7 +70,7 @@ public void accept(T t) { public Consumer andThen(Consumer after) { requireNonNull(after, "Cannot follow ConsumerWithContext with after consumer ."); return (T t) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(t); @@ -79,6 +82,8 @@ public Consumer andThen(Consumer after) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java index 022449d8..2466d781 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -49,7 +50,7 @@ protected FunctionWithContext(Supplier supplier, Function context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating apply method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().apply(in); @@ -60,13 +61,15 @@ public OUT apply(IN in) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new IllegalStateException("Error closing snapshot reactivation: " + e.getMessage(), e); } } public Function compose(Function before) { requireNonNull(before, "Cannot compose with before function ."); return (V v) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating compose method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().apply(before.apply(v)); @@ -77,6 +80,8 @@ public Function compose(Function before) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } @@ -84,7 +89,7 @@ public Function compose(Function before) { public Function andThen(Function after) { requireNonNull(after, "Cannot transform with after function ."); return (IN in) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); return after.apply(delegate().apply(in)); @@ -95,6 +100,8 @@ public Function andThen(Function after) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java index 24811f42..c3755173 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -50,7 +51,7 @@ protected PredicateWithContext(Supplier supplier, Predicate @Override public boolean test(T t) { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating test method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t); @@ -61,6 +62,8 @@ public boolean test(T t) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } @@ -68,7 +71,7 @@ public boolean test(T t) { public Predicate and(Predicate other) { requireNonNull(other, "Cannot combine predicate with 'and' ."); return (t) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'and' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t) && other.test(t); @@ -79,6 +82,8 @@ public Predicate and(Predicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } @@ -87,7 +92,7 @@ public Predicate and(Predicate other) { public Predicate or(Predicate other) { requireNonNull(other, "Cannot combine predicate with 'or' ."); return (t) -> { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'or' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t) || other.test(t); @@ -98,6 +103,8 @@ public Predicate or(Predicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java index 37c86906..64832c8a 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -71,7 +72,7 @@ protected RunnableWithContext(Supplier supplier, Runnable deleg @Override public void run() { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating run method with {0} to {1}.", new Object[]{context, delegate()}); delegate().run(); @@ -82,6 +83,8 @@ public void run() { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java index d208fdf1..b0844134 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java @@ -15,10 +15,11 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; +import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -47,7 +48,7 @@ protected SupplierWithContext(Supplier snapshotSupplier, Suppli @Override public T get() { - try (Context context = snapshot().reactivate()) { + try (Closeable context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating get method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().get(); @@ -58,6 +59,8 @@ public T get() { contextSnapshotConsumer.accept(resultSnapshot); } } + } catch (IOException e) { + throw new IllegalStateException(e.getMessage(), e); } } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java index df1253db..9f191cea 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; import java.util.Optional; @@ -69,4 +70,4 @@ private static Context current() { return AbstractThreadLocalContext.current(DummyContext.class); } } -} \ No newline at end of file +} diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java index f64a7ce5..8318f051 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java index 62506a43..c343411a 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,14 +15,16 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -33,8 +35,12 @@ import static nl.talsmasoftware.context.DummyContextManager.currentValue; import static nl.talsmasoftware.context.DummyContextManager.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Sjoerd Talsma @@ -102,8 +108,10 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat("Thread context must propagate", currentValue(), is(Optional.of("New value"))); + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }); t.start(); @@ -111,7 +119,7 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { } @Test - public void testAndThen() throws InterruptedException { + public void testAndThen() throws InterruptedException, IOException { setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -127,7 +135,7 @@ public void testAndThen() throws InterruptedException { t.join(); assertThat(currentValue(), is(Optional.of("Old value"))); - try (Context reactivated = snapshotHolder[0].reactivate()) { + try (Closeable reactivated = snapshotHolder[0].reactivate()) { assertThat(currentValue(), is(Optional.of("NEW value, New value, Old value"))); } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java index f94f3add..a542ab6e 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; @@ -94,7 +96,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException { + public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -108,7 +110,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java index c359d235..0b05da92 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiPredicate; @@ -93,7 +95,7 @@ public void testTestWithoutSnapshotSupplier() { } @Test - public void testTestWithSnapshotConsumer() throws InterruptedException { + public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -107,7 +109,7 @@ public void testTestWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java index 44d33d6d..54c2fc1b 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; @@ -96,7 +98,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException { + public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -110,7 +112,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java index c6dc0fd6..b52fba55 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; @@ -23,6 +22,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -85,7 +86,7 @@ public void testConstructWithoutSnapshotSupplier() { } @Test - public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException { + public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { DummyContextManager.setCurrentValue("true"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -101,7 +102,7 @@ public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, In assertThat(future.get(), is(true)); assertThat(DummyContextManager.currentValue(), is(Optional.of("true"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("false"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("true"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java index fb4f36fd..2dc3de44 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,14 +15,16 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -32,8 +34,12 @@ import static nl.talsmasoftware.context.DummyContextManager.currentValue; import static nl.talsmasoftware.context.DummyContextManager.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Sjoerd Talsma @@ -96,8 +102,10 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat("Thread context must propagate", currentValue(), is(Optional.of("New value"))); + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } }); t.start(); @@ -105,7 +113,7 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { } @Test - public void testAndThen() throws InterruptedException { + public void testAndThen() throws InterruptedException, IOException { setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -120,7 +128,7 @@ public void testAndThen() throws InterruptedException { t.join(); assertThat(currentValue(), is(Optional.of("Old value"))); - try (Context reactivated = snapshotHolder[0].reactivate()) { + try (Closeable reactivated = snapshotHolder[0].reactivate()) { assertThat(currentValue(), is(Optional.of("NEW VALUE, New value, Old value"))); } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java index 771f111a..30bf5153 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; @@ -93,7 +95,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException { + public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -107,7 +109,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java index 7c9d830e..ae00e7a9 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; @@ -94,7 +96,7 @@ public void testTestWithoutSnapshotSupplier() { } @Test - public void testTestWithSnapshotConsumer() throws InterruptedException { + public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -108,7 +110,7 @@ public void testTestWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java index 618355c3..367ef8f7 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.function.Supplier; @@ -92,7 +94,7 @@ public void testRunWithoutSnapshotSupplier() { } @Test - public void testRunWithSnapshotConsumer() throws InterruptedException { + public void testRunWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -103,7 +105,7 @@ public void testRunWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java index 58b4c9c2..529398cc 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -74,7 +76,7 @@ public void testGetNull() { } @Test - public void testGetWithSnapshotConsumer() throws ExecutionException, InterruptedException { + public void testGetWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { DummyContextManager.setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -91,7 +93,7 @@ public void testGetWithSnapshotConsumer() throws ExecutionException, Interrupted verify(snapshot).reactivate(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java index c60ef6d1..3d61225d 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,15 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.util.Optional; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -91,7 +93,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException { + public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContextManager.setCurrentValue("Old value"); @@ -105,7 +107,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException { t.join(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); - try (Context reactivation = snapshotHolder[0].reactivate()) { + try (Closeable reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); } assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java index 211463cb..ca946562 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/Context.java b/context-propagation/src/main/java/nl/talsmasoftware/context/Context.java deleted file mode 100644 index 7561dae0..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/Context.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import java.io.Closeable; - -/** - * A context can be anything that needs to be maintained on the 'current thread' level. - *

- * It is the responsibility of the one activating a new context to - * also {@linkplain #close() close} it again from the same thread. - *

- * Implementations are typically maintained within a static {@link ThreadLocal} variable.
- * A context has a very simple life-cycle: they can be created and {@link #close() closed}. - * A well-behaved Context implementation will make sure that thread-local state is restored - * to the way it was before when the context gets {@link #close() closed} again.
- * There is an {@link nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext abstract implementation} - * available that can be extended, that takes care of random-depth nested contexts and restoring the 'previous' - * context state. - * - * @param type of the context value - * @author Sjoerd Talsma - * @deprecated Moved to nl.talsmasoftware.context.api package. - */ -@Deprecated -public interface Context extends Closeable { - - /** - * Returns the value associated with this context. - *

- * Implementors should explicitly document the behaviour of this method after {@link #close()} was called. - * For example, it may be useful to always return null after a {@link Context} has been - * {@link #close() closed}. - * Contrary, it may in some cases be useful to retain the existing value after the context is closed, - * so clients that have kept a reference can still have access to it. - *

- * Normally, for security-related contexts, it is wise to always return null from closed contexts. - * - * @return The value associated with this context. - */ - T getValue(); - - /** - * Closes this context. - *

- * It is the responsibility of the one activating a new context to also close it again from the same thread. - *

- * It must be possible to call this method multiple times. - * It is the responsibility of the implementor of this context to make sure that closing an already-closed context - * has no unwanted side-effects. - * A simple way to achieve this is by using an {@link java.util.concurrent.atomic.AtomicBoolean} to make sure the - * 'closing' transition is executed only once. - *

- * Implementors should attempt to restore previous contextual state upon close. - * - * @throws RuntimeException if an error occurs while restoring the context. - */ - void close(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java index 37545fcb..0424c9b0 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java @@ -15,6 +15,8 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; + /** * The contract for a ContextManager Service. * diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java index abf416f7..23317c38 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java @@ -27,7 +27,7 @@ *

* Such a {@link ContextSnapshot snapshot} can be passed to a background task to allow the context to be * {@link ContextSnapshot#reactivate() reactivated} in that background thread, until it gets - * {@link Context#close() closed} again (preferably in a try-with-resources construct). + * {@link nl.talsmasoftware.context.api.Context#close() closed} again (preferably in a try-with-resources construct). * * @author Sjoerd Talsma * @see nl.talsmasoftware.context.core.ContextManagers @@ -60,7 +60,7 @@ private ContextManagers() { * implementations. *

* This snapshot is returned as a single object that can be temporarily - * {@link ContextSnapshot#reactivate() reactivated}. Don't forget to {@link Context#close() close} the reactivated + * {@link ContextSnapshot#reactivate() reactivated}. Don't forget to {@link nl.talsmasoftware.context.api.Context#close() close} the reactivated * context once you're done, preferably in a try-with-resources construct. * * @return A new snapshot that can be reactivated elsewhere (e.g. a background thread or even another node) @@ -87,7 +87,7 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho * as this will allow any unclosed contexts to be garbage collected. Besides preventing contextual issues, * this reduces the risk of memory leaks by unbalanced context calls. *

- * For context managers that are not {@linkplain Clearable} and contain an active {@linkplain Context} + * For context managers that are not {@linkplain Clearable} and contain an active {@linkplain nl.talsmasoftware.context.api.Context} * that is not {@code Clearable} either, this active context will be closed normally. * * @deprecated Moved to the {@code nl.talsmasoftware.context.core} package. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java index 02dce5a6..9cfa8450 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java @@ -15,11 +15,13 @@ */ package nl.talsmasoftware.context; +import java.io.Closeable; + /** * Interface for a 'snapshot' that can capture the (then-) 'active context' from all known registered * {@link ContextManager} implementations.
* Obtain a new snapshot by calling {@link ContextManagers#createContextSnapshot()} which will include a snapshot - * for all supported {@link Context} types through their respective {@link ContextManager managers}. + * for all supported {@link nl.talsmasoftware.context.api.Context} types through their respective {@link ContextManager managers}. *

* This allows for a generic method to: *

    @@ -27,8 +29,8 @@ *
  1. Pass the returned ContextSnapshot along to a background job.
  2. *
  3. Allow the background job to (temporary) {@link #reactivate() reactivate} the snapshot * for some required code path.
  4. - *
  5. The reactivation is also a {@link Context} of its own. Although it does not return any specific - * {@link Context#getValue() value}, it must be {@link Context#close() closed} when the work requiring + *
  6. The reactivation is also a {@link nl.talsmasoftware.context.api.Context} of its own. Although it does not return any specific + * {@link nl.talsmasoftware.context.api.Context#getValue() value}, it must be {@link nl.talsmasoftware.context.api.Context#close() closed} when the work requiring * the context snapshot is done. This prevents context values leaking in case the used threads * are returned to some pool.
  7. *
@@ -40,7 +42,7 @@ public interface ContextSnapshot { /** - * This method activates all contained values by the snapshot in their respective {@link Context} implementations. + * This method activates all contained values by the snapshot in their respective {@link nl.talsmasoftware.context.api.Context} implementations. *

* The reactivated context is of type {@code Void}, because it does not contain any value itself. * It closes all contained snapshot values collectively from its {@code close()} method. @@ -54,6 +56,6 @@ public interface ContextSnapshot { * @return A new reactivation context with the snapshot values that will be valid until closed * (or new values are registered). */ - Context reactivate(); + Closeable reactivate(); } diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java b/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java index 6ac77ef5..3c09ffb3 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java @@ -46,7 +46,7 @@ * @author Sjoerd Talsma * @since 1.1.0 */ -public interface Context extends Closeable, nl.talsmasoftware.context.Context { +public interface Context extends Closeable { /** * The value associated with this context. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java index cb7f78ec..9faa2dae 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java @@ -15,7 +15,6 @@ */ package nl.talsmasoftware.context.api; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import java.io.Closeable; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 0aff6d19..1822cbdd 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.core; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextObserver; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; import nl.talsmasoftware.context.clearable.Clearable; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java index 72f2b2f5..8943c10a 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import java.io.Closeable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.logging.Level; @@ -58,7 +58,7 @@ protected Callable map(final Callable callable) { return new Callable() { public V call() throws Exception { Exception exception = null; - final Context context = snapshot.reactivate(); + final Closeable context = snapshot.reactivate(); try { return callable.call(); } catch (Exception ex) { @@ -76,7 +76,7 @@ public V call() throws Exception { * @param context context to be closed * @param exception exception if any occurred */ - private static void tryClose(Context context, Exception exception) throws Exception { + private static void tryClose(Closeable context, Exception exception) throws Exception { if (context != null) try { context.close(); } catch (RuntimeException closeEx) { diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java index 840f2f94..7113daff 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.core.threadlocal; -import nl.talsmasoftware.context.Context; +import nl.talsmasoftware.context.api.Context; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java index 63587099..ab3cc7b4 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,11 @@ * *

* Each call to {@linkplain nl.talsmasoftware.context.ContextManager#initializeNewContext(java.lang.Object)} or - * {@linkplain nl.talsmasoftware.context.Context#close()} is sent to all relevant context observers. + * {@linkplain nl.talsmasoftware.context.api.Context#close()} is sent to all relevant context observers. * *

* Each observer must specify which context manager is being observed by implementing the * {@linkplain nl.talsmasoftware.context.observer.ContextObserver#getObservedContextManager()} method. * Context observers are looked up by java's {@code ServiceLoader}. */ -package nl.talsmasoftware.context.observer; \ No newline at end of file +package nl.talsmasoftware.context.observer; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java index 42b0de0b..9bfe4438 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ /** * Main package defining the core {@code context-propagation} concepts in this library * - *

{@linkplain nl.talsmasoftware.context.Context}

+ *

{@linkplain nl.talsmasoftware.context.api.Context}

*

- * A {@linkplain nl.talsmasoftware.context.Context context} contains - * a {@linkplain nl.talsmasoftware.context.Context#getValue() value}.
+ * A {@linkplain nl.talsmasoftware.context.api.Context context} contains + * a {@linkplain nl.talsmasoftware.context.api.Context#getValue() value}.
* There can be one active context per thread. A context remains active until it is closed or another context * is activated in that thread. * @@ -48,4 +48,4 @@ * * @author Sjoerd Talsma */ -package nl.talsmasoftware.context; \ No newline at end of file +package nl.talsmasoftware.context; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java index c0abf5c8..06773ce7 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.threadlocal; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java index f1a39dd8..c612f005 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java @@ -15,12 +15,15 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import nl.talsmasoftware.context.observer.SimpleContextObserver; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -89,7 +92,7 @@ public void testUnsupportedConstructor() { } @Test - public void testSnapshot_inSameThread() { + public void testSnapshot_inSameThread() throws IOException { DummyContext.reset(); assertThat(DummyContext.currentValue(), is(nullValue())); @@ -106,10 +109,10 @@ public void testSnapshot_inSameThread() { assertThat(DummyContext.currentValue(), is("third value")); // Reactivate snapshot: ctx1 -> ctx2 -> ctx3 -> ctx2' - Context ctxSnapshot = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); assertThat(DummyContext.currentValue(), is("second value")); - ctxSnapshot.close(); + reactivation.close(); assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! // out-of-order closing! @@ -183,14 +186,14 @@ public ContextSnapshot call() throws Exception { } @Test - public void testCreateSnapshot_ExceptionHandling() { + public void testCreateSnapshot_ExceptionHandling() throws IOException { ThrowingContextManager.onGet = new IllegalStateException("No active context!"); Context ctx = new DummyContext("blah"); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx.close(); assertThat(DummyContext.currentValue(), is(nullValue())); - Context reactivation = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); assertThat(DummyContext.currentValue(), is("blah")); reactivation.close(); assertThat(DummyContext.current(), is(nullValue())); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java index 4274f709..e23635a5 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,15 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.Test; +import java.io.Closeable; +import java.io.IOException; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; /** @@ -40,7 +43,7 @@ public void testSnapshotToString() { } @Test - public void testSnapshotReactivate() { + public void testSnapshotReactivate() throws IOException { Context ctx = MGR.initializeNewContext("Old value"); try { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); @@ -48,10 +51,9 @@ public void testSnapshotReactivate() { try { assertThat(MGR.getActiveContext().getValue(), is("New value")); - Context reactivation = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); try { assertThat(MGR.getActiveContext().getValue(), is("Old value")); - assertThat(reactivation.getValue(), is(nullValue())); assertThat(reactivation, hasToString(startsWith("ReactivatedContext{size="))); } finally { reactivation.close(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java b/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java index b29d5fb9..c6a2f85f 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; /** diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java index 298fcbc5..98d181a6 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java @@ -15,6 +15,8 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; + /** * Trivial manager around the {@link DummyContext} implementation to be registered as service provider. * diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java index 97cbeb0f..96cd8c9f 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,14 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.Closeable; import java.io.File; +import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -44,21 +47,21 @@ public void resetDefaultClassLoader() { } @Test - public void testReactivate_withoutContextManagers() { + public void testReactivate_withoutContextManagers() throws IOException { Context ctx1 = new DummyContext("foo"); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx1.close(); - Context reactivated = snapshot.reactivate(); + Closeable reactivated = snapshot.reactivate(); reactivated.close(); } @Test - public void testCreateSnapshot_withoutContextManagers() { + public void testCreateSnapshot_withoutContextManagers() throws IOException { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); assertThat(snapshot, is(notNullValue())); - Context reactivated = snapshot.reactivate(); + Closeable reactivated = snapshot.reactivate(); assertThat(reactivated, is(notNullValue())); reactivated.close(); } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java index 3fa1ad7d..6a0a66bc 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package nl.talsmasoftware.context; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; /** diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java index 09ce826d..e5de5708 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.clearable; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; public class AutoInitializingContextManager implements ContextManager { private static final ThreadLocal CTX = new ThreadLocal() { diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java index a89a1e5f..c8ec90bf 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.clearable; -import nl.talsmasoftware.context.Context; +import nl.talsmasoftware.context.api.Context; public class ClearableDummyContextManager implements ClearableContextManager { private static final ThreadLocal CTX = new ThreadLocal(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java index 0ba534e6..16fd9dfa 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.clearable; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; public class DummyManagerOfClearableContext implements ContextManager { private static final ThreadLocal CTX = new ThreadLocal(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java index da9c6a55..11371597 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java @@ -123,7 +123,7 @@ public Integer call() { void testObserveActivatedSnapshot() { SimpleContextObserver observer = new SimpleContextObserver(); try { - nl.talsmasoftware.context.Context ctx = dummyManager.initializeNewContext("Snapshot value"); + nl.talsmasoftware.context.api.Context ctx = dummyManager.initializeNewContext("Snapshot value"); ContextManagers.registerContextObserver(observer, DummyContextManager.class); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx.close(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java index 5283e92c..bfa7248d 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.executors; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.ThrowingContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java index eafd51bf..f97df70a 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,11 @@ */ package nl.talsmasoftware.context.observer; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.ThrowingContextManager; +import nl.talsmasoftware.context.api.Context; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java index 09914fa8..74a902b3 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.observer; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; @SuppressWarnings("deprecation") // The whole idea of this class is to test deprecated behaviour diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java index 768e427a..473b7722 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.observer; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.Context; import org.junit.jupiter.api.Test; import static nl.talsmasoftware.context.observer.Observed.activated; diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java index dcd813ce..55caa168 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java +++ b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; import java.util.Locale; diff --git a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java index 69ed180f..6d116bed 100644 --- a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java +++ b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java b/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java index d6e871a2..bdf0a568 100644 --- a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java +++ b/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.log4j2.threadcontext; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.clearable.ClearableContextManager; import org.apache.logging.log4j.CloseableThreadContext; import org.apache.logging.log4j.ThreadContext; diff --git a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java index 187ca359..018e0f13 100644 --- a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java +++ b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.log4j2.threadcontext; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.AfterEach; @@ -25,6 +25,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; +import java.io.Closeable; +import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -207,7 +209,7 @@ public Integer call() { } @Test - void testSnapshotRestorationAfterClosingReactivatedSnapshot() { + void testSnapshotRestorationAfterClosingReactivatedSnapshot() throws IOException { String mapKey1 = "map1"; ThreadContext.put(mapKey1, "value1"); ThreadContext.push("stack1"); @@ -226,7 +228,7 @@ void testSnapshotRestorationAfterClosingReactivatedSnapshot() { String mapKey2 = "map2"; ThreadContext.put(mapKey2, "value2"); - Context reactivation = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); assertThat("ThreadContext changed by reactivation", ThreadContext.get(mapKey1), equalTo("value1")); assertThat("Existing ThreadContext data should not have been cleared", ThreadContext.get(mapKey2), equalTo("value2")); assertThat(ThreadContext.getContext().size(), is(2)); diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java index 0636d95c..4c526a87 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ import io.opentracing.Scope; import io.opentracing.ScopeManager; import io.opentracing.Span; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java index 11e1678b..8ebb9778 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,9 @@ import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.util.GlobalTracer; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java index a1489085..1d840ae8 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2023 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import io.opentracing.mock.MockTracer; import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java index 037a7d22..ee523791 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; import io.opentracing.util.ThreadLocalScopeManager; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java index 40aef5c2..daec436f 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import javax.servlet.ServletRequest; diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java index 1df43b6f..9da1c691 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; +import nl.talsmasoftware.context.api.Context; import javax.servlet.ServletRequest; diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java index 468232b9..b68b3818 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java +++ b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java index 422f593f..ab883b83 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java +++ b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.slf4j.mdc; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.clearable.Clearable; import org.slf4j.MDC; diff --git a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java index 260de05e..0cf0e625 100644 --- a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java +++ b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,15 +15,16 @@ */ package nl.talsmasoftware.context.slf4j.mdc; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.MDC; +import java.io.Closeable; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -83,7 +84,7 @@ public void testMdcItemRestoration() throws Exception { MDC.put("mdc-item", "Value 2"); assertThat("Sanity check: MDC changed?", GET_MDC_ITEM.call(), is("Value 2")); - Context reactivation = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); assertThat("MDC changed by reactivation", GET_MDC_ITEM.call(), is("Value 1")); reactivation.close(); diff --git a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java b/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java index 9b5e9dc8..1224b2df 100644 --- a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java +++ b/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.springsecurity; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.clearable.ClearableContextManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; diff --git a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java index 146dc3e0..35848871 100644 --- a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java +++ b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ */ package nl.talsmasoftware.context.springsecurity; -import nl.talsmasoftware.context.Context; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; @@ -26,6 +25,7 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import java.io.Closeable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -103,7 +103,7 @@ public void testAuthenticationReactivation() throws Exception { assertThat("Sanity check: Context changed?", GET_AUTHENTICATION.call(), hasToString(containsString("Jules Winnfield"))); - Context reactivation = snapshot.reactivate(); + Closeable reactivation = snapshot.reactivate(); assertThat("Context changed by reactivation", GET_AUTHENTICATION.call(), hasToString(containsString("Vincent Vega"))); From 679bc3e91090719d852bde8a527c9a1d5d4cb766 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Sat, 2 Nov 2024 13:30:41 +0100 Subject: [PATCH 05/41] Remove deprecated ContextTimer interface. Signed-off-by: Sjoerd Talsma --- .../context/metrics/MetricsContextTimer.java | 2 +- ...l.talsmasoftware.context.api.ContextTimer} | 0 .../metrics/MetricsContextTimerTest.java | 4 +- .../micrometer/MicrometerContextTimer.java | 4 +- ...l.talsmasoftware.context.api.ContextTimer} | 0 .../talsmasoftware/context/core/Timers.java | 11 +----- .../context/timing/ContextTimer.java | 37 ------------------- .../context/timing/package-info.java | 25 ------------- .../context/core/TimersTest.java | 2 +- ...l.talsmasoftware.context.api.ContextTimer} | 0 .../opentracing/OpentracingContextTimer.java | 2 +- ...l.talsmasoftware.context.api.ContextTimer} | 0 12 files changed, 8 insertions(+), 79 deletions(-) rename context-propagation-metrics/src/main/resources/META-INF/services/{nl.talsmasoftware.context.timing.ContextTimer => nl.talsmasoftware.context.api.ContextTimer} (100%) rename context-propagation-micrometer/src/main/resources/META-INF/services/{nl.talsmasoftware.context.timing.ContextTimer => nl.talsmasoftware.context.api.ContextTimer} (100%) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/timing/ContextTimer.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/timing/package-info.java rename context-propagation/src/test/resources/META-INF/services/{nl.talsmasoftware.context.timing.ContextTimer => nl.talsmasoftware.context.api.ContextTimer} (100%) rename opentracing-span-propagation/src/main/resources/META-INF/services/{nl.talsmasoftware.context.timing.ContextTimer => nl.talsmasoftware.context.api.ContextTimer} (100%) diff --git a/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java b/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java index 8b44dfac..99292872 100644 --- a/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java +++ b/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java @@ -18,7 +18,7 @@ import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; import com.codahale.metrics.Timer; -import nl.talsmasoftware.context.timing.ContextTimer; +import nl.talsmasoftware.context.api.ContextTimer; import java.util.ArrayList; import java.util.Collection; diff --git a/context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer b/context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer rename to context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer diff --git a/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java b/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java index ba4b619e..a51ecb59 100644 --- a/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java +++ b/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java @@ -17,8 +17,8 @@ import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java b/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java index cb7392b5..3b623bc9 100644 --- a/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java +++ b/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package nl.talsmasoftware.context.micrometer; import io.micrometer.core.instrument.Metrics; -import nl.talsmasoftware.context.timing.ContextTimer; +import nl.talsmasoftware.context.api.ContextTimer; import java.util.concurrent.TimeUnit; diff --git a/context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer b/context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer rename to context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java index 6d147abf..2e6e8108 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java @@ -29,9 +29,6 @@ * @author Sjoerd Talsma */ final class Timers { - @Deprecated - private static final Logger DEPRECATED_TIMING_LOGGER = Logger.getLogger("nl.talsmasoftware.context.Timing"); - private static final Logger TIMING_LOGGER = Logger.getLogger(Timers.class.getName()); /** @@ -46,12 +43,6 @@ private enum Singleton { for (ContextTimer delegate : new PriorityServiceLoader(ContextTimer.class)) { delegates.add(delegate); } - // add legacy context services - for (nl.talsmasoftware.context.timing.ContextTimer delegate : new PriorityServiceLoader(nl.talsmasoftware.context.timing.ContextTimer.class)) { - if (!delegates.contains(delegate)) { - delegates.add(delegate); - } - } this.delegates = delegates.toArray(new ContextTimer[0]); } } @@ -60,7 +51,7 @@ static void timed(long durationNanos, Class type, String method) { for (ContextTimer delegate : Singleton.INSTANCE.delegates) { delegate.update(type, method, durationNanos, TimeUnit.NANOSECONDS); } - if (TIMING_LOGGER.isLoggable(Level.FINEST) || DEPRECATED_TIMING_LOGGER.isLoggable(Level.FINEST)) { + if (TIMING_LOGGER.isLoggable(Level.FINEST)) { TIMING_LOGGER.log(Level.FINEST, "{0}.{1}: {2,number}ns", new Object[]{type.getName(), method, durationNanos}); } } diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/timing/ContextTimer.java b/context-propagation/src/main/java/nl/talsmasoftware/context/timing/ContextTimer.java deleted file mode 100644 index 12d3f834..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/timing/ContextTimer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.timing; - -/** - * Minimal Service Provider Interface for services that wish to get informed of context switching metrics. - *

- * Currently the following timed operations are updated: - *

    - *
  • {@code ContextManagers.createContextSnapshot}
  • - *
  • {@code ContextSnapshot.reactivate}
  • - *
  • {@code ContextManager.initializeNewContext}(*)
  • - *
  • {@code ContextManager.getActiveContext}(*)
  • - *
- *

- * (*) Timing is updated for each concrete {@code ContextManager} implementation class - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.api} - */ -@Deprecated -public interface ContextTimer extends nl.talsmasoftware.context.api.ContextTimer { - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/timing/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/timing/package-info.java deleted file mode 100644 index f07f5e59..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/timing/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Package containing an api for obtaining timing information about propagated contexts. - * - *

{@linkplain nl.talsmasoftware.context.timing.ContextTimer}

- *

- * Interface to be implemented and registered as SPI to receive updates about propagated contexts. - * An example on how to use this can be found in the {@code context-propagation-metrics} library - * that uses this functionality to update Dropwizard metrics' {@code Timer} instances. - */ -package nl.talsmasoftware.context.timing; \ No newline at end of file diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java index 5eb1ecdb..90da0c3f 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.core; -import nl.talsmasoftware.context.timing.ContextTimer; +import nl.talsmasoftware.context.api.ContextTimer; import org.junit.jupiter.api.Test; import java.util.HashMap; diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer b/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer rename to context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java index df31e016..bade8e27 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java @@ -19,7 +19,7 @@ import io.opentracing.util.GlobalTracer; import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.ContextSnapshot; -import nl.talsmasoftware.context.timing.ContextTimer; +import nl.talsmasoftware.context.api.ContextTimer; import java.util.concurrent.TimeUnit; diff --git a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer b/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.timing.ContextTimer rename to opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer From 4d50b09121a5271aabcd74f83219845072e2d251 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 12:05:57 +0100 Subject: [PATCH 06/41] Remove deprecated ContextSnapshot interface. Signed-off-by: Sjoerd Talsma --- .../ContextAwareCompletableFuture.java | 4 +- .../concurrent/ContextSnapshotHolder.java | 4 +- .../core/function/BiConsumerWithContext.java | 4 +- .../core/function/BiFunctionWithContext.java | 4 +- .../core/function/BiPredicateWithContext.java | 4 +- .../function/BinaryOperatorWithContext.java | 2 +- .../function/BooleanSupplierWithContext.java | 4 +- .../core/function/ConsumerWithContext.java | 4 +- .../core/function/FunctionWithContext.java | 4 +- .../core/function/PredicateWithContext.java | 4 +- .../core/function/RunnableWithContext.java | 4 +- .../core/function/SupplierWithContext.java | 4 +- .../function/UnaryOperatorWithContext.java | 3 +- .../WrapperWithContextAndConsumer.java | 2 +- .../functions/BiConsumerWithContext.java | 2 +- .../functions/BiFunctionWithContext.java | 2 +- .../functions/BiPredicateWithContext.java | 2 +- .../functions/BinaryOperatorWithContext.java | 2 +- .../functions/BooleanSupplierWithContext.java | 2 +- .../functions/ConsumerWithContext.java | 2 +- .../functions/FunctionWithContext.java | 2 +- .../functions/PredicateWithContext.java | 2 +- .../functions/RunnableWithContext.java | 4 +- .../functions/SupplierWithContext.java | 2 +- .../functions/UnaryOperatorWithContext.java | 2 +- .../WrapperWithContextAndConsumer.java | 2 +- .../ContextAwareCompletableFuture.java | 4 +- .../futures/ContextSnapshotHolder.java | 4 +- .../context/futures/package-info.java | 7 +- .../ContextAwareCompletableFutureTest.java | 4 +- .../functions/BiConsumerWithContextTest.java | 4 +- .../functions/BiFunctionWithContextTest.java | 12 ++-- .../functions/BiPredicateWithContextTest.java | 27 ++++--- .../BinaryOperatorWithContextTest.java | 12 ++-- .../BooleanSupplierWithContextTest.java | 2 +- .../functions/ConsumerWithContextTest.java | 2 +- .../functions/FunctionWithContextTest.java | 17 +++-- .../functions/PredicateWithContextTest.java | 27 ++++--- .../functions/RunnableWithContextTest.java | 7 +- .../functions/SupplierWithContextTest.java | 2 +- .../UnaryOperatorWithContextTest.java | 7 +- .../WrapperWithContextAndConsumerTest.java | 4 +- .../context/futures/CompletedFutureTest.java | 4 +- .../ContextAwareCompletableFutureTest.java | 4 +- .../futures/ContextSnapshotHolderTest.java | 4 +- .../context/futures/FailedFutureTest.java | 6 +- .../MicrometerContextTimerTest.java | 4 +- .../context/ContextManager.java | 4 +- .../context/ContextManagers.java | 8 +-- .../context/ContextSnapshot.java | 61 ---------------- .../context/api/ContextSnapshot.java | 15 +--- .../context/core/ContextManagers.java | 2 +- .../ContextAwareExecutorService.java | 2 +- .../core/delegation/WrapperWithContext.java | 2 +- .../delegation/ContextSnapshotSupplier.java | 2 +- .../delegation/WrapperWithContext.java | 2 +- .../talsmasoftware/context/package-info.java | 2 +- .../context/ContextManagersTest.java | 1 + .../context/ContextSnapshotTest.java | 1 + .../context/NoContextManagersTest.java | 1 + .../delegation/WrapperWithContextTest.java | 4 +- .../Log4j2ThreadContextManagerTest.java | 4 +- .../opentracing/ContextScopeManager.java | 72 ++++++------------- .../opentracing/OpentracingContextTimer.java | 4 +- .../context/opentracing/SpanManager.java | 15 ++-- ...talsmasoftware.context.api.ContextManager} | 0 .../opentracing/ContextScopeManagerTest.java | 20 +++++- .../context/opentracing/Issue30Test.java | 6 +- .../context/opentracing/SpanManagerTest.java | 11 +-- .../context/slf4j/mdc/package-info.java | 8 +-- .../slf4j/mdc/Slf4jMdcManagerTest.java | 4 +- .../SpringSecurityContextManagerTest.java | 4 +- 72 files changed, 220 insertions(+), 276 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java rename opentracing-span-propagation/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java index 17c18526..395297f1 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.functions.BiConsumerWithContext; import nl.talsmasoftware.context.functions.BiFunctionWithContext; import nl.talsmasoftware.context.functions.ConsumerWithContext; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java index 13327842..a51995f9 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java index 54debbbd..f446c85e 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java index 82ec60a1..b5e8cc78 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java index 27a62d30..508c0858 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java index 087a9401..3c197d85 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BinaryOperator; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java index 1a892306..88bedf5f 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java index f24d17ec..c9ca7392 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java index 2466d781..b4d250c8 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java index c3755173..285fb320 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java index 64832c8a..ac552c7e 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java index b0844134..9a2bcfab 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.io.Closeable; import java.io.IOException; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java index b5e37f0e..a3f6a8b0 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java @@ -15,8 +15,7 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextSnapshot; -import nl.talsmasoftware.context.functions.FunctionWithContext; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java index e752878c..29c9f0c4 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.delegation.WrapperWithContext; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java index 73e2e6cb..2065af38 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BiConsumer; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java index 755ea12c..fe505cc4 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BiFunction; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java index 0b8c9460..3c898bc8 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BiPredicate; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java index 1648cf69..7768af10 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BinaryOperator; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java index 2710bb63..9225412f 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.BooleanSupplier; import java.util.function.Consumer; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java index ddb634bf..82ced5ea 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java index 12c4f620..a7563c42 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Function; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java index a6a6113c..f71f62cb 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Predicate; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java index c416f063..69b9d8c4 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java index 8158b6f9..cf76d39b 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java index e2ee09b4..a50359e2 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java index ef4f8501..c9f3c7a4 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.delegation.WrapperWithContext; import java.util.Optional; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java index 5cfee4be..bf8fb66f 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.functions.BiConsumerWithContext; import nl.talsmasoftware.context.functions.BiFunctionWithContext; import nl.talsmasoftware.context.functions.ConsumerWithContext; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java index 1c0c1abb..a937357c 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import java.util.function.Consumer; import java.util.function.Supplier; diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java index 5f8934ae..de9881ad 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** * Package for context-aware java {@link java.util.concurrent.Future} code. * *

{@linkplain nl.talsmasoftware.context.futures.ContextAwareCompletableFuture}

*

* A {@linkplain java.util.concurrent.CompletableFuture} that applies a certain - * {@linkplain nl.talsmasoftware.context.ContextSnapshot} to all + * {@linkplain nl.talsmasoftware.context.api.ContextSnapshot} to all * {@linkplain java.util.concurrent.CompletionStage completion stages} of the completable future. */ -package nl.talsmasoftware.context.futures; \ No newline at end of file +package nl.talsmasoftware.context.futures; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java index 8318f051..f89c92c7 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java index c343411a..4fc39a50 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java index a542ab6e..a62ddb45 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -120,7 +120,8 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -131,7 +132,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } @Test @@ -146,7 +147,8 @@ public void testAndThenNull() { @Test public void testAndThen_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Function after = i -> i + 100; BiFunction function = (a, b) -> a * 10 + b * 5; AtomicInteger consumed = new AtomicInteger(0); @@ -157,7 +159,7 @@ public void testAndThen_singleContextSwitch() { assertThat(composed.apply(2, 3), is(20 + 15 + 100)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java index 0b05da92..74c88e98 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -119,7 +119,8 @@ public void testTestWithSnapshotConsumer() throws InterruptedException, IOExcept @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -130,7 +131,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } @Test @@ -145,7 +146,8 @@ public void testAndOtherNull() { @Test public void testAnd_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); BiPredicate predicate = (a, b) -> a != null && b != null; BiPredicate and = (a, b) -> a.isEmpty() || b.isEmpty(); @@ -155,13 +157,14 @@ public void testAnd_singleContextSwitch() { assertThat(combined.test("", ""), is(true)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @Test public void testAnd_shortCircuit() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); BiPredicate predicate = (a, b) -> a != null && b != null; @SuppressWarnings("unchecked") BiPredicate and = mock(BiPredicate.class); @@ -174,7 +177,7 @@ public void testAnd_shortCircuit() { verifyNoMoreInteractions(and); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @@ -190,7 +193,8 @@ public void testOrOtherNull() { @Test public void tesOr_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); BiPredicate predicate = (a, b) -> a == null || b == null; BiPredicate or = (a, b) -> a.isEmpty() || b.isEmpty(); @@ -200,13 +204,14 @@ public void tesOr_singleContextSwitch() { assertThat(combined.test("", ""), is(true)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @Test public void testOr_shortCircuit() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); BiPredicate predicate = (a, b) -> a == null || b == null; @SuppressWarnings("unchecked") BiPredicate or = mock(BiPredicate.class); @@ -219,7 +224,7 @@ public void testOr_shortCircuit() { verifyNoMoreInteractions(or); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java index 54c2fc1b..6d40ac15 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -122,7 +122,8 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -134,7 +135,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } @Test @@ -149,7 +150,8 @@ public void testAndThenNull() { @Test public void testAndThen_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); UnaryOperator after = i -> i + 100; BinaryOperator function = (a, b) -> a * 10 + b * 5; AtomicInteger consumed = new AtomicInteger(0); @@ -160,7 +162,7 @@ public void testAndThen_singleContextSwitch() { assertThat(composed.apply(2, 3), is(20 + 15 + 100)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java index b52fba55..9fd0103c 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java @@ -16,8 +16,8 @@ package nl.talsmasoftware.context.functions; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java index 2dc3de44..60bc163c 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java @@ -16,9 +16,9 @@ package nl.talsmasoftware.context.functions; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java index 30bf5153..cad2eb91 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -119,7 +119,8 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -130,7 +131,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } @Test @@ -145,7 +146,8 @@ public void testComposeWithNull() { @Test public void testComposeWith_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Function before = i -> i * 10; Function function = i -> i + 3; AtomicInteger consumed = new AtomicInteger(0); @@ -154,13 +156,14 @@ public void testComposeWith_singleContextSwitch() { assertThat(composed.apply(2), is((2 * 10) + 3)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @Test public void testAndThen_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Function after = i -> i * 10; Function function = i -> i + 3; AtomicInteger consumed = new AtomicInteger(0); @@ -169,7 +172,7 @@ public void testAndThen_singleContextSwitch() { assertThat(composed.apply(2), is((2 + 3) * 10)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java index ae00e7a9..d0053a99 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -120,7 +120,8 @@ public void testTestWithSnapshotConsumer() throws InterruptedException, IOExcept @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -131,7 +132,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } @Test @@ -146,7 +147,8 @@ public void testAndOtherNull() { @Test public void testAnd_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Predicate predicate = Objects::nonNull; Predicate and = String::isEmpty; @@ -155,13 +157,14 @@ public void testAnd_singleContextSwitch() { assertThat(combined.test(""), is(true)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @Test public void testAnd_shortCircuit() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Predicate predicate = Objects::nonNull; @SuppressWarnings("unchecked") Predicate and = mock(Predicate.class); @@ -173,7 +176,7 @@ public void testAnd_shortCircuit() { verifyNoMoreInteractions(and); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @@ -189,7 +192,8 @@ public void testOrOtherNull() { @Test public void tesOr_singleContextSwitch() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Predicate predicate = Objects::isNull; Predicate or = String::isEmpty; @@ -198,13 +202,14 @@ public void tesOr_singleContextSwitch() { assertThat(combined.test(""), is(true)); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } @Test public void testOr_shortCircuit() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); Predicate predicate = Objects::isNull; @SuppressWarnings("unchecked") Predicate or = mock(Predicate.class); @@ -216,7 +221,7 @@ public void testOr_shortCircuit() { verifyNoMoreInteractions(or); verify(snapshot, times(1)).reactivate(); - verify(context, times(1)).close(); + verify(reactivation, times(1)).close(); assertThat(consumed.get(), is(1)); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java index 367ef8f7..785d3ceb 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -114,7 +114,8 @@ public void testRunWithSnapshotConsumer() throws InterruptedException, IOExcepti @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -125,7 +126,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } private static Runnable throwing(RuntimeException rte) { diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java index 529398cc..e7f2dd85 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java index 3d61225d..ee592945 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -117,7 +117,8 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep @Test public void testCloseReactivatedContextInCaseOfException() { - when(snapshot.reactivate()).thenReturn(context); + ContextSnapshot.Reactivation reactivation = mock(ContextSnapshot.Reactivation.class); + when(snapshot.reactivate()).thenReturn(reactivation); final RuntimeException expectedException = new RuntimeException("Whoops!"); try { @@ -129,7 +130,7 @@ public void testCloseReactivatedContextInCaseOfException() { } verify(snapshot).reactivate(); - verify(context).close(); + verify(reactivation).close(); } private static UnaryOperator throwing(RuntimeException rte) { diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java index 67419ca6..576636ec 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java index 9d588144..a94398f3 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package nl.talsmasoftware.context.futures; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java index ca946562..b961e987 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java index a991e784..1bd17267 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java index 9f78212d..0b60f6c3 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.DummyContextManager; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java b/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java index c567cbce..5979bb09 100644 --- a/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java +++ b/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java @@ -18,8 +18,8 @@ import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java index 0424c9b0..cc5f8a5c 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java @@ -23,7 +23,7 @@ *

* Implementations can be registered by providing a fully qualified class name in a service file called:
* "/META-INF/services/nl.talsmasoftware.context.ContextManager"
- * That will take care of any active context being captured in {@link ContextSnapshot} instances + * That will take care of any active context being captured in {@link nl.talsmasoftware.context.api.ContextSnapshot} instances * managed by the {@link ContextManagers} utility class.
* Note: Make sure your implementation has a default (no-argument) constructor. * @@ -31,7 +31,7 @@ * A context manager is required to notify * registered {@linkplain nl.talsmasoftware.context.observer.ContextObserver ContextObserver} instances * of context updates.
- * The {@linkplain nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} + * The {@linkplain nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} * already notifies these observers.
* Other implementations can use the {@linkplain ContextManagers#onActivate(Class, Object, Object)} * and {@linkplain ContextManagers#onDeactivate(Class, Object, Object)} methods diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java index 23317c38..2c39e2d5 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java @@ -25,8 +25,8 @@ * Core implementation to allow {@link #createContextSnapshot() taking a snapshot of all contexts}. * *

- * Such a {@link ContextSnapshot snapshot} can be passed to a background task to allow the context to be - * {@link ContextSnapshot#reactivate() reactivated} in that background thread, until it gets + * Such a {@link nl.talsmasoftware.context.api.ContextSnapshot snapshot} can be passed to a background task to allow the context to be + * {@link nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated} in that background thread, until it gets * {@link nl.talsmasoftware.context.api.Context#close() closed} again (preferably in a try-with-resources construct). * * @author Sjoerd Talsma @@ -60,7 +60,7 @@ private ContextManagers() { * implementations. *

* This snapshot is returned as a single object that can be temporarily - * {@link ContextSnapshot#reactivate() reactivated}. Don't forget to {@link nl.talsmasoftware.context.api.Context#close() close} the reactivated + * {@link nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated}. Don't forget to {@link nl.talsmasoftware.context.api.Context#close() close} the reactivated * context once you're done, preferably in a try-with-resources construct. * * @return A new snapshot that can be reactivated elsewhere (e.g. a background thread or even another node) @@ -105,7 +105,7 @@ public static void clearActiveContexts() { * It is possible to configure a fixed, single classloader in your application for looking up the context managers. *

* Using this method to specify a fixed classloader will only impact - * new {@linkplain ContextSnapshot context snapshots}. Existing snapshots will not be impacted. + * new {@linkplain nl.talsmasoftware.context.api.ContextSnapshot context snapshots}. Existing snapshots will not be impacted. *

* Notes:
*

    diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java deleted file mode 100644 index 9cfa8450..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextSnapshot.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import java.io.Closeable; - -/** - * Interface for a 'snapshot' that can capture the (then-) 'active context' from all known registered - * {@link ContextManager} implementations.
    - * Obtain a new snapshot by calling {@link ContextManagers#createContextSnapshot()} which will include a snapshot - * for all supported {@link nl.talsmasoftware.context.api.Context} types through their respective {@link ContextManager managers}. - *

    - * This allows for a generic method to: - *

      - *
    1. Create a new snapshot of the active context (for all registered ContextManagers).
    2. - *
    3. Pass the returned ContextSnapshot along to a background job.
    4. - *
    5. Allow the background job to (temporary) {@link #reactivate() reactivate} the snapshot - * for some required code path.
    6. - *
    7. The reactivation is also a {@link nl.talsmasoftware.context.api.Context} of its own. Although it does not return any specific - * {@link nl.talsmasoftware.context.api.Context#getValue() value}, it must be {@link nl.talsmasoftware.context.api.Context#close() closed} when the work requiring - * the context snapshot is done. This prevents context values leaking in case the used threads - * are returned to some pool.
    8. - *
    - * - * @author Sjoerd Talsma - * @deprecated Moved to api package. - */ -@Deprecated -public interface ContextSnapshot { - - /** - * This method activates all contained values by the snapshot in their respective {@link nl.talsmasoftware.context.api.Context} implementations. - *

    - * The reactivated context is of type {@code Void}, because it does not contain any value itself. - * It closes all contained snapshot values collectively from its {@code close()} method. - *

    - * Note: The reactivated context must be closed from the same thread that - * reactivated it. It is the responsibility of the caller to make sure this happens - * (preferably in a try-with-resources block)
    - * Using the {@linkplain nl.talsmasoftware.context.executors.ContextAwareExecutorService ContextAwareExecutorService} - * is a safe way to propagate context snapshots without having to worry about closing them. - * - * @return A new reactivation context with the snapshot values that will be valid until closed - * (or new values are registered). - */ - Closeable reactivate(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java index 9faa2dae..191ceea4 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java @@ -15,8 +15,6 @@ */ package nl.talsmasoftware.context.api; -import nl.talsmasoftware.context.ContextManager; - import java.io.Closeable; /** @@ -42,7 +40,7 @@ * @author Sjoerd Talsma * @since 1.1.0 */ -public interface ContextSnapshot extends nl.talsmasoftware.context.ContextSnapshot { +public interface ContextSnapshot { /** * Temporarily reactivates all captured context values that are in the snapshot. @@ -69,7 +67,7 @@ public interface ContextSnapshot extends nl.talsmasoftware.context.ContextSnapsh *

    * It is strongly advised to only use reactivation with try-with-resources code blocks. */ - interface Reactivation extends Closeable, Context { + interface Reactivation extends Closeable { /** * Ends the contexts from the reactivated context snapshot. * @@ -78,15 +76,6 @@ interface Reactivation extends Closeable, Context { * before the snapshot was activated. */ void close(); - - /** - * A reactivation contains no value. - * - * @return Always {@code null}. - * @deprecated From the next major version, Reactivation will no longer extend Context. - */ - @Deprecated - Void getValue(); } } diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 1822cbdd..30c7aecc 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -16,9 +16,9 @@ package nl.talsmasoftware.context.core; import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextObserver; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; import nl.talsmasoftware.context.clearable.Clearable; import nl.talsmasoftware.context.delegation.Wrapper; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java index 8943c10a..ab08301b 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java @@ -16,7 +16,7 @@ package nl.talsmasoftware.context.core.concurrent; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import java.io.Closeable; import java.util.concurrent.Callable; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java index 4dc22eed..917be149 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.core.delegation; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.delegation.ContextSnapshotSupplier; /** diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java index 60177c7c..d0b4b4f0 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.delegation; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; /** * Interface for a {@code Supplier} of {@link ContextSnapshot}. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java index de082fc1..229de27b 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.delegation; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; /** * Wrapper that also contains a fixed context snapshot. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java index 9bfe4438..1cbaf441 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java @@ -33,7 +33,7 @@ * Can {@linkplain nl.talsmasoftware.context.ContextManager#initializeNewContext(java.lang.Object) initialize a new context} * and provides access to the {@linkplain nl.talsmasoftware.context.ContextManager#getActiveContext() active context}. * - *

    {@linkplain nl.talsmasoftware.context.ContextSnapshot}

    + *

    {@linkplain nl.talsmasoftware.context.api.ContextSnapshot}

    *

    * A snapshot contains the current value from all known context managers.
    * These values can be reactivated in another thread.
    diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java index c612f005..42fe62af 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java @@ -16,6 +16,7 @@ package nl.talsmasoftware.context; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import nl.talsmasoftware.context.observer.SimpleContextObserver; import org.junit.jupiter.api.AfterEach; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java index e23635a5..44138eb7 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java @@ -16,6 +16,7 @@ package nl.talsmasoftware.context; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.Test; import java.io.Closeable; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java index 96cd8c9f..4a9100f6 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java @@ -16,6 +16,7 @@ package nl.talsmasoftware.context; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java index 35c4c754..0b5a3f68 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package nl.talsmasoftware.context.delegation; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.Test; import java.util.LinkedHashSet; diff --git a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java index 018e0f13..5365bbe6 100644 --- a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java +++ b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.log4j2.threadcontext; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.AfterEach; diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java index 4c526a87..162e5394 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java @@ -18,11 +18,9 @@ import io.opentracing.Scope; import io.opentracing.ScopeManager; import io.opentracing.Span; -import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; - -import java.util.concurrent.atomic.AtomicBoolean; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; /** * Our own implementation of the opentracing {@linkplain ScopeManager}. @@ -32,7 +30,7 @@ * taking care to restore the previous value when closing an active scope. * *

    - * This manager is based on our {@linkplain nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext} + * This manager is based on our {@linkplain nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext} * implementation. Compared to the 'standard' {@linkplain io.opentracing.util.ThreadLocalScopeManager} * this implementation has the following advantages: *

      @@ -41,7 +39,7 @@ *
    1. More predictable behaviour for out-of-order closing of scopes. * Although this is explicitly unsupported by the opentracing specification, * we think having consistent and predictable behaviour is an advantage. - *
    2. Support for {@link nl.talsmasoftware.context.observer.ContextObserver}. + *
    3. Support for {@link nl.talsmasoftware.context.api.ContextObserver}. * See https://github.com/opentracing/opentracing-java/issues/334 explicitly wanting this. *
    * @@ -58,33 +56,9 @@ * @since 1.0.6 */ public class ContextScopeManager implements ScopeManager, ContextManager { - /** - * Makes the given span the new active span. - * - * @param span The span to become the active span. - * @param finishSpanOnClose Whether the span should automatically finish when closing the resulting scope. - * @return The new active scope (must be closed from the same thread). - * @deprecated This is no longer part of the OpenTracing API as of {@code 0.33.0} - */ - @Deprecated - public Scope activate(Span span, boolean finishSpanOnClose) { - return new ThreadLocalSpanContext(getClass(), span, finishSpanOnClose); - } - @Override public Scope activate(Span span) { - return new ThreadLocalSpanContext(getClass(), span, false); - } - - /** - * The currently active {@link Scope} containing the {@linkplain #activeSpan() active span}. - * - * @return the active scope, or {@code null} if none could be found. - * @deprecated This is no longer part of the OpenTracing API as of {@code 0.33.0} - */ - @Deprecated - public Scope active() { - return ThreadLocalSpanContext.current(); + return new ThreadLocalSpanContext(span); } @Override @@ -102,7 +76,7 @@ public Span activeSpan() { */ @Override public Context initializeNewContext(Span value) { - return new ThreadLocalSpanContext(getClass(), value, false); + return new ThreadLocalSpanContext(value); } /** @@ -113,6 +87,17 @@ public Context getActiveContext() { return ThreadLocalSpanContext.current(); } + @Override + public Span getActiveContextValue() { + Context activeContext = getActiveContext(); + return activeContext == null ? null : activeContext.getValue(); + } + + @Override + public void clear() { + ThreadLocalSpanContext.removeThreadLocal(); + } + /** * @return String representation for this context manager. */ @@ -121,31 +106,16 @@ public String toString() { } private static final class ThreadLocalSpanContext extends AbstractThreadLocalContext implements Scope { - private final AtomicBoolean finishOnClose; - - private ThreadLocalSpanContext(Class> contextManagerType, Span newValue, boolean finishOnClose) { - super(contextManagerType, newValue); - this.finishOnClose = new AtomicBoolean(finishOnClose); + private ThreadLocalSpanContext(Span newValue) { + super(newValue); } private static ThreadLocalSpanContext current() { return current(ThreadLocalSpanContext.class); } - /** - * @deprecated This is no longer part of the OpenTracing API as of {@code 0.33.0} - */ - @Deprecated - public Span span() { - return value; - } - - @Override - public void close() { - super.close(); - if (finishOnClose.compareAndSet(true, false) && value != null) { - value.finish(); - } + private static void removeThreadLocal() { + threadLocalInstanceOf(ThreadLocalSpanContext.class).remove(); } } } diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java index bade8e27..36d45b10 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java @@ -17,9 +17,9 @@ import io.opentracing.Span; import io.opentracing.util.GlobalTracer; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextTimer; +import nl.talsmasoftware.context.core.ContextManagers; import java.util.concurrent.TimeUnit; diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java index 8ebb9778..81af56ea 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java @@ -18,9 +18,8 @@ import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.util.GlobalTracer; -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; import java.util.concurrent.atomic.AtomicBoolean; @@ -47,6 +46,16 @@ public Context getActiveContext() { return activeSpan == null ? null : new SpanContext(activeSpan, null); } + @Override + public Span getActiveContextValue() { + return GlobalTracer.get().activeSpan(); + } + + @Override + public void clear() { + + } + /** * {@linkplain io.opentracing.ScopeManager#activate(Span) Activates} the given {@linkplain Span span}. *

    @@ -87,7 +96,6 @@ private static class SpanContext implements Context { private SpanContext(Span span, Scope scope) { this.span = span; this.scope = scope; - ContextManagers.onActivate(SpanManager.class, span, null); } @Override @@ -101,7 +109,6 @@ public void close() { if (scope != null) { scope.close(); } - ContextManagers.onDeactivate(SpanManager.class, span, null); } } diff --git a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java index 1d840ae8..ca948e15 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java @@ -20,11 +20,14 @@ import io.opentracing.mock.MockTracer; import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -48,10 +51,21 @@ import static org.junit.jupiter.api.Assertions.fail; public class ContextScopeManagerTest { + static ContextScopeManagerObserver observer = new ContextScopeManagerObserver(); MockTracer mockTracer; ContextScopeManager scopeManager; ExecutorService threadpool; + @BeforeAll + static void registerObserver() { + ContextManagers.registerContextObserver(observer, ContextScopeManager.class); + } + + @AfterAll + static void unregisterObserver() { + ContextManagers.unregisterContextObserver(observer); + } + @BeforeEach public void registerMockGlobalTracer() { GlobalTracerTestUtil.resetGlobalTracer(); @@ -70,6 +84,7 @@ public void cleanup() { } @Test + @Disabled("TODO replace observer by MockTracer .finishedSpans inspection!") public void testObservedSpans() { assertThat(ContextScopeManagerObserver.observed, is(empty())); Span parentSpan = GlobalTracer.get().buildSpan("parent").start(); @@ -88,6 +103,7 @@ public void testObservedSpans() { } @Test + @Disabled("TODO replace observer by MockTracer .finishedSpans inspection!") public void testConcurrency() throws InterruptedException { List threads = new ArrayList(); final Span parentSpan = GlobalTracer.get().buildSpan("parent").start(); diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java index 0868956a..c80ad31d 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; import io.opentracing.util.ThreadLocalScopeManager; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java index ee523791..9a1abbf8 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java @@ -23,12 +23,13 @@ import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; import io.opentracing.util.ThreadLocalScopeManager; -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; @@ -92,6 +93,7 @@ public String call() { }; @Test + @Disabled("TODO Investigate the problem with this test and fix it before releasing!") public void testSingleSnapshotInBackgroundThread() throws Exception { Span outerSpan = mockTracer.buildSpan("first-op").start(); Scope outerScope = mockTracer.scopeManager().activate(outerSpan); @@ -111,12 +113,13 @@ public void testSingleSnapshotInBackgroundThread() throws Exception { } @Test + @Disabled("TODO Investigate the problem with this test and fix it before releasing!") public void testFinishSpanFromBlockingBackgroundThread() throws Exception { Span outerSpan = mockTracer.buildSpan("first-op").start(); Scope outerScope = mockTracer.scopeManager().activate(outerSpan); outerSpan.setBaggageItem("baggage-item", "in-outer-span"); - // sanity-check: outerSpan should be the active span.. + // sanity-check: outerSpan should be the active span. assertThat("sanity-check", GET_BAGGAGE_ITEM.call(), equalTo("in-outer-span")); // Start a blocking background thread. diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java index c5d96b55..636638f5 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java +++ b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ * This context manager maintains no threadlocal state of its own, * instead it propagates the * existing {@linkplain org.slf4j.MDC#getCopyOfContextMap() MDC context map} - * into each {@linkplain nl.talsmasoftware.context.ContextSnapshot context snapshot} + * into each {@linkplain nl.talsmasoftware.context.api.ContextSnapshot context snapshot} * to be applied again when the snapshot - * is {@linkplain nl.talsmasoftware.context.ContextSnapshot#reactivate() reactivated} + * is {@linkplain nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated} * in another thread. */ -package nl.talsmasoftware.context.slf4j.mdc; \ No newline at end of file +package nl.talsmasoftware.context.slf4j.mdc; diff --git a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java index 0cf0e625..58ba0e4a 100644 --- a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java +++ b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.slf4j.mdc; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java index 35848871..00648f26 100644 --- a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java +++ b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.springsecurity; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; From 18ac1348267168fd852912031074a139656867d1 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 12:41:18 +0100 Subject: [PATCH 07/41] Bump minimum java version to 1.8 Signed-off-by: Sjoerd Talsma --- context-propagation/pom.xml | 4 ---- locale-context/pom.xml | 4 ---- opentracing-span-propagation/pom.xml | 4 ---- servletrequest-propagation/pom.xml | 4 ---- slf4j-propagation/pom.xml | 4 ---- 5 files changed, 20 deletions(-) diff --git a/context-propagation/pom.xml b/context-propagation/pom.xml index 1e8e6c4a..42b6f9c7 100644 --- a/context-propagation/pom.xml +++ b/context-propagation/pom.xml @@ -34,10 +34,6 @@ ${project.groupId} ${project.parent.basedir} - 1.5 - 1.5 - - -Xlint:-options 8 1.3.2 diff --git a/locale-context/pom.xml b/locale-context/pom.xml index 065d46f2..2d284d32 100644 --- a/locale-context/pom.xml +++ b/locale-context/pom.xml @@ -33,10 +33,6 @@ ${project.groupId}.locale ${project.parent.basedir} - 1.5 - 1.5 - - -Xlint:-options 8 diff --git a/opentracing-span-propagation/pom.xml b/opentracing-span-propagation/pom.xml index f81e1464..d5b074dd 100644 --- a/opentracing-span-propagation/pom.xml +++ b/opentracing-span-propagation/pom.xml @@ -35,10 +35,6 @@ ${project.groupId}.opentracing ${project.parent.basedir} - 1.6 - 1.6 - - -Xlint:-options 8 diff --git a/servletrequest-propagation/pom.xml b/servletrequest-propagation/pom.xml index eb3d23ff..672df092 100644 --- a/servletrequest-propagation/pom.xml +++ b/servletrequest-propagation/pom.xml @@ -35,10 +35,6 @@ ${project.groupId}.servletrequest ${project.parent.basedir} - 1.5 - 1.5 - - -Xlint:-options 8 diff --git a/slf4j-propagation/pom.xml b/slf4j-propagation/pom.xml index 136ecb39..e930e746 100644 --- a/slf4j-propagation/pom.xml +++ b/slf4j-propagation/pom.xml @@ -33,10 +33,6 @@ ${project.groupId}.mdc ${project.parent.basedir} - 1.5 - 1.5 - - -Xlint:-options 8 From e2033ec104d2087dbfc8d19c4adb9d2f0f33cff7 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 14:20:35 +0100 Subject: [PATCH 08/41] Replace deprecated ContextSnapshotSupplier with Supplier Signed-off-by: Sjoerd Talsma --- .../core/delegation/WrapperWithContext.java | 11 +-- .../delegation/ContextSnapshotSupplier.java | 42 ----------- .../delegation/WrapperWithContext.java | 4 +- .../delegation/WrapperWithContextTest.java | 69 +++++++------------ 4 files changed, 35 insertions(+), 91 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/delegation/WrapperWithContextTest.java (70%) diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java index 917be149..077762e4 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java @@ -16,16 +16,17 @@ package nl.talsmasoftware.context.core.delegation; import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.delegation.ContextSnapshotSupplier; + +import java.util.function.Supplier; /** * Wrapper that contains a context snapshot. * * @author Sjoerd Talsma */ -public abstract class WrapperWithContext extends nl.talsmasoftware.context.delegation.Wrapper { +public abstract class WrapperWithContext extends Wrapper { - private final ContextSnapshotSupplier supplier; + private final Supplier supplier; private volatile ContextSnapshot snapshot; /** @@ -48,7 +49,7 @@ protected WrapperWithContext(final ContextSnapshot snapshot, final T delegate) { *

    * Note: Make sure the supplier function does not obtain the context snapshot * from any threadlocal storage! The wrapper is designed to propagate contexts from one thread to another. - * Therefore, the snapshot must be {@link nl.talsmasoftware.context.ContextManagers#createContextSnapshot() captured} + * Therefore, the snapshot must be {@link nl.talsmasoftware.context.core.ContextManagers#createContextSnapshot() captured} * in the source thread and {@link ContextSnapshot#reactivate() reactivated} in the target thread. * If unsure, please use the * {@link #WrapperWithContext(ContextSnapshot, Object) constructor with snapshot} instead. @@ -60,7 +61,7 @@ protected WrapperWithContext(final ContextSnapshot snapshot, final T delegate) { * @param delegate The delegate object to be wrapped. * @see #WrapperWithContext(ContextSnapshot, Object) */ - protected WrapperWithContext(ContextSnapshotSupplier supplier, T delegate) { + protected WrapperWithContext(Supplier supplier, T delegate) { super(delegate); this.supplier = supplier; this.snapshot = null; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java deleted file mode 100644 index d0b4b4f0..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/ContextSnapshotSupplier.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -/** - * Interface for a {@code Supplier} of {@link ContextSnapshot}. - *

    - * Merely an equivalent of the functional interface - * {@code java.util.Supplier} - * in order to retain JDK 5 compatibility. - * - * @author Sjoerd Talsma - * @deprecated This will be replace by {@code Supplier} from Java 8. - */ -@Deprecated -public interface ContextSnapshotSupplier { - - /** - * Supply a {@linkplain ContextSnapshot snapshot}. - *

    - * The supplier interface itself makes no guarantees whether the snapshot is nullable or not. - * - * @return The context snapshot. - */ - ContextSnapshot get(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java index 229de27b..0749b354 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java @@ -17,6 +17,8 @@ import nl.talsmasoftware.context.api.ContextSnapshot; +import java.util.function.Supplier; + /** * Wrapper that also contains a fixed context snapshot. * @@ -53,7 +55,7 @@ protected WrapperWithContext(final ContextSnapshot snapshot, final T delegate) { * @param delegate The delegate object to be wrapped. * @see #WrapperWithContext(ContextSnapshot, Object) */ - protected WrapperWithContext(ContextSnapshotSupplier supplier, T delegate) { + protected WrapperWithContext(Supplier supplier, T delegate) { super(supplier, delegate); } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java similarity index 70% rename from context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java index 0b5a3f68..5f50ad6e 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperWithContextTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.Test; import java.util.LinkedHashSet; import java.util.Set; +import java.util.function.Supplier; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -30,7 +31,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; /** @@ -39,7 +40,6 @@ public class WrapperWithContextTest { @Test - @SuppressWarnings("deprecation") public void testCreateWrapperWithoutDelegate() { WrapperWithContext wrapper = new WrapperWithContext(mock(ContextSnapshot.class), null) { }; @@ -48,32 +48,36 @@ public void testCreateWrapperWithoutDelegate() { } @Test - @SuppressWarnings("deprecation") public void testCreateWrapperWithoutSnapshot() { - try { - new WrapperWithContext((ContextSnapshot) null, mock(Wrapper.class)) { - }; - fail("Exception expected."); - } catch (NullPointerException expected) { - assertThat(expected, hasToString(containsString("No context snapshot provided"))); - } + ContextSnapshot snapshot = null; + Wrapper wrapper = mock(Wrapper.class); + Exception expected = assertThrows(NullPointerException.class, () -> + new WrapperWithContext(snapshot, wrapper) { + }); + assertThat(expected, hasToString(containsString("No context snapshot provided"))); } @Test public void testCreateWrapperWithoutSnapshotSupplier() { - try { - new WrapperWithContext((ContextSnapshotSupplier) null, mock(Wrapper.class)) { - }; - fail("Exception expected."); - } catch (NullPointerException expected) { - assertThat(expected, hasToString(containsString("No context snapshot supplier provided"))); - } + Supplier supplier = null; + Wrapper wrapper = mock(Wrapper.class); + Exception expected = assertThrows(NullPointerException.class, () -> + new WrapperWithContext(supplier, wrapper) { + }); + assertThat(expected, hasToString(containsString("No context snapshot supplier provided"))); + } + + @Test + public void testSupplySnapshotNull() { + WrapperWithContext wrapperWithContext = new WrapperWithContext((Supplier) () -> null, mock(Wrapper.class)) { + }; + Exception expected = assertThrows(NullPointerException.class, wrapperWithContext::snapshot); + assertThat(expected, hasToString(containsString("Context snapshot is "))); } @Test - @SuppressWarnings("deprecation") public void testEqualsHashcode() { - Set> set = new LinkedHashSet>(); + Set> set = new LinkedHashSet<>(); ContextSnapshot snapshot = mock(ContextSnapshot.class); Wrapper delegate = mock(Wrapper.class); @@ -87,7 +91,7 @@ public void testEqualsHashcode() { assertThat(set, hasSize(3)); assertThat(wrapper, equalTo(wrapper)); - assertThat(wrapper, equalTo((WrapperWithContext) new DoNothingWrapper(snapshot, delegate))); + assertThat(wrapper, equalTo(new DoNothingWrapper(snapshot, delegate))); WrapperWithContext copy = new WrapperWithContext(snapshot, delegate) { }; assertThat(wrapper, not(equalTo(copy))); // different inner class @@ -100,7 +104,6 @@ protected DoNothingWrapper(ContextSnapshot snapshot, Object delegate) { } @Test - @SuppressWarnings("deprecation") public void testToString() { ContextSnapshot snapshot = mock(ContextSnapshot.class); Wrapper delegate = mock(Wrapper.class); @@ -115,11 +118,7 @@ public void testToString() { public void testToString_contextSnapshotSupplier() { final ContextSnapshot snapshot = mock(ContextSnapshot.class); final Wrapper delegate = mock(Wrapper.class); - final WrapperWithContext wrapper = new WrapperWithContext(new ContextSnapshotSupplier() { - public ContextSnapshot get() { - return snapshot; - } - }, delegate) { + final WrapperWithContext wrapper = new WrapperWithContext(() -> snapshot, delegate) { }; // Test that toString does NOT trigger eager snapshot evaluation. @@ -128,20 +127,4 @@ public ContextSnapshot get() { wrapper.snapshot(); assertThat(wrapper, hasToString(containsString(snapshot.toString()))); } - - @Test - public void testSupplySnapshotNull() { - try { - new WrapperWithContext(new ContextSnapshotSupplier() { - public ContextSnapshot get() { - return null; - } - }, "Delegate") { - }.snapshot(); - fail("Exception expected!"); - } catch (NullPointerException expected) { - assertThat(expected, hasToString(containsString("Context snapshot is "))); - } - } - } From 541bc3559fb6bdcc19d13463fc8809504c887802 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 14:38:57 +0100 Subject: [PATCH 09/41] Remove deprecated Wrapper class. Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 2 +- .../delegation/DelegatingExecutorService.java | 7 +- .../core/delegation/DelegatingFuture.java | 4 +- .../delegation/DelegatingExecutorService.java | 2 +- .../context/delegation/DelegatingFuture.java | 2 +- .../context/delegation/Wrapper.java | 65 ------------------- .../context/delegation/package-info.java | 6 +- .../{ => core}/delegation/WrapperTest.java | 2 +- 8 files changed, 13 insertions(+), 77 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/Wrapper.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/delegation/WrapperTest.java (96%) diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 30c7aecc..d24e2821 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -21,7 +21,7 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; import nl.talsmasoftware.context.clearable.Clearable; -import nl.talsmasoftware.context.delegation.Wrapper; +import nl.talsmasoftware.context.core.delegation.Wrapper; import java.util.ArrayList; import java.util.Arrays; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java index 81567fbd..f684dfcf 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java @@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -27,7 +28,7 @@ /** * Abstract baseclass that makes it a little easier to wrap existing {@link ExecutorService} implementations by - * forwarding all methods to a {@link nl.talsmasoftware.context.delegation.Wrapper#delegate() delegate} executor service.
    + * forwarding all methods to a {@link Wrapper#delegate() delegate} executor service.
    * The class also provides overridable wrapper methods for all complex input (e.g. {@link Callable}, {@link Runnable}) * and result types (e.g. {@link Future}). *

    @@ -37,7 +38,7 @@ * * @author Sjoerd Talsma */ -public abstract class DelegatingExecutorService extends nl.talsmasoftware.context.delegation.Wrapper implements ExecutorService { +public abstract class DelegatingExecutorService extends Wrapper implements ExecutorService { /** * Creates a new executor service that delegates all methods to the specified delegate. @@ -79,7 +80,7 @@ protected Collection> wrapTasks(Collection> copy = new ArrayList>(tasks.size()); for (Callable task : tasks) { final Callable wrapped = wrap(task); - modification |= (task == wrapped || (task != null && task.equals(wrapped))); // TODO Objects.equals + modification |= (task == wrapped || Objects.equals(task, wrapped)); copy.add(wrapped); } if (modification) wrappedTasks = copy; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java index 65e7e9de..6681bc2e 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java @@ -22,7 +22,7 @@ /** * Abstract baseclass that simplifies wrapping an existing {@link Future} by forwarding all required methods to a - * {@link nl.talsmasoftware.context.delegation.Wrapper#delegate() delegate future} object.
    + * {@link Wrapper#delegate() delegate future} object.
    * The class also provides overridable wrapper methods for {@link #wrapResult(Object) result} * and {@link #wrapException(ExecutionException) exception} outcomes. *

    @@ -32,7 +32,7 @@ * * @author Sjoerd Talsma */ -public abstract class DelegatingFuture extends nl.talsmasoftware.context.delegation.Wrapper> implements Future { +public abstract class DelegatingFuture extends Wrapper> implements Future { protected DelegatingFuture(Future delegate) { super(delegate); diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java index 0a83e990..ba1d59d7 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java @@ -23,7 +23,7 @@ /** * Abstract baseclass that makes it a little easier to wrap existing {@link ExecutorService} implementations by - * forwarding all methods to a {@link Wrapper#delegate() delegate} executor service.
    + * forwarding all methods to a {@link nl.talsmasoftware.context.core.delegation.Wrapper#delegate() delegate} executor service.
    * The class also provides overridable wrapper methods for all complex input (e.g. {@link Callable}, {@link Runnable}) * and result types (e.g. {@link Future}). *

    diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java index 1d01bce5..6740e6e4 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java @@ -20,7 +20,7 @@ /** * Abstract baseclass that simplifies wrapping an existing {@link Future} by forwarding all required methods to a - * {@link Wrapper#delegate() delegate future} object.
    + * {@link nl.talsmasoftware.context.core.delegation.Wrapper#delegate() delegate future} object.
    * The class also provides overridable wrapper methods for {@link #wrapResult(Object) result} * and {@link #wrapException(ExecutionException) exception} outcomes. *

    diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/Wrapper.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/Wrapper.java deleted file mode 100644 index b1bd7f4e..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/Wrapper.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -/** - * Base class for wrapping a {@linkplain #delegate()} object. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.delegation}. - */ -@Deprecated -public abstract class Wrapper extends nl.talsmasoftware.context.core.delegation.Wrapper { - - /** - * Constructor providing a delegate wrapped object. - * - * @param delegate The delegate object being wrapped. - * This may only be null if the delegate() method is - * overridden to provide an alternative non-null result. - */ - protected Wrapper(T delegate) { - super(delegate); - } - - /** - * {@inheritDoc} - */ - @Override - protected T delegate() { - return super.delegate(); - } - - /** - * Accessor to provide a guaranteed non-null delegate instance for use within delegation method - * implementations. - * - * @return The delegate for this wrapper (guaranteed to be non-null). - * @throws NullPointerException with a specific message in case the delegate was null. - * @deprecated This extra check will be removed in the next version, - * {@linkplain #delegate()} must return non-null. - */ - @Deprecated - protected final T nonNullDelegate() { - final T foundDelegate = delegate(); - if (foundDelegate == null) try { - throw new NullPointerException(String.format("No delegate available for %s.", this)); - } catch (StackOverflowError toStringCallsNonNullDelegate) { - throw new NullPointerException(String.format("No delegate available for %s.", getClass().getSimpleName())); - } - return foundDelegate; - } -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java index e8e5dac6..1fb033c1 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ /** * Layered code for delegation such as {@code CallMappingExecutorService}. * - *

    {@linkplain nl.talsmasoftware.context.delegation.Wrapper}

    + *

    {@linkplain nl.talsmasoftware.context.core.delegation.Wrapper}

    *

    * The base class for any delegation in this package. * Any wrapper contains an implementation of {@code hashCode}, {@code equals} @@ -35,4 +35,4 @@ * objects, providing a base executor service that can wrap any background task * by implementing a single {@code map(Callable)} method. */ -package nl.talsmasoftware.context.delegation; \ No newline at end of file +package nl.talsmasoftware.context.delegation; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java similarity index 96% rename from context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java index 6ea4423b..478306a5 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/WrapperTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; import org.junit.jupiter.api.Test; From d4d2757882c3b406d30ca98abb11e54a3cd9934f Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 14:53:05 +0100 Subject: [PATCH 10/41] Remove deprecated WrapperWithContext class. Signed-off-by: Sjoerd Talsma --- .../WrapperWithContextAndConsumer.java | 11 +-- .../WrapperWithContextAndConsumer.java | 2 +- .../delegation/WrapperWithContext.java | 71 ------------------- .../context/delegation/package-info.java | 6 +- 4 files changed, 11 insertions(+), 79 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java index 29c9f0c4..2d089509 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java @@ -16,14 +16,17 @@ package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.delegation.WrapperWithContext; +import nl.talsmasoftware.context.core.delegation.WrapperWithContext; import java.util.function.Consumer; import java.util.function.Supplier; /** - * Package-convenience subclass for {@linkplain WrapperWithContext} that takes Java 8 generic functional interfaces - * {@link Supplier} and {@link Consumer} instead of the specific Java 5 versions. + * A {@linkplain WrapperWithContext} that takes an additional {@link Consumer} accepting a result snapshot, + * captured after the function end. + * + *

    + * This consumer is optional. All clients should avoid taking unnecessary snapshots if the consumer is {@code null}. * * @param The type of the wrapped delegate object. */ @@ -54,7 +57,7 @@ protected WrapperWithContextAndConsumer(ContextSnapshot snapshot, T delegate, Co * @param contextSnapshotConsumer An optional post-action consumer to receive a new context snapshot taken after the action. */ protected WrapperWithContextAndConsumer(Supplier contextSnapshotSupplier, T delegate, Consumer contextSnapshotConsumer) { - super(contextSnapshotSupplier == null ? null : contextSnapshotSupplier::get, delegate); + super(contextSnapshotSupplier, delegate); this.contextSnapshotConsumer = contextSnapshotConsumer; } diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java index c9f3c7a4..3da0bf55 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java +++ b/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java @@ -16,7 +16,7 @@ package nl.talsmasoftware.context.functions; import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.delegation.WrapperWithContext; +import nl.talsmasoftware.context.core.delegation.WrapperWithContext; import java.util.Optional; import java.util.function.Consumer; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java deleted file mode 100644 index 0749b354..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/WrapperWithContext.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Supplier; - -/** - * Wrapper that also contains a fixed context snapshot. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.delegation}. - */ -@Deprecated -public abstract class WrapperWithContext extends nl.talsmasoftware.context.core.delegation.WrapperWithContext { - - /** - * Creates a new Wrapper with the specified context snapshot. - * - * @param snapshot The context snapshot (required, non-{@code null}) - * @param delegate The wrapped delegate object providing core functionality - */ - protected WrapperWithContext(final ContextSnapshot snapshot, final T delegate) { - super(snapshot, delegate); - } - - /** - * Wraps the delegate and provides a context snapshot. - *

    - * Note: Make sure the supplier function does not obtain the context snapshot - * from any threadlocal storage! The wrapper is designed to propagate contexts from one thread to another. - * Therefore, the snapshot must be {@link nl.talsmasoftware.context.ContextManagers#createContextSnapshot() captured} - * in the source thread and {@link ContextSnapshot#reactivate() reactivated} in the target thread. - * If unsure, please use the - * {@link #WrapperWithContext(ContextSnapshot, Object) constructor with snapshot} instead. - * - * @param supplier The supplier for the (fixed!) context snapshot. - * This can be a straightforward 'holder' object or an ongoing background call. - * Please do not make this supplier function access any {@code ThreadLocal} value, - * as the wrapper is designed to propagate the snapshot from thread to thread! - * @param delegate The delegate object to be wrapped. - * @see #WrapperWithContext(ContextSnapshot, Object) - */ - protected WrapperWithContext(Supplier supplier, T delegate) { - super(supplier, delegate); - } - - /** - * Calls the supplier for the context snapshot, making sure it is called only once for this wrapper instance. - * - * @return The snapshot value. - */ - protected ContextSnapshot snapshot() { - return super.snapshot(); - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java index 1fb033c1..84e7d07f 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java @@ -25,12 +25,12 @@ * and {@code nonNullDelegate()}. The latter validates that the delegate is non-null. * *

    - * The {@linkplain nl.talsmasoftware.context.delegation.WrapperWithContext} is + * The {@linkplain nl.talsmasoftware.context.core.delegation.WrapperWithContext} is * just a wrapper that also contains a context snapshot (or a supplier for it). * - *

    {@linkplain nl.talsmasoftware.context.delegation.CallMappingExecutorService}

    + *

    {@linkplain nl.talsmasoftware.context.core.delegation.CallMappingExecutorService}

    *

    - * A {@linkplain nl.talsmasoftware.context.delegation.DelegatingExecutorService} that maps + * A {@linkplain nl.talsmasoftware.context.core.delegation.DelegatingExecutorService} that maps * all {@linkplain java.lang.Runnable} tasks in {@linkplain java.util.concurrent.Callable} * objects, providing a base executor service that can wrap any background task * by implementing a single {@code map(Callable)} method. From c637edc576f902acb4d2893433bee46488c84ee2 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 20:38:22 +0100 Subject: [PATCH 11/41] Remove deprecated DelegatingFuture class. Signed-off-by: Sjoerd Talsma --- .../context/delegation/DelegatingFuture.java | 41 ------------------- .../delegation/DelegatingFutureTest.java | 5 ++- 2 files changed, 3 insertions(+), 43 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java deleted file mode 100644 index 6740e6e4..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingFuture.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * Abstract baseclass that simplifies wrapping an existing {@link Future} by forwarding all required methods to a - * {@link nl.talsmasoftware.context.core.delegation.Wrapper#delegate() delegate future} object.
    - * The class also provides overridable wrapper methods for {@link #wrapResult(Object) result} - * and {@link #wrapException(ExecutionException) exception} outcomes. - *

    - * Although this class does implement all required methods of {@link Future} it is still declared as an - * abstract class.
    - * This is because it does not provide any value in itself. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.delegation}. - */ -@Deprecated -public abstract class DelegatingFuture extends nl.talsmasoftware.context.core.delegation.DelegatingFuture { - - protected DelegatingFuture(Future delegate) { - super(delegate); - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java index 5e9e2bde..356d622b 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java @@ -15,6 +15,7 @@ */ package nl.talsmasoftware.context.delegation; +import nl.talsmasoftware.context.core.delegation.DelegatingFuture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,14 +50,14 @@ */ public class DelegatingFutureTest { - private static class TestDelegatingFuture extends DelegatingFuture { + private static class TestDelegatingFuture extends nl.talsmasoftware.context.core.delegation.DelegatingFuture { private TestDelegatingFuture(Future delegate) { super(delegate); } } Future delegate; - DelegatingFuture subject; + DelegatingFuture subject; @BeforeEach public void setUp() { From 1ac5e5f52f6d3ed6b4a24723506a877bb102a5aa Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 20:41:00 +0100 Subject: [PATCH 12/41] Remove deprecated DelegatingExecutorService class. Signed-off-by: Sjoerd Talsma --- .../CallMappingExecutorService.java | 2 +- .../delegation/DelegatingExecutorService.java | 89 ------------------- .../DelegatingExecutorServiceTest.java | 2 +- .../delegation/DelegatingFutureTest.java | 3 +- .../MappingExecutorServiceTest.java | 2 +- 5 files changed, 4 insertions(+), 94 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/delegation/DelegatingExecutorServiceTest.java (99%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/delegation/DelegatingFutureTest.java (97%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/delegation/MappingExecutorServiceTest.java (99%) diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java index 74eee340..eb96d37e 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java @@ -26,7 +26,7 @@ * * @author Sjoerd Talsma */ -public abstract class CallMappingExecutorService extends nl.talsmasoftware.context.delegation.DelegatingExecutorService { +public abstract class CallMappingExecutorService extends DelegatingExecutorService { /** * Constructor to create a new wrapper around the specified {@link ExecutorService service delegate}. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java deleted file mode 100644 index ba1d59d7..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/DelegatingExecutorService.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -/** - * Abstract baseclass that makes it a little easier to wrap existing {@link ExecutorService} implementations by - * forwarding all methods to a {@link nl.talsmasoftware.context.core.delegation.Wrapper#delegate() delegate} executor service.
    - * The class also provides overridable wrapper methods for all complex input (e.g. {@link Callable}, {@link Runnable}) - * and result types (e.g. {@link Future}). - *

    - * Although this class does implements all required methods of {@link ExecutorService} it is still declared - * as an abstract class.
    - * This is because it does not provide any value in itself. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.delegation}. - */ -@Deprecated -public abstract class DelegatingExecutorService extends nl.talsmasoftware.context.core.delegation.DelegatingExecutorService { - - /** - * Creates a new executor service that delegates all methods to the specified delegate. - * - * @param delegate The delegate ExecutorService being wrapped. - * This may only be null if the delegate() method is - * overridden to provide an alternative non-null result. - * @see #delegate() - */ - protected DelegatingExecutorService(ExecutorService delegate) { - super(delegate); - } - - protected Callable wrap(Callable source) { - return super.wrap(source); - } - - protected Runnable wrap(Runnable source) { - return super.wrap(source); - } - - protected Future wrap(Future source) { - return super.wrap(source); - } - - /** - * Default way of mapping a {@link Collection} of {@link Callable} objects: - * Create a new collection and add each {@link #wrap(Callable) individually wrapped} object into it. - * - * @param tasks The tasks to be mapped. - * @param The common result type for the collection of tasks. - * @return A collection with each individual task wrapped. - * @see #wrap(Callable) - */ - protected Collection> wrapTasks(Collection> tasks) { - return super.wrapTasks(tasks); - } - - /** - * Default way of mapping a {@link Collection} of {@link Future} objects: - * Create a new list and add each {@link #wrap(Future) individually wrapped} object into it. - * - * @param futures The futures to be mapped. - * @param The common result type for the collection of futures. - * @return A list with each individual future wrapped. - * @see #wrap(Future) - */ - protected List> wrapFutures(Collection> futures) { - return super.wrapFutures(futures); - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingExecutorServiceTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java similarity index 99% rename from context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingExecutorServiceTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java index 572f59bd..4a75abb5 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingExecutorServiceTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java similarity index 97% rename from context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java index 356d622b..95e9b469 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/DelegatingFutureTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; -import nl.talsmasoftware.context.core.delegation.DelegatingFuture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/MappingExecutorServiceTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java similarity index 99% rename from context-propagation/src/test/java/nl/talsmasoftware/context/delegation/MappingExecutorServiceTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java index 71f40827..d626fb3f 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/delegation/MappingExecutorServiceTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; From 79b45b5d0c4a3265f18693c5308d9af155a54fdd Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Mon, 4 Nov 2024 20:45:10 +0100 Subject: [PATCH 13/41] Remove deprecated CallMappingExecutorService class. Signed-off-by: Sjoerd Talsma --- .../ContextAwareExecutorService.java | 3 +- .../core/delegation/CallableToRunnable.java | 2 - .../{ => core}/delegation/package-info.java | 2 +- .../CallMappingExecutorService.java | 55 ------------------- 4 files changed, 3 insertions(+), 59 deletions(-) rename context-propagation/src/main/java/nl/talsmasoftware/context/{ => core}/delegation/package-info.java (97%) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/delegation/CallMappingExecutorService.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java index ab08301b..a7ba41db 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java @@ -17,6 +17,7 @@ import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.delegation.CallMappingExecutorService; import java.io.Closeable; import java.util.concurrent.Callable; @@ -37,7 +38,7 @@ * * @author Sjoerd Talsma */ -public class ContextAwareExecutorService extends nl.talsmasoftware.context.delegation.CallMappingExecutorService { +public class ContextAwareExecutorService extends CallMappingExecutorService { private static final Logger LOGGER = Logger.getLogger(ContextAwareExecutorService.class.getName()); public ContextAwareExecutorService(ExecutorService delegate) { diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java index 1d1cc1f7..b7fa58e8 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java @@ -15,8 +15,6 @@ */ package nl.talsmasoftware.context.core.delegation; -import nl.talsmasoftware.context.delegation.CallMappingExecutorService; - import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java similarity index 97% rename from context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java rename to context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java index 84e7d07f..d8b34e43 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java @@ -35,4 +35,4 @@ * objects, providing a base executor service that can wrap any background task * by implementing a single {@code map(Callable)} method. */ -package nl.talsmasoftware.context.delegation; +package nl.talsmasoftware.context.core.delegation; diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/CallMappingExecutorService.java b/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/CallMappingExecutorService.java deleted file mode 100644 index e6541313..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/delegation/CallMappingExecutorService.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.delegation; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; - -/** - * Abstract base-class that makes it a little easier to schedule tasks - * ({@link java.lang.Runnable Runnable} or {@link Callable} objects) using an existing {@link ExecutorService} while - * providing a custom {@link #wrap(Callable) mapping} for all tasks before they get scheduled. - * - * @author Sjoerd Talsma - * @deprecated This will be replace by {@code Supplier} from Java 8. - */ -@Deprecated -public abstract class CallMappingExecutorService extends nl.talsmasoftware.context.core.delegation.CallMappingExecutorService { - - /** - * Constructor to create a new wrapper around the specified {@link ExecutorService service delegate}. - * - * @param delegate The delegate executor service that does the heavy lifting of executing all tasks once they are mapped. - */ - protected CallMappingExecutorService(ExecutorService delegate) { - super(delegate); - } - - /** - * Default implementation to wrap {@link Runnable} objects before scheduling: - * {@link #wrap(Callable) wrap} it into a {@link Callable} object and return an - * unwrapped {@link Runnable} implementation that simply runs by calling the mapped {@link Callable} object. - * - * @param runnable The runnable object to be wrapped. - * @return The wrapped runnable (the default implementation re-uses the callable mapping). - * @see #wrap(Callable) - */ - @Override - protected Runnable wrap(final Runnable runnable) { - return super.wrap(runnable); - } - -} From e461f0cdf058b2c0ac2d6fdd1a5b62f5001a8ab5 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 10:37:00 +0100 Subject: [PATCH 14/41] Migrate most of the code to the new API. Signed-off-by: Sjoerd Talsma --- .../ContextAwareCompletableFutureTest.java | 110 +++++------ .../function}/BiConsumerWithContextTest.java | 33 ++-- .../{ => dummy}/DummyContextManager.java | 17 +- .../functions/BiFunctionWithContextTest.java | 4 +- .../functions/BiPredicateWithContextTest.java | 4 +- .../BinaryOperatorWithContextTest.java | 4 +- .../BooleanSupplierWithContextTest.java | 4 +- .../functions/ConsumerWithContextTest.java | 8 +- .../functions/FunctionWithContextTest.java | 4 +- .../functions/PredicateWithContextTest.java | 4 +- .../functions/RunnableWithContextTest.java | 4 +- .../functions/SupplierWithContextTest.java | 4 +- .../UnaryOperatorWithContextTest.java | 4 +- .../context/futures/CompletedFutureTest.java | 12 +- .../ContextAwareCompletableFutureTest.java | 110 +++++------ .../context/futures/FailedFutureTest.java | 12 +- .../nl.talsmasoftware.context.ContextManager | 1 - ....talsmasoftware.context.api.ContextManager | 1 + .../src/test/resources/logging.properties | 1 + .../talsmasoftware/context/api/Context.java | 2 - .../context/api/ContextManager.java | 13 +- .../context/core/ContextManagers.java | 122 ++++-------- .../context/PriorityServiceLoaderTest.java | 113 ----------- .../AutoInitializingContextManager.java | 18 +- .../ClearableContextManagerTest.java | 61 +----- .../ClearableDummyContextManager.java | 8 +- .../DummyManagerOfClearableContext.java | 61 ------ .../{ => core}/ContextManagersTest.java | 86 ++------- .../context/core/ContextObserversTest.java | 141 -------------- .../{ => core}/ContextSnapshotTest.java | 29 +-- .../{ => core}/NoContextManagersTest.java | 8 +- .../core/PriorityServiceLoaderTest.java | 115 ------------ .../ContextAwareExecutorServiceTest.java | 19 +- .../context/{ => dummy}/DummyContext.java | 20 +- .../{ => dummy}/DummyContextManager.java | 7 +- .../{ => dummy}/ThrowingContextManager.java | 34 +++- .../observer/ContextObserversTest.java | 176 ------------------ .../observer/DeprecatedContextManager.java | 43 ----- .../context/observer/Observed.java | 88 --------- .../observer/SimpleContextObserver.java | 46 ----- .../observer/ThrowingContextObserver.java | 50 ----- .../observer/ThrowingContextObserverTest.java | 63 ------- .../nl.talsmasoftware.context.ContextManager | 6 - ....talsmasoftware.context.api.ContextManager | 4 + ...asoftware.context.observer.ContextObserver | 2 - .../context/locale/LocaleContext.java | 46 ++--- .../context/locale/LocaleContextManager.java | 28 ++- ...talsmasoftware.context.api.ContextManager} | 0 .../locale/LocaleContextManagerTest.java | 79 ++++---- .../Log4j2ThreadContextManager.java | 40 +--- ...talsmasoftware.context.api.ContextManager} | 0 .../Log4j2ThreadContextManagerTest.java | 49 +---- .../opentracing/ContextScopeManager.java | 11 +- .../context/opentracing/SpanManager.java | 41 ++-- .../ContextScopeManagerObserver.java | 12 +- .../opentracing/ContextScopeManagerTest.java | 2 +- .../context/opentracing/SpanManagerTest.java | 15 +- .../servletrequest/ServletRequestContext.java | 45 ++--- .../ServletRequestContextAsyncListener.java | 8 +- .../ServletRequestContextFilter.java | 14 +- .../ServletRequestContextManager.java | 18 +- ...talsmasoftware.context.api.ContextManager} | 0 ...ervletRequestContextAsyncListenerTest.java | 6 +- .../ServletRequestContextManagerTest.java | 41 ++-- .../context/mdc/MdcManager.java | 25 --- .../context/mdc/package-info.java | 19 -- .../context/slf4j/mdc/Slf4jMdcManager.java | 82 ++++---- ...talsmasoftware.context.api.ContextManager} | 0 .../slf4j/mdc/Slf4jMdcManagerTest.java | 11 +- .../SpringSecurityContextManager.java | 60 +++--- ...talsmasoftware.context.api.ContextManager} | 0 .../SpringSecurityContextManagerTest.java | 17 +- 72 files changed, 558 insertions(+), 1787 deletions(-) rename context-propagation-java8/src/test/java/nl/talsmasoftware/context/{functions => core/function}/BiConsumerWithContextTest.java (82%) rename context-propagation-java8/src/test/java/nl/talsmasoftware/context/{ => dummy}/DummyContextManager.java (85%) delete mode 100644 context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager create mode 100644 context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/PriorityServiceLoaderTest.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/ContextManagersTest.java (72%) delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/ContextSnapshotTest.java (65%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => core}/NoContextManagersTest.java (88%) delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityServiceLoaderTest.java rename context-propagation/src/test/java/nl/talsmasoftware/context/{executors => core/concurrent}/ContextAwareExecutorServiceTest.java (87%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => dummy}/DummyContext.java (67%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => dummy}/DummyContextManager.java (88%) rename context-propagation/src/test/java/nl/talsmasoftware/context/{ => dummy}/ThrowingContextManager.java (68%) delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/Observed.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/SimpleContextObserver.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserver.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java delete mode 100644 context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager create mode 100644 context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager delete mode 100644 context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver rename locale-context/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) rename log4j2-propagation/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) rename servletrequest-propagation/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) delete mode 100644 slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/MdcManager.java delete mode 100644 slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/package-info.java rename slf4j-propagation/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) rename spring-security-context/src/main/resources/META-INF/services/{nl.talsmasoftware.context.ContextManager => nl.talsmasoftware.context.api.ContextManager} (100%) diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java index f89c92c7..9384b30c 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -58,11 +58,11 @@ public class ContextAwareCompletableFutureTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } private static void assertContext(String expectedValue) { - assertThat("Active context value", manager.getActiveContext().getValue(), is(expectedValue)); + assertThat("Active context value", manager.getActiveContextValue(), is(expectedValue)); } private static Supplier stringSupplier(String name, String requiredContext) { @@ -81,8 +81,8 @@ public void testDefaultConstructor() throws ExecutionException, InterruptedExcep CompletableFuture future1 = new ContextAwareCompletableFuture<>(); // should have a new snapshot with foo ctx.close(); - CompletableFuture future2 = future1.thenApply(value -> manager.getActiveContext().getValue() + value); - assertThat(manager.getActiveContext(), is(nullValue())); + CompletableFuture future2 = future1.thenApply(value -> manager.getActiveContextValue() + value); + assertThat(manager.getActiveContextValue(), is(nullValue())); assertThat(future1.isDone(), is(false)); assertThat(future2.isDone(), is(false)); @@ -533,14 +533,14 @@ public void testHandle() throws ExecutionException, InterruptedException { assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()).get(), is("Jody")); + }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()).get(), is("Trudy")); + }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Trudy")); } } @@ -551,14 +551,14 @@ public void testHandleAsync() throws ExecutionException, InterruptedException { assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()).get(), is("Jody")); + }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()).get(), is("Trudy")); + }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Trudy")); } } @@ -569,14 +569,14 @@ public void testHandleAsync_executor() throws ExecutionException, InterruptedExc assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue(), contextUnawareThreadpool).get(), is("Jody")); + }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { manager.initializeNewContext("Trudy"); throw exception; - }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue(), contextUnawareThreadpool).get(), is("Trudy")); + }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool).get(), is("Trudy")); } } @@ -588,7 +588,7 @@ public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedEx manager.initializeNewContext("Trudy"); throw exception; }).takeNewSnapshot().handle((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); @@ -599,7 +599,7 @@ public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedEx manager.initializeNewContext("Trudy"); throw exception; }, null, null, true).handle((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); @@ -614,7 +614,7 @@ public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, Interrup manager.initializeNewContext("Trudy"); throw exception; }).takeNewSnapshot().handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); @@ -625,7 +625,7 @@ public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, Interrup manager.initializeNewContext("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); @@ -640,7 +640,7 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, manager.initializeNewContext("Trudy"); throw exception; }).takeNewSnapshot().handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }, contextUnawareThreadpool).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); @@ -651,7 +651,7 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, manager.initializeNewContext("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }, contextUnawareThreadpool).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); @@ -665,7 +665,7 @@ public void testExceptionally() throws ExecutionException, InterruptedException manager.initializeNewContext("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }).exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Gringo")); return null; }).get(); @@ -676,7 +676,7 @@ public void testExceptionally() throws ExecutionException, InterruptedException manager.initializeNewContext("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }, null, null, true).exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Jules Winnfield")); return null; }).get(); @@ -690,7 +690,7 @@ public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, Int manager.initializeNewContext("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }).takeNewSnapshot().exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Gringo")); manager.initializeNewContext("-" + val); return null; @@ -702,7 +702,7 @@ public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, Int manager.initializeNewContext("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }, null, null, true).exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Jules Winnfield")); manager.initializeNewContext("-" + val); return null; @@ -831,7 +831,7 @@ public void testThenCombineAsyncAndTakeNewSnapshot_executor() throws ExecutionEx @Test public void testThenAcceptBoth() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContext().getValue() + stringB, is("QuentinTarantino"))).get(); + ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))).get(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); } } @@ -839,7 +839,7 @@ public void testThenAcceptBoth() throws ExecutionException, InterruptedException @Test public void testThenAcceptBothAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContext().getValue() + stringB, is("QuentinTarantino"))).get(); + ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))).get(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); } } @@ -847,7 +847,7 @@ public void testThenAcceptBothAsync() throws ExecutionException, InterruptedExce @Test public void testThenAcceptBothAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContext().getValue() + stringB, is("QuentinTarantino")), contextUnawareThreadpool).get(); + ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino")), contextUnawareThreadpool).get(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); } } @@ -856,7 +856,7 @@ public void testThenAcceptBothAsync_executor() throws ExecutionException, Interr public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); @@ -864,7 +864,7 @@ public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, In try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Quentin by Tarantino")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-Quentin by Tarantino")).get(); @@ -875,7 +875,7 @@ public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, In public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); @@ -883,7 +883,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionExceptio try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("QuentinTarantino")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-QuentinTarantino")).get(); @@ -894,7 +894,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionExceptio public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBothAsync(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); @@ -903,7 +903,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws Executio try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("QuentinTarantino")); manager.initializeNewContext("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-QuentinTarantino")).get(); @@ -948,7 +948,7 @@ public void testRunAfterBothAsync_executor() throws ExecutionException, Interrup public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-French Fries")).get(); @@ -956,7 +956,7 @@ public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, Inte try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-Ketchup")).get(); @@ -967,7 +967,7 @@ public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, Inte public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-French Fries")).get(); @@ -975,7 +975,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }).thenAccept(aVoid -> assertContext("-Ketchup")).get(); @@ -986,7 +986,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-French Fries")).get(); @@ -994,7 +994,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionE try (Context ctx = manager.initializeNewContext("French Fries")) { ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-Ketchup")).get(); @@ -1010,7 +1010,7 @@ public void testApplyToEither(boolean takeNewSnapshot) throws ExecutionException ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEither(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContext().getValue())); + Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEither(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContextValue())); // verify assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); @@ -1026,7 +1026,7 @@ public void testApplyToEitherAsync(boolean takeNewSnapshot) throws ExecutionExce ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEitherAsync(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContext().getValue())); + Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEitherAsync(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContextValue())); // verify assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); @@ -1042,7 +1042,7 @@ public void testApplyToEitherAsync_executor(boolean takeNewSnapshot) throws Exec ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEitherAsync(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContext().getValue()), contextUnawareThreadpool); + Future result = future1.takeNewSnapshot(takeNewSnapshot).applyToEitherAsync(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", input, Thread.currentThread().getName(), manager.getActiveContextValue()), contextUnawareThreadpool); // verify assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); @@ -1158,18 +1158,18 @@ public void testRunAfterEitherAsync_executor(boolean takeNewSnapshot) { public void testThenCompose() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContext().getValue())).get(), is("JohnJohn")); + }).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnJohn")); } try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }, null, null, true).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContext().getValue())).get(), is("JohnTravolta")); + }, null, null, true).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnTravolta")); } } @@ -1177,18 +1177,18 @@ public void testThenCompose() throws ExecutionException, InterruptedException { public void testThenComposeAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContext().getValue())).get(), is("JohnJohn")); + }).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnJohn")); } try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }, null, null, true).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContext().getValue())).get(), is("JohnTravolta")); + }, null, null, true).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnTravolta")); } } @@ -1196,18 +1196,18 @@ public void testThenComposeAsync() throws ExecutionException, InterruptedExcepti public void testThenComposeAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }).thenComposeAsync(value -> completedFuture(value + manager.getActiveContext().getValue()), contextUnawareThreadpool).get(), is("JohnJohn")); + }).thenComposeAsync(value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool).get(), is("JohnJohn")); } try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; - }, null, null, true).thenComposeAsync(value -> completedFuture(value + manager.getActiveContext().getValue()), contextUnawareThreadpool).get(), is("JohnTravolta")); + }, null, null, true).thenComposeAsync(value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool).get(), is("JohnTravolta")); } } @@ -1258,7 +1258,7 @@ public void testAllOf() throws ExecutionException, InterruptedException { ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.isDone(), is(false)); @@ -1279,7 +1279,7 @@ public void testAllOfWithSpecificSnapshot() throws ExecutionException, Interrupt ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(snapshot, cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.isDone(), is(false)); @@ -1298,7 +1298,7 @@ public void testAnyOf() throws ExecutionException, InterruptedException { ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf2.complete("Value 2"); assertThat(result.get(), is("Vincent Vega")); @@ -1318,7 +1318,7 @@ public void testAnyOfWithSpecificSnapshot() throws ExecutionException, Interrupt ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(snapshot, cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.get(), is("Vincent Vega")); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java similarity index 82% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java rename to context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java index 4fc39a50..9a732d09 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -32,8 +31,8 @@ import java.util.function.BiConsumer; import static java.lang.String.format; -import static nl.talsmasoftware.context.DummyContextManager.currentValue; -import static nl.talsmasoftware.context.DummyContextManager.setCurrentValue; +import static nl.talsmasoftware.context.dummy.DummyContextManager.currentValue; +import static nl.talsmasoftware.context.dummy.DummyContextManager.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -53,7 +52,7 @@ public class BiConsumerWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach @@ -108,10 +107,8 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat("Thread context must propagate", currentValue(), is(Optional.of("New value"))); - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }); t.start(); @@ -119,23 +116,23 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { } @Test - public void testAndThen() throws InterruptedException, IOException { - setCurrentValue("Old value"); + public void testAndThen() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - BiConsumer consumer = new BiConsumerWithContext( + setCurrentValue("Old value"); + BiConsumer consumer1 = new BiConsumerWithContext<>( ContextManagers.createContextSnapshot(), (a, b) -> setCurrentValue(a + " " + b + ", " + currentValue().orElse("NO VALUE")), - s -> snapshotHolder[0] = s) - .andThen((a, b) -> setCurrentValue(a.toUpperCase() + " " + b.toLowerCase() + ", " + currentValue() - .orElse("NO VALUE"))); + s -> snapshotHolder[0] = s); + BiConsumer consumer2 = consumer1.andThen( + (a, b) -> setCurrentValue(a.toUpperCase() + " " + b.toLowerCase() + ", " + currentValue().orElse("NO VALUE"))); - Thread t = new Thread(() -> consumer.accept("New", "value")); + Thread t = new Thread(() -> consumer2.accept("New", "value")); t.start(); t.join(); assertThat(currentValue(), is(Optional.of("Old value"))); - try (Closeable reactivated = snapshotHolder[0].reactivate()) { + try (Reactivation reactivated = snapshotHolder[0].reactivate()) { assertThat(currentValue(), is(Optional.of("NEW value, New value, Old value"))); } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java similarity index 85% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java rename to context-propagation-java8/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java index 9f191cea..b2535253 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/DummyContextManager.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.dummy; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; import java.util.Optional; import java.util.logging.Logger; @@ -28,8 +29,12 @@ public Context initializeNewContext(String value) { return setCurrentValue(value); } - public Context getActiveContext() { - return DummyContext.current(); + public String getActiveContextValue() { + return currentValue().orElse(null); + } + + public void clear() { + clearAllContexts(); } public static Optional currentValue() { @@ -52,14 +57,14 @@ public static Context setCurrentValue(String value) { /** * For easier testing */ - public static void clear() { + public static void clearAllContexts() { LOGGER.fine(() -> "Clearing values in " + Thread.currentThread() + ", currently: " + DummyContext.current()); DummyContext.clear(); } private static final class DummyContext extends AbstractThreadLocalContext { private DummyContext(String newValue) { - super(DummyContextManager.class, newValue); + super(newValue); } private static void clear() { diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java index a62ddb45..b472bc6a 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -53,7 +53,7 @@ public class BiFunctionWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java index 74c88e98..c018849b 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -52,7 +52,7 @@ public class BiPredicateWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java index 6d40ac15..d640666c 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -55,7 +55,7 @@ public class BinaryOperatorWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java index 9fd0103c..2c4676bb 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java @@ -16,8 +16,8 @@ package nl.talsmasoftware.context.functions; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,7 +49,7 @@ public class BooleanSupplierWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java index 60bc163c..26aca887 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java @@ -16,9 +16,9 @@ package nl.talsmasoftware.context.functions; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,8 +31,8 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import static nl.talsmasoftware.context.DummyContextManager.currentValue; -import static nl.talsmasoftware.context.DummyContextManager.setCurrentValue; +import static nl.talsmasoftware.context.dummy.DummyContextManager.currentValue; +import static nl.talsmasoftware.context.dummy.DummyContextManager.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -52,7 +52,7 @@ public class ConsumerWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java index cad2eb91..c03c211a 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -52,7 +52,7 @@ public class FunctionWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java index d0053a99..37217035 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -53,7 +53,7 @@ public class PredicateWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java index 785d3ceb..63f63f60 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,7 +49,7 @@ public class RunnableWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java index e7f2dd85..565beed5 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,7 +51,7 @@ public class SupplierWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java index ee592945..ec414dbf 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.functions; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -50,7 +50,7 @@ public class UnaryOperatorWithContextTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @BeforeEach diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java index a94398f3..75f3468a 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java @@ -16,8 +16,8 @@ package nl.talsmasoftware.context.futures; import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,12 +34,12 @@ public class CompletedFutureTest { private static final DummyContextManager manager = new DummyContextManager(); - private static final UnaryOperator addActiveContextValue = s -> s + ", " + manager.getActiveContext().getValue(); + private static final UnaryOperator addActiveContextValue = s -> s + ", " + manager.getActiveContextValue(); @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @Test @@ -50,7 +50,7 @@ public void testCompletedFutureTakesNewSnapshot() throws ExecutionException, Int CompletableFuture future = completed.thenApplyAsync(addActiveContextValue); assertThat(future.get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Brown")); + assertThat(manager.getActiveContextValue(), is("Mr. Brown")); } @Test @@ -63,7 +63,7 @@ public void testCompletedFutureAppliesGivenSnapshot() throws ExecutionException, CompletableFuture future = completed.thenApplyAsync(addActiveContextValue); assertThat(future.get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Orange")); + assertThat(manager.getActiveContextValue(), is("Mr. Orange")); } @Test @@ -74,7 +74,7 @@ public void testCompletedStageTakesNewSnapshot() throws ExecutionException, Inte CompletionStage stage = completed.thenApplyAsync(addActiveContextValue); assertThat(stage.toCompletableFuture().get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Brown")); + assertThat(manager.getActiveContextValue(), is("Mr. Brown")); } } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java index b961e987..0e0b24ca 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java @@ -15,10 +15,10 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -58,11 +58,11 @@ public class ContextAwareCompletableFutureTest { @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } private static void assertContext(String expectedValue) { - assertThat("Active context value", manager.getActiveContext().getValue(), is(expectedValue)); + assertThat("Active context value", manager.getActiveContextValue(), is(expectedValue)); } private static Supplier stringSupplier(String name, String requiredContext) { @@ -81,8 +81,8 @@ public void testDefaultConstructor() throws ExecutionException, InterruptedExcep CompletableFuture future1 = new ContextAwareCompletableFuture<>(); // should have a new snapshot with foo ctx.close(); - CompletableFuture future2 = future1.thenApply(value -> manager.getActiveContext().getValue() + value); - assertThat(manager.getActiveContext(), is(nullValue())); + CompletableFuture future2 = future1.thenApply(value -> manager.getActiveContextValue() + value); + assertThat(manager.getActiveContextValue(), is(nullValue())); assertThat(future1.isDone(), is(false)); assertThat(future2.isDone(), is(false)); @@ -701,7 +701,7 @@ public void testHandle() throws ExecutionException, InterruptedException { manager.initializeNewContext("Trudy"); throw exception; }) - .handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()) + .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) .get(), is("Jody")); } @@ -712,7 +712,7 @@ public void testHandle() throws ExecutionException, InterruptedException { manager.initializeNewContext("Trudy"); throw exception; }, null, null, true) - .handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()) + .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) .get(), is("Trudy")); } @@ -727,7 +727,7 @@ public void testHandleAsync() throws ExecutionException, InterruptedException { manager.initializeNewContext("Trudy"); throw exception; }) - .handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()) + .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) .get(), is("Jody")); } @@ -738,7 +738,7 @@ public void testHandleAsync() throws ExecutionException, InterruptedException { manager.initializeNewContext("Trudy"); throw exception; }, null, null, true) - .handleAsync((voidValue, throwable) -> manager.getActiveContext().getValue()) + .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) .get(), is("Trudy")); } @@ -754,7 +754,7 @@ public void testHandleAsync_executor() throws ExecutionException, InterruptedExc throw exception; }) .handleAsync( - (voidValue, throwable) -> manager.getActiveContext().getValue(), + (voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool) .get(), is("Jody")); @@ -767,7 +767,7 @@ public void testHandleAsync_executor() throws ExecutionException, InterruptedExc throw exception; }, null, null, true) .handleAsync( - (voidValue, throwable) -> manager.getActiveContext().getValue(), + (voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool) .get(), is("Trudy")); @@ -785,7 +785,7 @@ public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedEx }) .takeNewSnapshot() .handle((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }) @@ -801,7 +801,7 @@ public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedEx throw exception; }, null, null, true) .handle((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }) @@ -822,7 +822,7 @@ public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, Interrup }) .takeNewSnapshot() .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }) @@ -838,7 +838,7 @@ public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, Interrup throw exception; }, null, null, true) .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }) @@ -859,7 +859,7 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, }) .takeNewSnapshot() .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }, contextUnawareThreadpool) @@ -875,7 +875,7 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, throw exception; }, null, null, true) .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); manager.initializeNewContext("-" + val); return val; }, contextUnawareThreadpool) @@ -894,7 +894,7 @@ public void testExceptionally() throws ExecutionException, InterruptedException throw new RuntimeException("Bad Motherfucker"); }) .exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Gringo")); return null; }) @@ -908,7 +908,7 @@ public void testExceptionally() throws ExecutionException, InterruptedException throw new RuntimeException("Bad Motherfucker"); }, null, null, true) .exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Jules Winnfield")); return null; }) @@ -926,7 +926,7 @@ public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, Int }) .takeNewSnapshot() .exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Gringo")); manager.initializeNewContext("-" + val); return null; @@ -942,7 +942,7 @@ public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, Int throw new RuntimeException("Bad Motherfucker"); }, null, null, true) .exceptionally(ex -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Jules Winnfield")); manager.initializeNewContext("-" + val); return null; @@ -1138,7 +1138,7 @@ public void testThenAcceptBoth() throws ExecutionException, InterruptedException .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> - assertThat(manager.getActiveContext().getValue() + stringB, + assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))) .get(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); @@ -1152,7 +1152,7 @@ public void testThenAcceptBothAsync() throws ExecutionException, InterruptedExce .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> - assertThat(manager.getActiveContext().getValue() + stringB, + assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))) .get(); assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); @@ -1166,7 +1166,7 @@ public void testThenAcceptBothAsync_executor() throws ExecutionException, Interr .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> - assertThat(manager.getActiveContext().getValue() + stringB, + assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino")), contextUnawareThreadpool) .get(); @@ -1182,7 +1182,7 @@ public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, In .takeNewSnapshot() .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }) @@ -1195,7 +1195,7 @@ public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, In .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Quentin by Tarantino")); manager.initializeNewContext("-" + val); }) @@ -1212,7 +1212,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionExceptio .takeNewSnapshot() .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }) @@ -1225,7 +1225,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionExceptio .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("QuentinTarantino")); manager.initializeNewContext("-" + val); }) @@ -1242,7 +1242,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws Executio .takeNewSnapshot() .thenAcceptBothAsync(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("Pulp Fiction by Tarantino")); manager.initializeNewContext("-" + val); }, @@ -1257,7 +1257,7 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws Executio .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContext().getValue() + stringB; + String val = manager.getActiveContextValue() + stringB; assertThat(val, is("QuentinTarantino")); manager.initializeNewContext("-" + val); }, @@ -1342,7 +1342,7 @@ public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, Inte .runAfterBoth( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }) @@ -1356,7 +1356,7 @@ public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, Inte .runAfterBoth( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }) @@ -1374,7 +1374,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, .runAfterBothAsync( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }) @@ -1388,7 +1388,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, .runAfterBothAsync( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }) @@ -1406,7 +1406,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionE .runAfterBothAsync( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); manager.initializeNewContext("-" + val); }, @@ -1421,7 +1421,7 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionE .runAfterBothAsync( ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { - String val = manager.getActiveContext().getValue(); + String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); manager.initializeNewContext("-" + val); }, @@ -1444,7 +1444,7 @@ public void testApplyToEither(boolean takeNewSnapshot) throws ExecutionException .takeNewSnapshot(takeNewSnapshot) .applyToEither(future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContext().getValue())); + input, Thread.currentThread().getName(), manager.getActiveContextValue())); // verify assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); @@ -1465,7 +1465,7 @@ public void testApplyToEitherAsync(boolean takeNewSnapshot) throws ExecutionExce .applyToEitherAsync( future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContext().getValue())); + input, Thread.currentThread().getName(), manager.getActiveContextValue())); // verify assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); @@ -1486,7 +1486,7 @@ public void testApplyToEitherAsync_executor(boolean takeNewSnapshot) throws Exec .applyToEitherAsync( future2, input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContext().getValue()), + input, Thread.currentThread().getName(), manager.getActiveContextValue()), contextUnawareThreadpool); // verify @@ -1616,24 +1616,24 @@ public void testRunAfterEitherAsync_executor(boolean takeNewSnapshot) { public void testThenCompose() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }) .thenCompose(value -> supplyAsync( - () -> value + manager.getActiveContext().getValue())) + () -> value + manager.getActiveContextValue())) .get(), is("JohnJohn")); } try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }, null, null, true) .thenCompose(value -> supplyAsync( - () -> value + manager.getActiveContext().getValue())) + () -> value + manager.getActiveContextValue())) .get(), is("JohnTravolta")); } @@ -1643,24 +1643,24 @@ public void testThenCompose() throws ExecutionException, InterruptedException { public void testThenComposeAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }) .thenComposeAsync(value -> supplyAsync( - () -> value + manager.getActiveContext().getValue())) + () -> value + manager.getActiveContextValue())) .get(), is("JohnJohn")); } try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }, null, null, true) .thenComposeAsync(value -> supplyAsync( - () -> value + manager.getActiveContext().getValue())) + () -> value + manager.getActiveContextValue())) .get(), is("JohnTravolta")); } @@ -1670,12 +1670,12 @@ public void testThenComposeAsync() throws ExecutionException, InterruptedExcepti public void testThenComposeAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }) .thenComposeAsync( - value -> completedFuture(value + manager.getActiveContext().getValue()), + value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool) .get(), is("JohnJohn")); @@ -1683,12 +1683,12 @@ public void testThenComposeAsync_executor() throws ExecutionException, Interrupt try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { - String current = manager.getActiveContext().getValue(); + String current = manager.getActiveContextValue(); manager.initializeNewContext("Travolta"); return current; }, null, null, true) .thenComposeAsync( - value -> completedFuture(value + manager.getActiveContext().getValue()), + value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool) .get(), is("JohnTravolta")); @@ -1745,7 +1745,7 @@ public void testAllOf() throws ExecutionException, InterruptedException { ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.isDone(), is(false)); @@ -1768,7 +1768,7 @@ public void testAllOfWithSpecificSnapshot() throws ExecutionException, Interrupt ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(snapshot, cf1, cf2); manager.initializeNewContext("Jules Winnfield"); - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContext().getValue()); + ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.isDone(), is(false)); @@ -1790,7 +1790,7 @@ public void testAnyOf() throws ExecutionException, InterruptedException { manager.initializeNewContext("Jules Winnfield"); ContextAwareCompletableFuture result = future - .thenApplyAsync(s -> manager.getActiveContext().getValue()); + .thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf2.complete("Value 2"); assertThat(result.get(), is("Vincent Vega")); @@ -1813,7 +1813,7 @@ public void testAnyOfWithSpecificSnapshot() throws ExecutionException, Interrupt manager.initializeNewContext("Jules Winnfield"); ContextAwareCompletableFuture result = future - .thenApplyAsync(s -> manager.getActiveContext().getValue()); + .thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); cf1.complete("Value 1"); assertThat(result.get(), is("Vincent Vega")); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java index 0b60f6c3..9db6fdb9 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java +++ b/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.futures; -import nl.talsmasoftware.context.DummyContextManager; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,12 +35,12 @@ public class FailedFutureTest { private static final DummyContextManager manager = new DummyContextManager(); private static final BiFunction addActiveContextValue = - (value, ex) -> (ex == null ? value : ex.getMessage()) + ", " + manager.getActiveContext().getValue(); + (value, ex) -> (ex == null ? value : ex.getMessage()) + ", " + manager.getActiveContextValue(); @BeforeEach @AfterEach public void clearDummyContext() { - DummyContextManager.clear(); + DummyContextManager.clearAllContexts(); } @Test @@ -51,7 +51,7 @@ public void testFailedFutureTakesNewSnapshot() throws ExecutionException, Interr CompletableFuture future = completed.handleAsync(addActiveContextValue); assertThat(future.get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Brown")); + assertThat(manager.getActiveContextValue(), is("Mr. Brown")); } @Test @@ -64,7 +64,7 @@ public void testFailedFutureAppliesGivenSnapshot() throws ExecutionException, In CompletableFuture future = completed.handleAsync(addActiveContextValue); assertThat(future.get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Orange")); + assertThat(manager.getActiveContextValue(), is("Mr. Orange")); } @Test @@ -75,7 +75,7 @@ public void testFailedStageTakesNewSnapshot() throws ExecutionException, Interru CompletionStage stage = completed.handleAsync(addActiveContextValue); assertThat(stage.toCompletableFuture().get(), is("Mr. Blue, Mr. Blonde")); - assertThat(manager.getActiveContext().getValue(), is("Mr. Brown")); + assertThat(manager.getActiveContextValue(), is("Mr. Brown")); } } diff --git a/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager deleted file mode 100644 index 791450ee..00000000 --- a/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.DummyContextManager diff --git a/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..c4a9ba40 --- /dev/null +++ b/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.dummy.DummyContextManager diff --git a/context-propagation-java8/src/test/resources/logging.properties b/context-propagation-java8/src/test/resources/logging.properties index 4786544f..b61da601 100644 --- a/context-propagation-java8/src/test/resources/logging.properties +++ b/context-propagation-java8/src/test/resources/logging.properties @@ -1,2 +1,3 @@ # Use no logging by default during tests to keep the output as clean as possible. .level=OFF +nl.talsmasoftware.context.dummy.DummyContextManager.level=FINE diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java b/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java index 3c09ffb3..3c201145 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java @@ -15,8 +15,6 @@ */ package nl.talsmasoftware.context.api; -import nl.talsmasoftware.context.ContextManager; - import java.io.Closeable; /** diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java index 7f0f056f..cf7803d7 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java @@ -15,8 +15,6 @@ */ package nl.talsmasoftware.context.api; -import nl.talsmasoftware.context.clearable.Clearable; - /** * The service definition a {@linkplain Context} manager. * @@ -27,7 +25,7 @@ * @param type of the context value * @author Sjoerd Talsma */ -public interface ContextManager extends nl.talsmasoftware.context.ContextManager, Clearable { +public interface ContextManager { /** * Initialize a new context containing the specified value. @@ -41,15 +39,6 @@ public interface ContextManager extends nl.talsmasoftware.context.ContextMana */ Context initializeNewContext(T value); - /** - * The currently active context, or null if no context is active. - * - * @return The active context or null if there is none. - * @deprecated In favour of {@link #getActiveContextValue} - */ - @Deprecated - Context getActiveContext(); - /** * The value of the currently active context, or {@code null} if no context is active. * diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index d24e2821..2e932b1e 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -15,12 +15,11 @@ */ package nl.talsmasoftware.context.core; -import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; import nl.talsmasoftware.context.api.ContextObserver; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; -import nl.talsmasoftware.context.clearable.Clearable; import nl.talsmasoftware.context.core.delegation.Wrapper; import java.util.ArrayList; @@ -50,13 +49,13 @@ public final class ContextManagers { * The service loader that loads (and possibly caches) {@linkplain ContextManager} instances in prioritized order. */ private static final PriorityServiceLoader CONTEXT_MANAGERS = - new PriorityServiceLoader(ContextManager.class); + new PriorityServiceLoader<>(ContextManager.class); /** * Registered observers. */ private static final CopyOnWriteArrayList OBSERVERS = - new CopyOnWriteArrayList(); + new CopyOnWriteArrayList<>(); /** * Private constructor to avoid instantiation of this class. @@ -67,8 +66,8 @@ private ContextManagers() { /** * This method is able to create a 'snapshot' from the current - * {@link ContextManager#getActiveContext() active context} from all known {@link ContextManager} - * implementations. + * {@link ContextManager#getActiveContextValue() active context value} + * from all known {@link ContextManager} implementations. * *

    * This snapshot is returned as a single object that can be temporarily @@ -80,18 +79,18 @@ private ContextManagers() { */ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapshot() { final long start = System.nanoTime(); - final List managers = new LinkedList(); - final List values = new LinkedList(); + final List> managers = new LinkedList<>(); + final List values = new LinkedList<>(); Long managerStart = null; - for (ContextManager manager : getContextManagers()) { + for (ContextManager manager : getContextManagers()) { managerStart = System.nanoTime(); try { - final Context activeContext = manager.getActiveContext(); - if (activeContext != null) { - values.add(activeContext.getValue()); + final Object activeContextValue = manager.getActiveContextValue(); + if (activeContextValue != null) { + values.add(activeContextValue); managers.add(manager); if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Active context of " + manager + " added to new snapshot: " + activeContext + "."); + LOGGER.finest("Active context value of " + manager + " added to new snapshot: " + activeContextValue); } Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext"); } else if (LOGGER.isLoggable(Level.FINEST)) { @@ -126,31 +125,18 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho * An even better strategy would be to clear the context right before returning a used thread to the pool * as this will allow any unclosed contexts to be garbage collected. Besides preventing contextual issues, * this reduces the risk of memory leaks by unbalanced context calls. - *

    - * For context managers that are not {@linkplain Clearable} and contain an active {@linkplain Context} - * that is not {@code Clearable} either, this active context will be closed normally. */ public static void clearActiveContexts() { final long start = System.nanoTime(); Long managerStart = null; - for (ContextManager manager : getContextManagers()) { + for (ContextManager manager : getContextManagers()) { managerStart = System.nanoTime(); try { - // TODO add ContextObserver.onClear() - if (manager instanceof Clearable) { - ((Clearable) manager).clear(); - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Active context of " + manager + " was cleared."); - } - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear"); - } else { - Context activeContext = manager.getActiveContext(); - if (activeContext != null) { - clearContext(manager, activeContext); - } else if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("There is no active context for " + manager + " to be cleared."); - } + manager.clear(); + if (LOGGER.isLoggable(Level.FINEST)) { + LOGGER.finest("Active context of " + manager + " was cleared."); } + Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear"); } catch (RuntimeException rte) { LOGGER.log(Level.WARNING, "Exception clearing active context from " + manager + ".", rte); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear.exception"); @@ -180,15 +166,15 @@ public static boolean registerContextObserver(ContextObserver con } // Find ContextManager to register. - ObservableContextManager observableContextManager = null; - ContextManager contextManager = null; - for (ContextManager manager : getContextManagers()) { + ObservableContextManager observableContextManager = null; + ContextManager contextManager = null; + for (ContextManager manager : getContextManagers()) { if (manager instanceof ObservableContextManager - && ((ObservableContextManager) manager).observes(observedContextManagerType)) { - observableContextManager = (ObservableContextManager) manager; + && ((ObservableContextManager) manager).observes(observedContextManagerType)) { + observableContextManager = (ObservableContextManager) manager; break; } else if (observedContextManagerType.isInstance(manager)) { - contextManager = manager; + contextManager = (ContextManager) manager; break; } } @@ -223,7 +209,7 @@ public static boolean registerContextObserver(ContextObserver con */ public static boolean unregisterContextObserver(ContextObserver contextObserver) { boolean unregistered = false; - for (ObservableContextManager observer : OBSERVERS) { + for (ObservableContextManager observer : OBSERVERS) { unregistered |= observer.observers.remove(contextObserver); synchronized (observer) { if (observer.observers.isEmpty()) { @@ -296,30 +282,6 @@ public void remove() { }; } - private static void clearContext(ContextManager manager, Context context) { - final long start = System.nanoTime(); - final Class contextType = context.getClass(); - if (context instanceof Clearable) { - ((Clearable) context).clear(); - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Active context of " + manager + " was cleared."); - } - } else { - int maxAttempts = 255; - while (context != null && --maxAttempts > 0) { - context.close(); - context = manager.getActiveContext(); - } - if (context != null) { - Logger.getLogger(manager.getClass().getName()).warning( - "Possible endless loop prevented clearing the active context for " + manager + - ". Could it be that this manager returns a non-null context by default " + - "and has not implemented the Clearable interface?"); - } - } - Timers.timed(System.nanoTime() - start, contextType, "clear"); - } - /** * Implementation of the createContextSnapshot functionality that can reactivate all values from the * snapshot in each corresponding {@link ContextManager}. @@ -329,7 +291,7 @@ private static final class ContextSnapshotImpl implements nl.talsmasoftware.cont private final ContextManager[] managers; private final Object[] values; - private ContextSnapshotImpl(List managers, List values) { + private ContextSnapshotImpl(List> managers, List values) { this.managers = managers.toArray(MANAGER_ARRAY); this.values = values.toArray(); } @@ -354,7 +316,7 @@ public Reactivation reactivate() { } alreadyReactivated.close(); } catch (RuntimeException rte) { - addSuppressedOrWarn(reactivationException, rte, "Could not close already reactivated context."); + reactivationException.addSuppressed(rte); } } throw reactivationException; @@ -390,10 +352,6 @@ private ReactivationImpl(List> reactivated) { this.reactivated = reactivated; } - public Void getValue() { - return null; - } - public void close() { RuntimeException closeException = null; // close in reverse order of reactivation @@ -403,7 +361,7 @@ public void close() { reactivated.close(); } catch (RuntimeException rte) { if (closeException == null) closeException = rte; - else addSuppressedOrWarn(closeException, rte, "Exception closing the reactivated context."); + else closeException.addSuppressed(rte); } } if (closeException != null) throw closeException; @@ -415,15 +373,6 @@ public String toString() { } } - @SuppressWarnings("Since15") // That's why we catch the LinkageError here - private static void addSuppressedOrWarn(Throwable exception, Throwable toSuppress, String message) { - if (exception != null && toSuppress != null) try { - exception.addSuppressed(toSuppress); - } catch (LinkageError le) { - LOGGER.log(Level.WARNING, message, toSuppress); - } - } - private static final class ObservableContextManager extends Wrapper> implements ContextManager { private final CopyOnWriteArrayList> observers; @@ -436,9 +385,14 @@ private boolean observes(Class> contextManagerType) return contextManagerType.isInstance(delegate()); } - private T getActiveContextValue() { - final Context activeContext = delegate().getActiveContext(); - return activeContext != null ? activeContext.getValue() : null; + @Override + public T getActiveContextValue() { + return delegate().getActiveContextValue(); + } + + @Override + public void clear() { + delegate().clear(); } private void notifyActivated(T newValue, T oldValue) { @@ -461,6 +415,7 @@ private void notifyDeactivated(T deactivatedValue, T restoredValue) { } } + @Override public Context initializeNewContext(final T newValue) { final T oldValue = getActiveContextValue(); final Context context = delegate().initializeNewContext(newValue); @@ -479,11 +434,6 @@ public void close() { }; } - @Deprecated - public Context getActiveContext() { - return delegate().getActiveContext(); - } - @Override public String toString() { return getClass().getSimpleName() + '{' + delegate() + ", " + observers + '}'; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityServiceLoaderTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityServiceLoaderTest.java deleted file mode 100644 index 2865631d..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityServiceLoaderTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import org.junit.jupiter.api.Test; - -import javax.annotation.Priority; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * Test for the PriorityServiceLoader class. - * - * @author Sjoerd Talsma - */ -public class PriorityServiceLoaderTest { - - @Test - public void testWithoutServiceType() { - try { - new PriorityServiceLoader(null); - fail("Exception expected"); - } catch (NullPointerException expected) { - assertThat(expected.getMessage(), is(notNullValue())); - } - } - - @Test - public void testMultipleIterations() { - List> managers = new ArrayList>(); - PriorityServiceLoader subject = new PriorityServiceLoader(ContextManager.class); - for (ContextManager mgr : subject) assertThat(mgr, is(notNullValue())); - for (ContextManager mgr : subject) managers.add(mgr); - - assertThat(managers, hasItem(new DummyContextManager())); - } - - @Test - public void testUnimplementedService() { - Collection found = new ArrayList(); - for (UnimplementedService svc : new PriorityServiceLoader(UnimplementedService.class)) { - found.add(svc); - } - assertThat(found, is(empty())); - } - - @Test - public void testSingleService() { - assertThat(new PriorityServiceLoader(ServiceWithSingleImplementation.class), contains( - instanceOf(SingleImplementationWithLowestPriority.class) - )); - } - - @Test - public void testPrioritization() { - assertThat(new PriorityServiceLoader(TestService.class), contains( - instanceOf(HighestPrioImplementation.class), - instanceOf(ImplementationWithoutPriority.class), - instanceOf(LowestPrioImplementation.class) - )); - } - - interface UnimplementedService { - } - - interface ServiceWithSingleImplementation { - } - - interface TestService { - } - - @Priority(Integer.MIN_VALUE) - public static class LowestPrioImplementation implements TestService { - - } - - @Priority(0) - public static class HighestPrioImplementation implements TestService { - - } - - public static class ImplementationWithoutPriority implements TestService { - - } - - @Priority(Integer.MIN_VALUE) - public static class SingleImplementationWithLowestPriority implements ServiceWithSingleImplementation { - - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java index e5de5708..cbe94a62 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.clearable; -import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; public class AutoInitializingContextManager implements ContextManager { private static final ThreadLocal CTX = new ThreadLocal() { @@ -26,15 +26,23 @@ protected DummyContext initialValue() { } }; - public Context getActiveContext() { - return CTX.get(); - } - + @Override public Context initializeNewContext(String value) { CTX.set(new DummyContext(CTX.get(), value)); return CTX.get(); } + @Override + public String getActiveContextValue() { + DummyContext dummyContext = CTX.get(); + return dummyContext != null ? dummyContext.getValue() : null; + } + + @Override + public void clear() { + CTX.remove(); + } + private static class DummyContext implements Context { private final DummyContext previous; private String value; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java index 730f3283..2278696c 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,14 +15,15 @@ */ package nl.talsmasoftware.context.clearable; -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; -import nl.talsmasoftware.context.ThrowingContextManager; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.ThrowingContextManager; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; /** * Tests for clearing context managers. @@ -31,61 +32,19 @@ */ public class ClearableContextManagerTest { private static ContextManager CLEARABLE = new ClearableDummyContextManager(); - private static ContextManager CONTEXT_CLEARABLE = new DummyManagerOfClearableContext(); private static ContextManager AUTO_INITIALIZING = new AutoInitializingContextManager(); - private static ContextManager MANAGER_OF_ABSTRACTTLC = new DummyContextManager(); @Test public void testClearActiveContexts_byManager() { - assertThat(CLEARABLE, is(instanceOf(Clearable.class))); + assertThat(CLEARABLE, is(instanceOf(ContextManager.class))); CLEARABLE.initializeNewContext("First value"); CLEARABLE.initializeNewContext("Second value"); CLEARABLE.initializeNewContext("Third value"); - assertThat(CLEARABLE.getActiveContext().getValue(), is("Third value")); + assertThat(CLEARABLE.getActiveContextValue(), is("Third value")); ContextManagers.clearActiveContexts(); - assertThat(CLEARABLE.getActiveContext(), is(nullValue())); - } - - @Test - public void testClearActiveContexts_byClearableContext() { - assertThat(CONTEXT_CLEARABLE, is(not(instanceOf(Clearable.class)))); - - CONTEXT_CLEARABLE.initializeNewContext("First value"); - CONTEXT_CLEARABLE.initializeNewContext("Second value"); - CONTEXT_CLEARABLE.initializeNewContext("Third value"); - assertThat(CONTEXT_CLEARABLE.getActiveContext(), is(instanceOf(Clearable.class))); - assertThat(CONTEXT_CLEARABLE.getActiveContext().getValue(), is("Third value")); - - ContextManagers.clearActiveContexts(); - assertThat(CONTEXT_CLEARABLE.getActiveContext(), is(nullValue())); - } - - @Test - public void testClearActiveContexts_byAbstractTLC() { - assertThat(MANAGER_OF_ABSTRACTTLC, is(not(instanceOf(Clearable.class)))); - - MANAGER_OF_ABSTRACTTLC.initializeNewContext("First value"); - MANAGER_OF_ABSTRACTTLC.initializeNewContext("Second value"); - MANAGER_OF_ABSTRACTTLC.initializeNewContext("Third value"); - assertThat(MANAGER_OF_ABSTRACTTLC.getActiveContext().getValue(), is("Third value")); - - ContextManagers.clearActiveContexts(); - assertThat(MANAGER_OF_ABSTRACTTLC.getActiveContext(), is(nullValue())); - } - - @Test - public void testClearActiveContexts_autoReinitializeNewContext() { - assertThat(AUTO_INITIALIZING, is(not(instanceOf(Clearable.class)))); - - AUTO_INITIALIZING.initializeNewContext("First value"); - AUTO_INITIALIZING.initializeNewContext("Second value"); - AUTO_INITIALIZING.initializeNewContext("Third value"); - assertThat(AUTO_INITIALIZING.getActiveContext().getValue(), is("Third value")); - - ContextManagers.clearActiveContexts(); - assertThat(AUTO_INITIALIZING.getActiveContext().getValue(), is(nullValue())); + assertThat(CLEARABLE.getActiveContextValue(), is(nullValue())); } @Test diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java index c8ec90bf..d095eaa1 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java @@ -16,12 +16,14 @@ package nl.talsmasoftware.context.clearable; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; -public class ClearableDummyContextManager implements ClearableContextManager { +public class ClearableDummyContextManager implements ContextManager { private static final ThreadLocal CTX = new ThreadLocal(); - public Context getActiveContext() { - return CTX.get(); + public String getActiveContextValue() { + DummyContext current = CTX.get(); + return current != null ? current.getValue() : null; } public Context initializeNewContext(String value) { diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java b/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java deleted file mode 100644 index 16fd9dfa..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/DummyManagerOfClearableContext.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.clearable; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.api.Context; - -public class DummyManagerOfClearableContext implements ContextManager { - private static final ThreadLocal CTX = new ThreadLocal(); - - public Context getActiveContext() { - return CTX.get(); - } - - public Context initializeNewContext(String value) { - return new DummyContext(value); - } - - private static class DummyContext implements Context, Clearable { - private final DummyContext previous; - private String value; - - private DummyContext(String value) { - this.previous = CTX.get(); - this.value = value; - CTX.set(this); - } - - public String getValue() { - return value; - } - - /** - * Only for testing! DO NOT COPY! This is not a safe implementation. - *

    - * Please see AbstractThreadLocalContext for reference code if you wish manage a stack of contexts! - */ - public void close() { - CTX.set(previous); - this.value = null; - } - - public void clear() { - CTX.remove(); - } - - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java similarity index 72% rename from context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index 42fe62af..5c398820 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -13,12 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.core; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; -import nl.talsmasoftware.context.observer.SimpleContextObserver; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; +import nl.talsmasoftware.context.dummy.DummyContext; +import nl.talsmasoftware.context.dummy.DummyContextManager; +import nl.talsmasoftware.context.dummy.ThrowingContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,17 +37,12 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import static nl.talsmasoftware.context.observer.Observed.activated; -import static nl.talsmasoftware.context.observer.Observed.deactivated; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; @@ -53,11 +50,12 @@ * @author Sjoerd Talsma */ public class ContextManagersTest { + DummyContextManager dummyManager = new DummyContextManager(); @BeforeEach @AfterEach public void resetContexts() { - DummyContext.reset(); + ContextManagers.clearActiveContexts(); } @BeforeEach @@ -66,13 +64,6 @@ public void resetContextClassLoader() { ContextManagers.useClassLoader(null); } - @BeforeEach - @AfterEach - public void clearObserved() { - SimpleContextObserver.observedContextManager = null; - SimpleContextObserver.observed.clear(); - } - @Test public void testUnsupportedConstructor() { Constructor[] constructors = ContextManagers.class.getDeclaredConstructors(); @@ -83,9 +74,7 @@ public void testUnsupportedConstructor() { constructors[0].setAccessible(true); constructors[0].newInstance(); fail("Exception expected."); - } catch (IllegalAccessException e) { - fail("InvocationTargetException expected."); - } catch (InstantiationException e) { + } catch (IllegalAccessException | InstantiationException e) { fail("InvocationTargetException expected."); } catch (InvocationTargetException e) { assertThat(e.getCause(), is(instanceOf(UnsupportedOperationException.class))); @@ -94,7 +83,7 @@ public void testUnsupportedConstructor() { @Test public void testSnapshot_inSameThread() throws IOException { - DummyContext.reset(); + dummyManager.clear(); assertThat(DummyContext.currentValue(), is(nullValue())); DummyContext ctx1 = new DummyContext("initial value"); @@ -148,11 +137,8 @@ public String call() throws Exception { threadResult = threadpool.submit(new Callable() { public String call() throws Exception { String res = DummyContext.currentValue(); - DummyContext inThread = new DummyContext("in-thread value"); - try { + try (DummyContext inThread = new DummyContext("in-thread value")) { res += ", " + DummyContext.currentValue(); - } finally { - inThread.close(); } return res + ", " + DummyContext.currentValue(); } @@ -197,7 +183,7 @@ public void testCreateSnapshot_ExceptionHandling() throws IOException { Closeable reactivation = snapshot.reactivate(); assertThat(DummyContext.currentValue(), is("blah")); reactivation.close(); - assertThat(DummyContext.current(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); } @Test @@ -210,21 +196,17 @@ public void testReactivateSnapshot_ExceptionHandling() { ThrowingContextManager.onInitialize = reactivationException; assertThat(DummyContext.currentValue(), is("foo")); - assertThat(mgr.getActiveContext().getValue(), is("bar")); + assertThat(mgr.getActiveContextValue(), is("bar")); ctx1.close(); ctx2.close(); assertThat(DummyContext.currentValue(), is(nullValue())); - assertThat(mgr.getActiveContext(), is(nullValue())); - try { - snapshot.reactivate(); - fail("Exception expected"); - } catch (RuntimeException expected) { - assertThat(expected, is(sameInstance(reactivationException))); - } + assertThat(mgr.getActiveContextValue(), is(nullValue())); + RuntimeException expected = assertThrows(RuntimeException.class, snapshot::reactivate); + // foo + bar mustn't be set after exception! assertThat(DummyContext.currentValue(), is(nullValue())); - assertThat(mgr.getActiveContext(), is(nullValue())); + assertThat(mgr.getActiveContextValue(), is(nullValue())); } @Test @@ -235,11 +217,7 @@ public void testConcurrentSnapshots_fixedClassLoader() throws ExecutionException try { List> snapshots = new ArrayList>(threadcount); for (int i = 0; i < threadcount; i++) { - snapshots.add(threadpool.submit(new Callable() { - public ContextSnapshot call() throws Exception { - return ContextManagers.createContextSnapshot(); - } - })); + snapshots.add(threadpool.submit(ContextManagers::createContextSnapshot)); } for (int i = 0; i < threadcount; i++) { @@ -250,32 +228,4 @@ public ContextSnapshot call() throws Exception { } } - @Test - @SuppressWarnings("unchecked") - public void testOnActivate() { - SimpleContextObserver.observedContextManager = DummyContextManager.class; - Class reportedClass = ContextManager.class; - ContextManagers.onActivate(reportedClass, "activated value", "previous value"); - assertThat(SimpleContextObserver.observed, is(empty())); - - SimpleContextObserver.observedContextManager = ContextManager.class; - reportedClass = DummyContextManager.class; - ContextManagers.onActivate(reportedClass, "activated value", "previous value"); - assertThat(SimpleContextObserver.observed, hasItem(activated(equalTo("activated value")))); - } - - @Test - @SuppressWarnings("unchecked") - public void testOnDeactivate() { - SimpleContextObserver.observedContextManager = DummyContextManager.class; - Class reportedClass = ContextManager.class; - ContextManagers.onDeactivate(reportedClass, "deactivated value", "restored value"); - assertThat(SimpleContextObserver.observed, is(empty())); - - SimpleContextObserver.observedContextManager = ContextManager.class; - reportedClass = DummyContextManager.class; - ContextManagers.onDeactivate(reportedClass, "deactivated value", "restored value"); - assertThat(SimpleContextObserver.observed, hasItem(deactivated(equalTo("deactivated value")))); - } - } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java deleted file mode 100644 index 11371597..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextObserversTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core; - -import nl.talsmasoftware.context.DummyContextManager; -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.api.ContextManager; -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.observer.ContextObserver; -import nl.talsmasoftware.context.observer.Observed; -import nl.talsmasoftware.context.observer.SimpleContextObserver; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class ContextObserversTest { - private static final DummyContextManager dummyManager = new DummyContextManager(); - - static final class NoopContextManager implements ContextManager { - public Context initializeNewContext(Object value) { - return null; - } - - public Context getActiveContext() { - return null; - } - - public Object getActiveContextValue() { - return null; - } - - public void clear() { - } - } - - @Test - void registerContextObserver_nullObserver() { - RuntimeException expected = assertThrows(NullPointerException.class, new Executable() { - public void execute() { - ContextManagers.registerContextObserver(null, DummyContextManager.class); - } - }); - assertThat(expected.getMessage(), is("Context observer must not be null.")); - } - - @Test - void registerContextObserver_nullContextManagerType() { - final ContextObserver observer = new SimpleContextObserver(); - RuntimeException expected = assertThrows(NullPointerException.class, new Executable() { - public void execute() { - ContextManagers.registerContextObserver(observer, null); - } - }); - assertThat(expected.getMessage(), is("Observed ContextManager type must not be null.")); - } - - @Test - void registerContextObserver_forUnknownContextManagerType() { - final ContextObserver observer = new SimpleContextObserver(); - - boolean result = ContextManagers.registerContextObserver(observer, NoopContextManager.class); - - assertThat(result, is(false)); - } - - @Test - void testConcurrentRegistrations() throws ExecutionException, InterruptedException { - // prepare - final ExecutorService threadPool = Executors.newFixedThreadPool(10); - final SimpleContextObserver observer = new SimpleContextObserver(); - try { - final Callable registerTask = new Callable() { - public Integer call() { - return ContextManagers.registerContextObserver(observer, DummyContextManager.class) ? 1 : 0; - } - }; - List> results = new ArrayList>(); - - // execute - for (int i = 0; i < 100; i++) { - results.add(threadPool.submit(registerTask)); - } - - // verify - int sum = 0; - for (Future result : results) { - sum += result.get(); - } - assertThat(sum, is(1)); - } finally { - ContextManagers.unregisterContextObserver(observer); - threadPool.shutdownNow(); - } - } - - @Test - void testObserveActivatedSnapshot() { - SimpleContextObserver observer = new SimpleContextObserver(); - try { - nl.talsmasoftware.context.api.Context ctx = dummyManager.initializeNewContext("Snapshot value"); - ContextManagers.registerContextObserver(observer, DummyContextManager.class); - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - ctx.close(); - - snapshot.reactivate().close(); - - assertThat(SimpleContextObserver.observed, contains( - Observed.activated(equalTo("Snapshot value")), - Observed.deactivated(equalTo("Snapshot value")))); - } finally { - ContextManagers.unregisterContextObserver(observer); - dummyManager.clear(); - } - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java similarity index 65% rename from context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java index 44138eb7..865ca7d6 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ContextSnapshotTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.core; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.Test; import java.io.Closeable; @@ -35,37 +36,25 @@ public class ContextSnapshotTest { @Test public void testSnapshotToString() { - Context ctx = MGR.initializeNewContext("Dummy value"); - try { + try (Context ctx = MGR.initializeNewContext("Dummy value")) { assertThat(ContextManagers.createContextSnapshot(), hasToString(startsWith("ContextSnapshot{size="))); - } finally { - ctx.close(); } } @Test public void testSnapshotReactivate() throws IOException { - Context ctx = MGR.initializeNewContext("Old value"); - try { + try (Context ctx = MGR.initializeNewContext("Old value")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - Context ctx2 = MGR.initializeNewContext("New value"); - try { + try (Context ctx2 = MGR.initializeNewContext("New value")) { + assertThat(MGR.getActiveContextValue(), is("New value")); - assertThat(MGR.getActiveContext().getValue(), is("New value")); - Closeable reactivation = snapshot.reactivate(); - try { - assertThat(MGR.getActiveContext().getValue(), is("Old value")); + try (Closeable reactivation = snapshot.reactivate()) { + assertThat(MGR.getActiveContextValue(), is("Old value")); assertThat(reactivation, hasToString(startsWith("ReactivatedContext{size="))); - } finally { - reactivation.close(); } - assertThat(MGR.getActiveContext().getValue(), is("New value")); - } finally { - ctx2.close(); + assertThat(MGR.getActiveContextValue(), is("New value")); } - } finally { - ctx.close(); } } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java similarity index 88% rename from context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java index 4a9100f6..b33db0eb 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/NoContextManagersTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.core; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -50,7 +52,7 @@ public void resetDefaultClassLoader() { @Test public void testReactivate_withoutContextManagers() throws IOException { Context ctx1 = new DummyContext("foo"); - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); + ContextSnapshot snapshot = nl.talsmasoftware.context.ContextManagers.createContextSnapshot(); ctx1.close(); Closeable reactivated = snapshot.reactivate(); @@ -59,7 +61,7 @@ public void testReactivate_withoutContextManagers() throws IOException { @Test public void testCreateSnapshot_withoutContextManagers() throws IOException { - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); + ContextSnapshot snapshot = nl.talsmasoftware.context.ContextManagers.createContextSnapshot(); assertThat(snapshot, is(notNullValue())); Closeable reactivated = snapshot.reactivate(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityServiceLoaderTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityServiceLoaderTest.java deleted file mode 100644 index 1dc62874..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityServiceLoaderTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.DummyContextManager; -import org.junit.jupiter.api.Test; - -import javax.annotation.Priority; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * Test for the PriorityServiceLoader class. - * - * @author Sjoerd Talsma - */ -public class PriorityServiceLoaderTest { - - @Test - public void testWithoutServiceType() { - try { - new PriorityServiceLoader(null); - fail("Exception expected"); - } catch (NullPointerException expected) { - assertThat(expected.getMessage(), is(notNullValue())); - } - } - - @Test - public void testMultipleIterations() { - List> managers = new ArrayList>(); - PriorityServiceLoader subject = new PriorityServiceLoader(ContextManager.class); - for (ContextManager mgr : subject) assertThat(mgr, is(notNullValue())); - for (ContextManager mgr : subject) managers.add(mgr); - - assertThat(managers, hasItem(new DummyContextManager())); - } - - @Test - public void testUnimplementedService() { - Collection found = new ArrayList(); - for (UnimplementedService svc : new PriorityServiceLoader(UnimplementedService.class)) { - found.add(svc); - } - assertThat(found, is(empty())); - } - - @Test - public void testSingleService() { - assertThat(new PriorityServiceLoader(ServiceWithSingleImplementation.class), contains( - instanceOf(SingleImplementationWithLowestPriority.class) - )); - } - - @Test - public void testPrioritization() { - assertThat(new PriorityServiceLoader(TestService.class), contains( - instanceOf(HighestPrioImplementation.class), - instanceOf(ImplementationWithoutPriority.class), - instanceOf(LowestPrioImplementation.class) - )); - } - - interface UnimplementedService { - } - - interface ServiceWithSingleImplementation { - } - - interface TestService { - } - - @Priority(Integer.MIN_VALUE) - public static class LowestPrioImplementation implements TestService { - - } - - @Priority(0) - public static class HighestPrioImplementation implements TestService { - - } - - public static class ImplementationWithoutPriority implements TestService { - - } - - @Priority(Integer.MIN_VALUE) - public static class SingleImplementationWithLowestPriority implements ServiceWithSingleImplementation { - - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java similarity index 87% rename from context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java index bfa7248d..89868ac0 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/executors/ContextAwareExecutorServiceTest.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.executors; +package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; -import nl.talsmasoftware.context.ThrowingContextManager; -import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContextManager; +import nl.talsmasoftware.context.dummy.ThrowingContextManager; +import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,12 +40,7 @@ public class ContextAwareExecutorServiceTest { private static DummyContextManager dummyContextManager = new DummyContextManager(); private static ThrowingContextManager throwingContextManager = new ThrowingContextManager(); - private static Callable getDummyContext = new Callable() { - public String call() { - Context active = dummyContextManager.getActiveContext(); - return active == null ? null : active.getValue(); - } - }; + private static Callable getDummyContext = dummyContextManager::getActiveContextValue; private ContextAwareExecutorService executor; @@ -78,7 +73,7 @@ public void testContext() throws ExecutionException, InterruptedException { dummyContextManager.initializeNewContext("The quick brown fox jumps over the lazy dog"); Future dummy = executor.submit(getDummyContext); dummyContextManager.initializeNewContext("god yzal eht revo spmuj xof nworb kciuq ehT"); - assertThat(dummyContextManager.getActiveContext().getValue(), is("god yzal eht revo spmuj xof nworb kciuq ehT")); + assertThat(dummyContextManager.getActiveContextValue(), is("god yzal eht revo spmuj xof nworb kciuq ehT")); assertThat(dummy.get(), is("The quick brown fox jumps over the lazy dog")); } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java similarity index 67% rename from context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java index c6a2f85f..8f14990e 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContext.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.dummy; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; /** * @author Sjoerd Talsma */ -final class DummyContext extends AbstractThreadLocalContext { +public final class DummyContext extends AbstractThreadLocalContext { private static final ThreadLocal INSTANCE = AbstractThreadLocalContext.threadLocalInstanceOf(DummyContext.class); - DummyContext(String newValue) { - super(DummyContextManager.class, newValue); + public DummyContext(String newValue) { + super(newValue); } // Public for testing! @@ -34,16 +34,12 @@ public boolean isClosed() { return super.isClosed(); } - static Context current() { - return AbstractThreadLocalContext.current(DummyContext.class); - } - - static String currentValue() { - final Context currentContext = current(); + public static String currentValue() { + final Context currentContext = INSTANCE.get(); return currentContext != null ? currentContext.getValue() : null; } - static void reset() { + public static void reset() { INSTANCE.remove(); } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java similarity index 88% rename from context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java index 98d181a6..aa678ceb 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/DummyContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.dummy; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; /** * Trivial manager around the {@link DummyContext} implementation to be registered as service provider. @@ -28,8 +29,8 @@ public Context initializeNewContext(String value) { return new DummyContext(value); } - public Context getActiveContext() { - return DummyContext.current(); + public String getActiveContextValue() { + return DummyContext.currentValue(); } public void clear() { diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java similarity index 68% rename from context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java rename to context-propagation/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java index 6a0a66bc..4d11cb64 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/ThrowingContextManager.java +++ b/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.dummy; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; /** * Badly behaved {@link ContextManager} implementation that can throw things at us for testing purposes. @@ -24,7 +25,7 @@ * @author Sjoerd Talsma */ public class ThrowingContextManager implements ContextManager { - public static RuntimeException inConstructor = null, onInitialize = null, onGet = null, onClose = null; + public static RuntimeException inConstructor = null, onInitialize = null, onGet = null, onClose = null, onClear = null; public ThrowingContextManager() { if (inConstructor != null) try { @@ -34,6 +35,7 @@ public ThrowingContextManager() { } } + @Override public Context initializeNewContext(String value) { if (onInitialize != null) try { throw onInitialize; @@ -43,13 +45,24 @@ public Context initializeNewContext(String value) { return new Ctx(value); } - public Context getActiveContext() { + @Override + public String getActiveContextValue() { if (onGet != null) try { throw onGet; } finally { onGet = null; } - return Ctx.current(); + return Ctx.currentValue(); + } + + @Override + public void clear() { + if (onClear != null) try { + throw onClear; + } finally { + onClear = null; + } + Ctx.remove(); } @Override @@ -59,11 +72,16 @@ public String toString() { private final static class Ctx extends AbstractThreadLocalContext { private Ctx(String newValue) { - super(ThrowingContextManager.class, newValue); + super(newValue); + } + + private static String currentValue() { + Ctx current = AbstractThreadLocalContext.current(Ctx.class); + return current != null ? current.getValue() : null; } - private static Ctx current() { - return current(Ctx.class); + private static void remove() { + AbstractThreadLocalContext.threadLocalInstanceOf(Ctx.class).remove(); } @Override diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java deleted file mode 100644 index f97df70a..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ContextObserversTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.DummyContextManager; -import nl.talsmasoftware.context.ThrowingContextManager; -import nl.talsmasoftware.context.api.Context; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import static nl.talsmasoftware.context.observer.Observed.Action.ACTIVATE; -import static nl.talsmasoftware.context.observer.Observed.Action.DEACTIVATE; -import static nl.talsmasoftware.context.observer.Observed.activated; -import static nl.talsmasoftware.context.observer.Observed.deactivated; -import static nl.talsmasoftware.context.observer.SimpleContextObserver.observed; -import static nl.talsmasoftware.context.observer.SimpleContextObserver.observedContextManager; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.jupiter.api.Assertions.fail; - -@SuppressWarnings("deprecation") -public class ContextObserversTest { - - @BeforeEach - @AfterEach - public void clearObserved() { - observedContextManager = null; - observed.clear(); - } - - @Test - public void testUnsupportedConstructor() throws IllegalAccessException, InstantiationException { - Constructor[] constructors = ContextObservers.class.getDeclaredConstructors(); - assertThat("Number of constructors", constructors.length, is(1)); - assertThat("Constructor parameters", constructors[0].getParameterTypes().length, is(0)); - assertThat("Constructor accessibility", constructors[0].isAccessible(), is(false)); - try { - constructors[0].setAccessible(true); - constructors[0].newInstance(); - fail("InvocationTargetException expected."); - } catch (InvocationTargetException expected) { - assertThat(expected.getCause(), is(instanceOf(UnsupportedOperationException.class))); - } - } - - @Test - public void testSimpleContextObserver_observingNull() { - final ContextManager manager = new DummyContextManager(); - final Context ctx = manager.initializeNewContext("Activated context"); - try { - assertThat(manager.getActiveContext().getValue(), is("Activated context")); - assertThat(observed, is(Matchers.empty())); - } finally { - ctx.close(); - } - assertThat(observed, is(Matchers.empty())); - } - - @Test - public void testSimpleContextObserver_observingDifferentContextManager() { - observedContextManager = ThrowingContextManager.class; - final ContextManager manager = new DummyContextManager(); - final Context ctx = manager.initializeNewContext("Activated context"); - try { - assertThat(manager.getActiveContext().getValue(), is("Activated context")); - assertThat(observed, is(Matchers.empty())); - } finally { - ctx.close(); - } - assertThat(observed, is(Matchers.empty())); - } - - @Test - public void testSimpleContextObserver_observingSpecificContextManager() { - observedContextManager = DummyContextManager.class; - final ContextManager manager = new DummyContextManager(); - final Context ctx = manager.initializeNewContext("Activated context"); - try { - assertThat(manager.getActiveContext().getValue(), is("Activated context")); - assertThat(observed, contains(new Observed(ACTIVATE, "Activated context", null))); - } finally { - ctx.close(); - } - assertThat(observed, contains( - new Observed(ACTIVATE, "Activated context", null), - new Observed(DEACTIVATE, "Activated context", null))); - } - - @Test - public void testSimpleContextObserver_observingAnyContextManager() { - observedContextManager = ContextManager.class; - final ContextManager manager = new DummyContextManager(); - final Context ctx = manager.initializeNewContext("Activated context"); - try { - assertThat(manager.getActiveContext().getValue(), is("Activated context")); - assertThat(observed, contains(new Observed(ACTIVATE, "Activated context", null))); - } finally { - ctx.close(); - } - assertThat(observed, contains( - new Observed(ACTIVATE, "Activated context", null), - new Observed(DEACTIVATE, "Activated context", null))); - } - - @Test - public void testUnobservableDeprecatedLegacyAbstractThreadLocalContext() { - observedContextManager = DeprecatedContextManager.class; - final ContextManager manager = new DeprecatedContextManager(); - final Context ctx = manager.initializeNewContext("Activated context"); - Context ctx2 = null; - try { - assertThat(manager.getActiveContext().getValue(), is("Activated context")); - assertThat(observed, not(hasItem(activated(is("Activated context"))))); - ctx2 = manager.initializeNewContext("Nested active context"); - - } finally { - if (ctx2 != null) ctx2.close(); - ctx.close(); - } - assertThat(observed, not(hasItem(deactivated(is("Activated context"))))); - } - - @Test - @SuppressWarnings("unchecked") - public void testOnActivate() { - observedContextManager = DummyContextManager.class; - Class reportedClass = ContextManager.class; - ContextManagers.onActivate(reportedClass, "activated value", "previous value"); - assertThat(observed, is(empty())); - - observedContextManager = ContextManager.class; - reportedClass = DummyContextManager.class; - ContextObservers.onActivate(reportedClass, "activated value", "previous value"); - assertThat(observed, hasItem(activated(equalTo("activated value")))); - } - - @Test - @SuppressWarnings("unchecked") - public void testOnDeactivate() { - observedContextManager = DummyContextManager.class; - Class reportedClass = ContextManager.class; - ContextObservers.onDeactivate(reportedClass, "deactivated value", "restored value"); - assertThat(observed, is(empty())); - - observedContextManager = ContextManager.class; - reportedClass = DummyContextManager.class; - ContextObservers.onDeactivate(reportedClass, "deactivated value", "restored value"); - assertThat(observed, hasItem(deactivated(equalTo("deactivated value")))); - } -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java deleted file mode 100644 index 74a902b3..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/DeprecatedContextManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; - -@SuppressWarnings("deprecation") // The whole idea of this class is to test deprecated behaviour -public class DeprecatedContextManager implements ContextManager { - - public Context initializeNewContext(String value) { - return new DeprecatedContext(value); - } - - public Context getActiveContext() { - return DeprecatedContext.current(); - } - - private static final class DeprecatedContext extends AbstractThreadLocalContext { - private DeprecatedContext(String value) { - super(value); - } - - private static DeprecatedContext current() { - return current(DeprecatedContext.class); - } - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/Observed.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/Observed.java deleted file mode 100644 index dede81ba..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/Observed.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import java.util.Arrays; - -public final class Observed { - - public enum Action { - ACTIVATE, DEACTIVATE - } - - final Action action; - final Object value; - - Observed(Action action, Object value, Object previous) { - this.action = action; - this.value = value; - } - - public static Matcher activated(final Matcher delegate) { - return new BaseMatcher() { - public boolean matches(Object actual) { - return actual instanceof Observed - && Action.ACTIVATE.equals(((Observed) actual).action) - && delegate.matches(((Observed) actual).value); - } - - public void describeTo(Description description) { - delegate.describeTo(description.appendText(" ")); - } - }; - } - - public static Matcher deactivated(final Matcher delegate) { - return new BaseMatcher() { - public boolean matches(Object actual) { - return actual instanceof Observed - && Action.DEACTIVATE.equals(((Observed) actual).action) - && delegate.matches(((Observed) actual).value); - } - - public void describeTo(Description description) { - delegate.describeTo(description.appendText(" ")); - } - }; - } - - @Override - public int hashCode() { - return Arrays.hashCode(new Object[]{action, value}); - } - - @Override - public boolean equals(Object other) { - return this == other || (other instanceof Observed - && equals(this.action, ((Observed) other).action) - && equals(this.value, ((Observed) other).value) - ); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "{action=" + action + ", value=" + value + '}'; - } - - private static boolean equals(Object obj1, Object obj2) { - return obj1 == null ? obj2 == null : obj1.equals(obj2); - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/SimpleContextObserver.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/SimpleContextObserver.java deleted file mode 100644 index ec2a6c1b..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/SimpleContextObserver.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -public class SimpleContextObserver implements ContextObserver { - public static Class observedContextManager = null; - - public static final List observed = new CopyOnWriteArrayList(); - - @SuppressWarnings("unchecked") - public Class> getObservedContextManager() { - return (Class) observedContextManager; - } - - public void onActivate(Object activatedContextValue, Object previousContextValue) { - observed.add(new Observed(Observed.Action.ACTIVATE, activatedContextValue, previousContextValue)); - } - - public void onDeactivate(Object deactivatedContextValue, Object restoredContextValue) { - observed.add(new Observed(Observed.Action.DEACTIVATE, deactivatedContextValue, restoredContextValue)); - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserver.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserver.java deleted file mode 100644 index 919169a7..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserver.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; - -import javax.annotation.Priority; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -@Priority(Integer.MIN_VALUE) -public class ThrowingContextObserver implements ContextObserver { - static Class> observedContextManager = null; - - static final List observed = new CopyOnWriteArrayList(); - - @SuppressWarnings("unchecked") - public Class> getObservedContextManager() { - return (Class) observedContextManager; - } - - public void onActivate(Object activatedContextValue, Object previousContextValue) { - observed.add(new Observed(Observed.Action.ACTIVATE, activatedContextValue, previousContextValue)); - throw new UnsupportedOperationException("Method onActivate is not supported!"); - } - - public void onDeactivate(Object deactivatedContextValue, Object restoredContextValue) { - observed.add(new Observed(Observed.Action.DEACTIVATE, deactivatedContextValue, restoredContextValue)); - throw new UnsupportedOperationException("Method onDeactivate is not supported!"); - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java deleted file mode 100644 index 473b7722..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/observer/ThrowingContextObserverTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.DummyContextManager; -import nl.talsmasoftware.context.api.Context; -import org.junit.jupiter.api.Test; - -import static nl.talsmasoftware.context.observer.Observed.activated; -import static nl.talsmasoftware.context.observer.Observed.deactivated; -import static nl.talsmasoftware.context.observer.ThrowingContextObserver.observed; -import static nl.talsmasoftware.context.observer.ThrowingContextObserver.observedContextManager; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; - -/** - * Test for context observers that throw exceptions. - */ -public class ThrowingContextObserverTest { - private static DummyContextManager MGR = new DummyContextManager(); - - @Test - public void testExceptionDoesNotPreventFunctionality() { - observedContextManager = MGR.getClass(); - observed.clear(); - try { - - Context ctx = MGR.initializeNewContext("Some value"); - try { - - assertThat(MGR.getActiveContext().getValue(), is("Some value")); - assertThat(observed, hasItem(activated(is("Some value")))); - assertThat(observed, not(hasItem(deactivated(is("Some value"))))); - - } finally { - ctx.close(); - } - - assertThat(MGR.getActiveContext(), is(nullValue())); - assertThat(observed, hasItem(deactivated(is("Some value")))); - - } finally { - observedContextManager = null; - } - } - -} diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager deleted file mode 100644 index 8b81eecc..00000000 --- a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.ContextManager +++ /dev/null @@ -1,6 +0,0 @@ -nl.talsmasoftware.context.DummyContextManager -nl.talsmasoftware.context.ThrowingContextManager -nl.talsmasoftware.context.clearable.AutoInitializingContextManager -nl.talsmasoftware.context.clearable.ClearableDummyContextManager -nl.talsmasoftware.context.clearable.DummyManagerOfClearableContext -nl.talsmasoftware.context.observer.DeprecatedContextManager \ No newline at end of file diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..bdc96303 --- /dev/null +++ b/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1,4 @@ +nl.talsmasoftware.context.dummy.DummyContextManager +nl.talsmasoftware.context.dummy.ThrowingContextManager +nl.talsmasoftware.context.clearable.AutoInitializingContextManager +nl.talsmasoftware.context.clearable.ClearableDummyContextManager diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver b/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver deleted file mode 100644 index 80c4e237..00000000 --- a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver +++ /dev/null @@ -1,2 +0,0 @@ -nl.talsmasoftware.context.observer.ThrowingContextObserver -nl.talsmasoftware.context.observer.SimpleContextObserver diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java index 51d2702c..6c031e56 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java +++ b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,7 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.clearable.Clearable; -import nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; import java.util.Locale; @@ -32,7 +31,10 @@ * * @author Sjoerd Talsma */ -final class LocaleContext extends AbstractThreadLocalContext implements Clearable { +final class LocaleContext extends AbstractThreadLocalContext { + private static final ThreadLocal LOCALE = + AbstractThreadLocalContext.threadLocalInstanceOf(LocaleContext.class); + /** * Instantiates a new context with the specified value. * The new context will be made the active context for the current thread. @@ -41,48 +43,24 @@ final class LocaleContext extends AbstractThreadLocalContext implements * (or null to register a new context with 'no value'). */ LocaleContext(Locale newValue) { - super(LocaleContextManager.class, newValue); - } - - /** - * @return The current {@code LocaleContext} or {@code null} if there is no current Locale context. - */ - static LocaleContext current() { - return AbstractThreadLocalContext.current(LocaleContext.class); - } - - /** - * @return Wether this locale context was already closed. - */ - @Override - public boolean isClosed() { - return super.isClosed(); + super(newValue); } - /** - * @return The locale of this context (even after the context itself is closed) - */ @Override public Locale getValue() { return value; } - /** - * Clears all remembered locales from this thread. - */ - public void clear() { - clearAll(); + static Locale currentValue() { + LocaleContext current = LOCALE.get(); + return current != null ? current.value : null; } /** * Unconditionally clears the entire {@link LocaleContext}. - * This can be useful when returning threads to a threadpool. + * This can be useful when returning threads to a thread pool. */ static void clearAll() { - try { - for (LocaleContext current = current(); current != null; current = current()) current.close(); - } finally { - AbstractThreadLocalContext.threadLocalInstanceOf(LocaleContext.class).remove(); - } + LOCALE.remove(); } } diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java index 55caa168..bc860f49 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java +++ b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; import java.util.Locale; @@ -26,25 +26,19 @@ * @author Sjoerd Talsma */ public final class LocaleContextManager implements ContextManager { - - /** - * @return The {@code Locale} for the current thread, or {@code null} if no context was initialized. - * @see #getCurrentLocaleOrDefault() - */ - public static Locale getCurrentLocale() { - final LocaleContext current = LocaleContext.current(); - return current == null ? null : current.getValue(); - } - /** * @return The {@code Locale} for the current thread, or {@code Locale.getDefault()} if no context was initialized. * @see Locale#getDefault() */ public static Locale getCurrentLocaleOrDefault() { - final Locale current = getCurrentLocale(); + final Locale current = LocaleContext.currentValue(); return current != null ? current : Locale.getDefault(); } + public static Context setCurrentLocale(Locale locale) { + return new LocaleContext(locale); + } + /** * Registers the given {@linkplain Locale} value as the current Locale for the active thread * until the returned context is {@link Context#close() closed} again. @@ -53,22 +47,22 @@ public static Locale getCurrentLocaleOrDefault() { * @return The context to be closed again by the caller to remove this locale as current locale. */ public Context initializeNewContext(Locale value) { - return new LocaleContext(value); + return setCurrentLocale(value); } /** * @return The active {@code Locale} context or {@code null} if no such context is active in the current thread. */ - public Context getActiveContext() { - return LocaleContext.current(); + public Locale getActiveContextValue() { + return LocaleContext.currentValue(); } /** * Unconditionally removes the active context (and any parents). *

    - * This is useful for boundary filters, whose Threads may be returned to some threadpool. + * This is useful for boundary filters, whose Threads may be returned to some thread pool. */ - public static void clear() { + public void clear() { LocaleContext.clearAll(); } diff --git a/locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java index 6d116bed..48f3a13f 100644 --- a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java +++ b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java @@ -15,15 +15,14 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Locale; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -36,7 +35,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; /** @@ -48,7 +46,8 @@ public class LocaleContextManagerTest { private static final Locale GERMAN = Locale.GERMANY; private static final Locale DEFAULT_LOCALE = Locale.getDefault(); - private static LocaleContextManager manager = new LocaleContextManager(); + private static final LocaleContextManager MANAGER = new LocaleContextManager(); + private ExecutorService threadpool; @BeforeEach @@ -65,88 +64,80 @@ public void cleanup() { @Test public void testLocalePropagation() throws ExecutionException, InterruptedException { - Context ctx1 = manager.initializeNewContext(DUTCH); - try { - assertThat("Current context", manager.getActiveContext(), is(notNullValue())); - assertThat("Current context value", manager.getActiveContext().getValue(), is(DUTCH)); + try (Context ctx1 = LocaleContextManager.setCurrentLocale(DUTCH)) { + assertThat(ctx1.getValue(), is(DUTCH)); + assertThat(MANAGER.getActiveContextValue(), is(DUTCH)); + assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DUTCH)); - Context ctx2 = manager.initializeNewContext(GERMAN); final CountDownLatch blocker = new CountDownLatch(1); Future slowCall; - try { + try (Context ctx2 = MANAGER.initializeNewContext(GERMAN)) { + assertThat(ctx2.getValue(), is(GERMAN)); + assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); + assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); - slowCall = threadpool.submit(new Callable() { - public Locale call() throws InterruptedException { - blocker.await(5, TimeUnit.SECONDS); - return LocaleContextManager.getCurrentLocale(); - } + slowCall = threadpool.submit(() -> { + blocker.await(5, TimeUnit.SECONDS); + return MANAGER.getActiveContextValue(); }); - - } finally { - ctx2.close(); } - assertThat("Restored context in parent", LocaleContextManager.getCurrentLocale(), is(DUTCH)); + + assertThat("Restored context in parent", MANAGER.getActiveContextValue(), is(DUTCH)); assertThat("Slow thread already done", slowCall.isDone(), is(false)); blocker.countDown(); assertThat("Context in slow thread", slowCall.get(), is(GERMAN)); - - } finally { - ctx1.close(); } - assertThat("Current context", manager.getActiveContext(), is(nullValue())); + assertThat("Current context", MANAGER.getActiveContextValue(), is(nullValue())); + assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); } @Test public void testGetCurrentLocaleOrDefault() { assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); - Context ctx1 = manager.initializeNewContext(GERMAN); - try { + try (Context ctx1 = LocaleContextManager.setCurrentLocale(GERMAN)) { assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); - Context ctx2 = manager.initializeNewContext(null); - try { + assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); + + try (Context ctx2 = MANAGER.initializeNewContext(null)) { assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(MANAGER.getActiveContextValue(), nullValue()); } finally { - ctx2.close(); assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); + assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); } } finally { - ctx1.close(); assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); } } @Test public void testClear() { - Context dutchCtx = manager.initializeNewContext(DUTCH); - Context englishCtx = manager.initializeNewContext(ENGLISH); + Context dutchCtx = MANAGER.initializeNewContext(DUTCH); + Context englishCtx = MANAGER.initializeNewContext(ENGLISH); - LocaleContextManager.clear(); - assertThat(manager.getActiveContext(), is(nullValue())); - assertThat(LocaleContextManager.getCurrentLocale(), is(nullValue())); + MANAGER.clear(); + assertThat(MANAGER.getActiveContextValue(), is(nullValue())); + assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); - assertThat(((LocaleContext) englishCtx).isClosed(), is(true)); - assertThat(((LocaleContext) dutchCtx).isClosed(), is(true)); assertThat(englishCtx.getValue(), equalTo(ENGLISH)); assertThat(dutchCtx.getValue(), equalTo(DUTCH)); } @Test public void testClearActiveContexts() { - Context dutchCtx = manager.initializeNewContext(DUTCH); - Context englishCtx = manager.initializeNewContext(ENGLISH); + Context dutchCtx = MANAGER.initializeNewContext(DUTCH); + Context englishCtx = MANAGER.initializeNewContext(ENGLISH); ContextManagers.clearActiveContexts(); - assertThat(manager.getActiveContext(), is(nullValue())); - assertThat(LocaleContextManager.getCurrentLocale(), is(nullValue())); + assertThat(MANAGER.getActiveContextValue(), is(nullValue())); + assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); - assertThat(((LocaleContext) englishCtx).isClosed(), is(true)); - assertThat(((LocaleContext) dutchCtx).isClosed(), is(true)); assertThat(englishCtx.getValue(), equalTo(ENGLISH)); assertThat(dutchCtx.getValue(), equalTo(DUTCH)); } @Test public void testToString() { - assertThat(manager, hasToString(containsString("LocaleContextManager"))); + assertThat(MANAGER, hasToString(containsString("LocaleContextManager"))); } } diff --git a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java b/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java index bdf0a568..3a587fc6 100644 --- a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java +++ b/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java @@ -15,9 +15,8 @@ */ package nl.talsmasoftware.context.log4j2.threadcontext; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.clearable.ClearableContextManager; +import nl.talsmasoftware.context.api.ContextManager; import org.apache.logging.log4j.CloseableThreadContext; import org.apache.logging.log4j.ThreadContext; @@ -26,11 +25,7 @@ /** * Manager to propagate the Log4j 2 {@link ThreadContext} data from one thread to another. *

    - * As {@code ThreadContext} already manages its own thread-local state, - * getting the active context is delegated to the {@code ThreadContext}. - * This means that closing the resulting context from {@link #getActiveContext()} will have - * no effect, because its data is not managed by this library. However, calling - * {@link #clear()} will clear the {@code ThreadContext} data of the current thread.
    + * Calling {@link #clear()} will clear the {@code ThreadContext} data of the current thread.
    * Methods of this manager may have no effect when the {@code ThreadContext} has been disabled * (see Log4j 2 manual). *

    @@ -60,7 +55,7 @@ * * @see Log4j 2 Thread Context manual */ -public class Log4j2ThreadContextManager implements ClearableContextManager { +public class Log4j2ThreadContextManager implements ContextManager { /** * Singleton instance of this class. */ @@ -81,7 +76,7 @@ public static Log4j2ThreadContextManager provider() { * Creates a new context manager. * * @see #provider() - * @deprecated This constructor only exists for usage by {@code ServiceLoader}. The singleton instance + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. */ @Deprecated @@ -96,8 +91,8 @@ public Log4j2ThreadContextManager() { * * @return Context containing the active Log4j 2 {@code ThreadContext} data */ - public Context getActiveContext() { - return new ReadonlyLog4j2ThreadContext(Log4j2ThreadContextSnapshot.captureFromCurrentThread()); + public Log4j2ThreadContextSnapshot getActiveContextValue() { + return Log4j2ThreadContextSnapshot.captureFromCurrentThread(); } /** @@ -132,27 +127,6 @@ public String toString() { return getClass().getSimpleName(); } - private static final class ReadonlyLog4j2ThreadContext implements Context { - private final Log4j2ThreadContextSnapshot snapshot; - - private ReadonlyLog4j2ThreadContext(Log4j2ThreadContextSnapshot snapshot) { - this.snapshot = snapshot; - } - - public Log4j2ThreadContextSnapshot getValue() { - return snapshot; - } - - public void close() { - // No-op. We don't manage the Log4j 2 ThreadContext, so we shouldn't close it either. - } - - @Override - public String toString() { - return getClass().getSimpleName() + '{' + snapshot + '}'; - } - } - private static final class ManagedLog4j2ThreadContext implements Context { private final Log4j2ThreadContextSnapshot previous, value; private final AtomicBoolean closed; @@ -161,7 +135,6 @@ private ManagedLog4j2ThreadContext(Log4j2ThreadContextSnapshot previous, Log4j2T this.previous = previous; this.value = value; this.closed = new AtomicBoolean(false); - ContextManagers.onActivate(Log4j2ThreadContextManager.class, value, previous); } public Log4j2ThreadContextSnapshot getValue() { @@ -173,7 +146,6 @@ public void close() { // Restore previous; overwrite current ThreadContext ThreadContext.clearAll(); previous.applyToCurrentThread(); - ContextManagers.onDeactivate(Log4j2ThreadContextManager.class, value, previous); } } diff --git a/log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java index 5365bbe6..71fd36eb 100644 --- a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java +++ b/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java @@ -18,19 +18,16 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -55,6 +52,7 @@ class Log4j2ThreadContextManagerTest { * Underlying executor of {@link #threadpool}; not context-aware */ private ExecutorService rawThreadpool; + /** * Context-aware executor */ @@ -79,19 +77,11 @@ void clearThreadContext() { } private static Callable createGetMapValue(final String key) { - return new Callable() { - public String call() { - return ThreadContext.get(key); - } - }; + return () -> ThreadContext.get(key); } private static Callable createGetStackValue(final int index) { - return new Callable() { - public String call() { - return ThreadContext.getImmutableStack().asList().get(index); - } - }; + return () -> ThreadContext.getImmutableStack().asList().get(index); } @Test @@ -109,37 +99,11 @@ void testDefaultConstructor() { @Test void testInitializeNewContext_null() { - NullPointerException expected = assertThrows(NullPointerException.class, new Executable() { - public void execute() { - Log4j2ThreadContextManager.provider().initializeNewContext(null); - } - }); + Log4j2ThreadContextManager manager = Log4j2ThreadContextManager.provider(); + NullPointerException expected = assertThrows(NullPointerException.class, () -> manager.initializeNewContext(null)); assertThat(expected.getMessage(), notNullValue()); } - /** - * Verify that calling {@code close()} on the result of {@link Log4j2ThreadContextManager#getActiveContext()} - * has no effect because it is managed by Log4j2. - */ - @Test - void testGetActiveContext_close() { - ThreadContext.put("map1", "value1"); - ThreadContext.put("map2", "value2"); - ThreadContext.push("stack1"); - ThreadContext.push("stack2"); - - // Should have no effect - Log4j2ThreadContextManager.provider().getActiveContext().close(); - - Map expectedMap = new HashMap(); - expectedMap.put("map1", "value1"); - expectedMap.put("map2", "value2"); - assertThat(ThreadContext.getContext(), equalTo(expectedMap)); - - List expectedStack = Arrays.asList("stack1", "stack2"); - assertThat(ThreadContext.getImmutableStack().asList(), equalTo(expectedStack)); - } - @Test void testPropagationOfThreadContextValues() throws ExecutionException, InterruptedException { String mapKey = "map1"; @@ -259,7 +223,6 @@ void testContextToString() { final Log4j2ThreadContextManager mgr = Log4j2ThreadContextManager.provider(); - assertThat(mgr.getActiveContext(), hasToString("ReadonlyLog4j2ThreadContext{" + data + "}")); Context ctx = mgr.initializeNewContext(data); try { assertThat(ctx, hasToString("ManagedLog4j2ThreadContext{" + data + "}")); diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java index 162e5394..c0344cb4 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java @@ -79,18 +79,9 @@ public Context initializeNewContext(Span value) { return new ThreadLocalSpanContext(value); } - /** - * @return The active span context (this is identical to the active scope). - */ - @Override - public Context getActiveContext() { - return ThreadLocalSpanContext.current(); - } - @Override public Span getActiveContextValue() { - Context activeContext = getActiveContext(); - return activeContext == null ? null : activeContext.getValue(); + return activeSpan(); } @Override diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java index 81af56ea..59ee3d9e 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java @@ -25,6 +25,7 @@ /** * Manager for OpenTracing {@linkplain Span}. + * *

    * Management of {@linkplain Span spans} is delegated to the {@linkplain GlobalTracer}. * @@ -33,27 +34,18 @@ public class SpanManager implements ContextManager { /** - * Return the {@link GlobalTracer#activeSpan() active span} as a {@link Context}. - *

    - * Please note: Closing this context will not close the corresponding OpenTracing scope - * as it is not ours to manage. + * Return the {@link GlobalTracer#activeSpan() active span}. * * @return The currently active span as a context. */ - @Override - public Context getActiveContext() { - Span activeSpan = GlobalTracer.get().activeSpan(); - return activeSpan == null ? null : new SpanContext(activeSpan, null); - } - @Override public Span getActiveContextValue() { - return GlobalTracer.get().activeSpan(); + return activeSpan(); } @Override public void clear() { - + // Opentracing API does not support clearing the span. } /** @@ -76,45 +68,44 @@ public void clear() { */ @Override public Context initializeNewContext(final Span span) { - Scope scope = span == null ? null : GlobalTracer.get().scopeManager().activate(span); - return new SpanContext(span, scope); + return new SpanContext(span); } /** - * @return Just the simple class name as this class carries no internal state. + * @return Simple class name as this class carries no internal state. */ @Override public String toString() { return getClass().getSimpleName(); } + private static Span activeSpan() { + return GlobalTracer.get().activeSpan(); + } + private static class SpanContext implements Context { private final AtomicBoolean closed = new AtomicBoolean(false); - private final Span span; private final Scope scope; - private SpanContext(Span span, Scope scope) { - this.span = span; - this.scope = scope; + private SpanContext(Span span) { + this.scope = span != null ? GlobalTracer.get().activateSpan(span) : null; } @Override public Span getValue() { - return closed.get() ? null : span; + return closed.get() ? null : activeSpan(); } @Override public void close() { - if (closed.compareAndSet(false, true)) { - if (scope != null) { - scope.close(); - } + if (closed.compareAndSet(false, true) && scope != null) { + scope.close(); } } @Override public String toString() { - return getClass().getSimpleName() + (closed.get() ? "{closed}" : "{" + span + '}'); + return getClass().getSimpleName() + (closed.get() ? "{closed}" : "{" + getValue() + '}'); } } diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java index 3e7b7512..99b52886 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,7 @@ import io.opentracing.Span; import io.opentracing.mock.MockSpan; -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.observer.ContextObserver; +import nl.talsmasoftware.context.api.ContextObserver; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -29,12 +28,7 @@ import static java.util.Collections.synchronizedList; public class ContextScopeManagerObserver implements ContextObserver { - static final List observed = synchronizedList(new ArrayList()); - - @Override - public Class> getObservedContextManager() { - return ContextScopeManager.class; - } + static final List observed = synchronizedList(new ArrayList<>()); @Override public void onActivate(Span activatedContextValue, Span previousContextValue) { diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java index ca948e15..6b6ff9cc 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java @@ -163,7 +163,7 @@ public void run() { public void testInitializeNewContext() { Span span = GlobalTracer.get().buildSpan("span").start(); Context context = scopeManager.initializeNewContext(span); - assertThat(scopeManager.getActiveContext().getValue(), is(span)); + assertThat(scopeManager.getActiveContextValue(), is(span)); assertThat(scopeManager.activeSpan(), is(span)); assertThat(GlobalTracer.get().activeSpan(), is(span)); context.close(); diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java index 9a1abbf8..2ba87197 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java @@ -216,7 +216,7 @@ public void testDeprecatedClassStillWorks() { Span parentSpan = mockTracer.buildSpan("first-op").start(); Scope parent = mockTracer.activateSpan(parentSpan); Span newSpan = mockTracer.buildSpan("second-span").start(); - assertThat(deprecatedManager.getActiveContext().getValue(), is(equalTo(parentSpan))); + assertThat(deprecatedManager.getActiveContextValue(), is(equalTo(parentSpan))); Context newContext = deprecatedManager.initializeNewContext(newSpan); assertThat(SCOPE_MANAGER.activeSpan(), is(equalTo(newSpan))); @@ -231,7 +231,7 @@ public void testDeprecatedClassStillWorks() { public void testClearingAllContexts() { Span span = mockTracer.buildSpan("test-span").start(); Scope scope = mockTracer.scopeManager().activate(span); - assertThat(new SpanManager().getActiveContext().getValue(), is(sameInstance(span))); + assertThat(new SpanManager().getActiveContextValue(), is(sameInstance(span))); ContextManagers.clearActiveContexts(); // TODO Test after this is merged: https://github.com/opentracing/opentracing-java/pull/313 @@ -246,17 +246,12 @@ public void testSpanManagerToString() { @Test public void testSpanContextToString() { Span span = mockTracer.buildSpan("test-span").start(); - assertThat(new SpanManager().getActiveContext(), nullValue()); + assertThat(new SpanManager().getActiveContextValue(), nullValue()); Scope scope = mockTracer.scopeManager().activate(span); - Context spanContext = new SpanManager().getActiveContext(); - assertThat(spanContext, hasToString("SpanContext{" + span + "}")); + assertThat(new SpanManager().getActiveContextValue(), is(span)); scope.close(); - assertThat(new SpanManager().getActiveContext(), nullValue()); - assertThat(spanContext, hasToString("SpanContext{" + span + "}")); - - spanContext.close(); - assertThat(spanContext, hasToString("SpanContext{closed}")); + assertThat(new SpanManager().getActiveContextValue(), nullValue()); } } diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java index daec436f..0a5e1cb9 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java @@ -15,46 +15,35 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; import javax.servlet.ServletRequest; /** - * Simple (unstacked) context using a Threadlocal containing the current {@link ServletRequest}. + * Simple (unstacked) context using a ThreadLocal containing the current {@link ServletRequest}. * * @author Sjoerd Talsma */ -final class ServletRequestContext implements Context { - - private static final ThreadLocal CONTEXT = new ThreadLocal(); - - volatile ServletRequest servletRequest; +final class ServletRequestContext extends AbstractThreadLocalContext { + private static final ThreadLocal CONTEXT = + AbstractThreadLocalContext.threadLocalInstanceOf(ServletRequestContext.class); ServletRequestContext(ServletRequest servletRequest) { - this.servletRequest = servletRequest; - CONTEXT.set(this); - ContextManagers.onActivate(ServletRequestContextManager.class, servletRequest, null); - } - - static Context current() { - return CONTEXT.get(); + super(servletRequest); } - public ServletRequest getValue() { - return servletRequest; + static ServletRequest currentValue() { + ServletRequestContext current = CONTEXT.get(); + return current != null ? current.getValue() : null; } - public void close() { - final ServletRequest deactivated = servletRequest; - servletRequest = null; - CONTEXT.set(null); - ContextManagers.onDeactivate(ServletRequestContextManager.class, deactivated, null); + static void clear() { + try { + for (ServletRequestContext current = CONTEXT.get(); current != null; current = CONTEXT.get()) { + current.close(); + } + } finally { + CONTEXT.remove(); + } } - - @Override - public String toString() { - return getClass().getSimpleName() + (servletRequest == null ? "{closed}" : "{value=" + servletRequest + "}"); - } - } diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java index 734ac15a..614f2284 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,14 +32,14 @@ public void onStartAsync(AsyncEvent event) { } public void onComplete(AsyncEvent event) { - ServletRequestContextManager.clear(); + ServletRequestContext.clear(); } public void onTimeout(AsyncEvent event) { - ServletRequestContextManager.clear(); + ServletRequestContext.clear(); } public void onError(AsyncEvent event) { - ServletRequestContextManager.clear(); + ServletRequestContext.clear(); } } diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java index 8bf1bad1..84eee257 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ */ package nl.talsmasoftware.context.servletrequest; +import nl.talsmasoftware.context.api.Context; + import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -28,7 +30,7 @@ /** * Servlet {@link Filter} that registers the current {@link ServletRequest} with the * {@link ServletRequestContextManager} to become the - * {@link ServletRequestContextManager#getActiveContext() active context} + * {@link ServletRequestContextManager#getActiveContextValue() active context value} * while the filter is active. * * @author Sjoerd Talsma @@ -42,19 +44,19 @@ public void init(FilterConfig filterConfig) { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - try { + // Automatically becomes the new active context. + try (Context context = new ServletRequestContext(request)) { - new ServletRequestContext(request); // Automatically becomes the new active context. if (request.isAsyncStarted()) try { request.getAsyncContext().addListener(new ServletRequestContextAsyncListener()); } catch (IllegalStateException e) { - LOGGER.log(Level.FINE, "Could not register servletrequest asynchronous listener: " + e.getMessage(), e); + LOGGER.log(Level.FINE, "Could not register ServletRequest asynchronous listener: " + e.getMessage(), e); } chain.doFilter(request, response); } finally { - ServletRequestContextManager.clear(); // Make sure there are no requests returned to the HTTP threadpool. + ServletRequestContext.clear(); // Make sure there are no requests returned to the HTTP thread pool. } } diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java index 9da1c691..c24f4ade 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java @@ -15,8 +15,8 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.ContextManager; import nl.talsmasoftware.context.api.Context; +import nl.talsmasoftware.context.api.ContextManager; import javax.servlet.ServletRequest; @@ -33,28 +33,24 @@ public final class ServletRequestContextManager implements ContextManagernull otherwise. */ public static ServletRequest currentServletRequest() { - Context current = ServletRequestContext.current(); - return current == null ? null : current.getValue(); + return ServletRequestContext.currentValue(); } public Context initializeNewContext(ServletRequest value) { return new ServletRequestContext(value); } - public Context getActiveContext() { - return ServletRequestContext.current(); + public ServletRequest getActiveContextValue() { + return currentServletRequest(); } /** * Unconditionally removes the active context (and any parents). *

    - * This is useful for boundary filters, whose Threads may be returned to some threadpool. + * This is useful for boundary filters, whose Threads may be returned to some thread pool. */ - public static void clear() { - Context current = ServletRequestContext.current(); - if (current != null) { - current.close(); - } + public void clear() { + ServletRequestContext.clear(); } @Override diff --git a/servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java index 9b5de716..0a56fa44 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java +++ b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class ServletRequestContextAsyncListenerTest { @BeforeEach public void setUp() { - ServletRequestContextManager.clear(); + ServletRequestContext.clear(); mockContext = mock(AsyncContext.class); mockRequest = mock(ServletRequest.class); mockResponse = mock(ServletResponse.class); @@ -55,7 +55,7 @@ public void setUp() { @AfterEach public void tearDown() { - ServletRequestContextManager.clear(); + ServletRequestContext.clear(); verifyNoMoreInteractions(mockContext, mockRequest, mockResponse); } diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java index b68b3818..3aee9e1d 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java +++ b/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java @@ -15,9 +15,9 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,14 +45,14 @@ public class ServletRequestContextManagerTest { @BeforeEach public void init() { - ServletRequestContextManager.clear(); + new ServletRequestContextManager().clear(); threadpool = new ContextAwareExecutorService(Executors.newCachedThreadPool()); } @AfterEach public void cleanup() { threadpool.shutdown(); - ServletRequestContextManager.clear(); + new ServletRequestContextManager().clear(); } @Test @@ -62,14 +62,14 @@ public void testContextManagerToStringValue() { @Test public void testGetActiveContext() { - assertThat(new ServletRequestContextManager().getActiveContext(), is(nullValue())); + assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); final ServletRequest request = mock(ServletRequest.class); Context ctx = new ServletRequestContextManager().initializeNewContext(request); - assertThat(new ServletRequestContextManager().getActiveContext().getValue(), is(sameInstance(request))); + assertThat(new ServletRequestContextManager().getActiveContextValue(), is(sameInstance(request))); ctx.close(); - assertThat(new ServletRequestContextManager().getActiveContext(), is(nullValue())); + assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); } @Test @@ -89,11 +89,11 @@ public void testClearableImplementation() { final ServletRequest request = mock(ServletRequest.class); Context ctx = new ServletRequestContextManager().initializeNewContext(request); assertThat(ctx.getValue(), is(sameInstance(request))); - assertThat(new ServletRequestContextManager().getActiveContext().getValue(), is(sameInstance(request))); + assertThat(new ServletRequestContextManager().getActiveContextValue(), is(sameInstance(request))); ContextManagers.clearActiveContexts(); assertThat(ctx.getValue(), is(nullValue())); // must have been closed - assertThat(new ServletRequestContextManager().getActiveContext(), is(nullValue())); + assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); } @Test @@ -102,16 +102,13 @@ public void testPropagationInOtherThreads() throws ExecutionException, Interrupt ServletRequest request1 = mock(ServletRequest.class); ServletRequest request2 = mock(ServletRequest.class); - Context ctx1 = manager.initializeNewContext(request1); - try { - assertThat("Current context", manager.getActiveContext(), is(notNullValue())); - assertThat("Current context value", manager.getActiveContext().getValue(), is(request1)); + try (Context ctx1 = manager.initializeNewContext(request1)) { + assertThat("Current context", manager.getActiveContextValue(), is(notNullValue())); + assertThat("Current context value", manager.getActiveContextValue(), is(request1)); - Context ctx2 = manager.initializeNewContext(request2); final CountDownLatch blocker = new CountDownLatch(1); Future slowCall; - try { - + try (Context ctx2 = manager.initializeNewContext(request2)) { slowCall = threadpool.submit(new Callable() { public ServletRequest call() throws InterruptedException { blocker.await(5, TimeUnit.SECONDS); @@ -119,24 +116,20 @@ public ServletRequest call() throws InterruptedException { } }); - } finally { - ctx2.close(); } - assertThat("Closed context in parent", ServletRequestContextManager.currentServletRequest(), is(nullValue())); + assertThat("Restored context in parent", ServletRequestContextManager.currentServletRequest(), is(request1)); assertThat("Slow thread already done", slowCall.isDone(), is(false)); blocker.countDown(); assertThat("Context in slow thread", slowCall.get(), is(request2)); - - } finally { - ctx1.close(); } - assertThat("Current closed context", manager.getActiveContext(), is(nullValue())); + + assertThat("Current closed context", manager.getActiveContextValue(), is(nullValue())); } @Test public void testServletRequestContextToString() { ServletRequestContextManager manager = new ServletRequestContextManager(); - assertThat(manager.getActiveContext(), nullValue()); + assertThat(manager.getActiveContextValue(), nullValue()); ServletRequest request = mock(ServletRequest.class); Context servletRequestContext = manager.initializeNewContext(request); diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/MdcManager.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/MdcManager.java deleted file mode 100644 index 0fc51d7c..00000000 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/MdcManager.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.mdc; - -import nl.talsmasoftware.context.slf4j.mdc.Slf4jMdcManager; - -/** - * @deprecated This class moved to package {@code nl.talsmasoftware.context.slf4j.mdc}. - */ -@Deprecated -public class MdcManager extends Slf4jMdcManager { -} diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/package-info.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/package-info.java deleted file mode 100644 index d521b229..00000000 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/mdc/package-info.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * (Deprecated) this package was renamed to {@code nl.talsmasoftware.context.slf4j.mdc}. - */ -package nl.talsmasoftware.context.mdc; diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java index ab883b83..0afa1565 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java +++ b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java @@ -15,10 +15,9 @@ */ package nl.talsmasoftware.context.slf4j.mdc; -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.clearable.Clearable; +import nl.talsmasoftware.context.api.ContextManager; +import nl.talsmasoftware.context.core.ContextManagers; import org.slf4j.MDC; import java.util.Map; @@ -26,18 +25,23 @@ /** * Manager to propagate the SLF4J {@link MDC} content from one thread to another. + * *

    * As {@link MDC} already manages its own thread-local state, - * getting the active context is 100% delegated to the MDC.
    - * This means that closing the resulting context from {@link #getActiveContext()} will have no side-effects, - * as it is not ours to manage. + * getting the active context is 100% delegated to the MDC. + * *

    - * Closing a context returned form {@link #initializeNewContext(Map)} will reset the MDC + * Closing a context returned form {@link #initializeNewContext(Map)} restores the MDC * to the values it had before the context was created.
    * This means that closing nested contexts out-of-order will probably result in an undesirable state.
    * It is therefore strongly advised to use Java's {@code try-with-resources} mechanism to ensure proper * closing when nesting new MDC contexts. * + *

    + * This manager does not implement the optional {@link #clear()} method. + * {@link ContextManagers#clearActiveContexts()} will therefore not clear the {@linkplain MDC}. + * Please use {@linkplain MDC#clear()} explicitly to do that. + * * @author Sjoerd Talsma */ public class Slf4jMdcManager implements ContextManager> { @@ -55,11 +59,7 @@ public class Slf4jMdcManager implements ContextManager> { * @return A context that -when closed- will restore the active MDC values to what they were just before this call. */ public Context> initializeNewContext(final Map mdcValues) { - // Capture current MDC as 'previous' and make the given values the 'new current' MDC. - final Map previous = MDC.getCopyOfContextMap(); - if (mdcValues == null) MDC.clear(); - else MDC.setContextMap(mdcValues); - return new Slf4jMdcContext(previous, mdcValues, false); + return new Slf4jMdcContext(mdcValues); } /** @@ -70,9 +70,33 @@ public Context> initializeNewContext(final Map> getActiveContext() { - // Return fresh context that is 'already-closed'. Therefore it doesn't need a previous mdc. - return new Slf4jMdcContext(null, MDC.getCopyOfContextMap(), true); + public Map getActiveContextValue() { + return MDC.getCopyOfContextMap(); + } + + /** + * This manager does not support clearing the MDC. + * + *

    + * Calling {@code ContextManagers.clearActiveContexts()} will therefore not clear the + * MDC by default. This can be achieved by calling {@link MDC#clear()} explicitly. + * + * @see MDC#clear() + */ + public void clear() { + // no-op + } + + private static Map currentMdc() { + return MDC.getCopyOfContextMap(); + } + + private static void setMdc(Map mdc) { + if (mdc == null) { + MDC.clear(); + } else { + MDC.setContextMap(mdc); + } } @Override @@ -80,37 +104,31 @@ public String toString() { return getClass().getSimpleName(); } - private static final class Slf4jMdcContext implements Context>, Clearable { - private final Map previous, value; + private static final class Slf4jMdcContext implements Context> { + private final Map previous; private final AtomicBoolean closed; - private Slf4jMdcContext(Map previous, Map value, boolean closed) { - this.previous = previous; - this.value = value; - this.closed = new AtomicBoolean(closed); - ContextManagers.onActivate(Slf4jMdcManager.class, value, previous); + private Slf4jMdcContext(Map value) { + // Capture current MDC as 'previous' and make the given values the 'new current' MDC. + this.previous = currentMdc(); + setMdc(value); + this.closed = new AtomicBoolean(false); } public Map getValue() { - return value; + return currentMdc(); } public void close() { if (closed.compareAndSet(false, true)) { - if (previous == null) MDC.clear(); - else MDC.setContextMap(previous); - ContextManagers.onDeactivate(Slf4jMdcManager.class, value, previous); + setMdc(previous); } } - public void clear() { - close(); - } - @Override public String toString() { - return closed.get() ? "Slf4jMdcContext{closed}" : "Slf4jMdcContext" + (value == null ? "{}" : value); + Map mdc = getValue(); + return closed.get() ? "Slf4jMdcContext{closed}" : "Slf4jMdcContext" + (mdc == null ? "{}" : mdc); } - } } diff --git a/slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java index 58ba0e4a..ae6811ca 100644 --- a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java +++ b/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java @@ -18,7 +18,7 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -33,6 +33,7 @@ import java.util.concurrent.Future; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; @@ -101,12 +102,10 @@ public void testSlf4jMdcContextToString() { Slf4jMdcManager mgr = new Slf4jMdcManager(); MDC.put("dummy", "value"); Map mdc = MDC.getCopyOfContextMap(); - assertThat(mgr.getActiveContext(), hasToString("Slf4jMdcContext{closed}")); - Context> ctx = mgr.initializeNewContext(mdc); - try { + assertThat(mgr.getActiveContextValue(), equalTo(mdc)); + + try (Context> ctx = mgr.initializeNewContext(mdc)) { assertThat(ctx, hasToString("Slf4jMdcContext" + mdc)); - } finally { - ctx.close(); } } diff --git a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java b/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java index 1224b2df..f77ffa11 100644 --- a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java +++ b/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java @@ -15,9 +15,8 @@ */ package nl.talsmasoftware.context.springsecurity; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.clearable.ClearableContextManager; +import nl.talsmasoftware.context.api.ContextManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; @@ -33,72 +32,71 @@ * * @author Sjoerd Talsma */ -public class SpringSecurityContextManager implements ClearableContextManager { +public class SpringSecurityContextManager implements ContextManager { /** * Creates a new Spring {@linkplain SecurityContext} and sets the {@linkplain Authentication value} in it. + * *

    * This new value is set in the {@linkplain SecurityContextHolder} and the current {@linkplain Authentication} * is remembered, to be restored when the returned {@link Context} is closed. * - * @param value The value to initialize a new context for. + * @param authentication The value to initialize a new context for. * @return A context with the new Authentication, restoring the previous authentication when closed. */ - public Context initializeNewContext(Authentication value) { - SecurityContext previous = SecurityContextHolder.getContext(); - SecurityContext current = SecurityContextHolder.createEmptyContext(); - current.setAuthentication(value); - SecurityContextHolder.setContext(current); - return new AuthenticationContext(current, previous, false); + public Context initializeNewContext(Authentication authentication) { + return new AuthenticationContext(authentication); } /** * @return A context object referring to the current {@code Authentication} in the spring security context holder. * Closing the returned context does nothing. */ - public Context getActiveContext() { - return new AuthenticationContext(SecurityContextHolder.getContext(), null, true); + public Authentication getActiveContextValue() { + return currentAuthentication(); + } + + private static Authentication currentAuthentication() { + SecurityContext context = SecurityContextHolder.getContext(); + return context != null ? context.getAuthentication() : null; } /** - * Clears the Spring {@linkplain SecurityContext} by calling {@linkplain SecurityContextHolder#clearContext()}. + * Clears the Spring {@linkplain SecurityContext}. + * + * @see SecurityContextHolder#clearContext() */ public void clear() { SecurityContextHolder.clearContext(); } private static final class AuthenticationContext implements Context { - private volatile SecurityContext current; private final SecurityContext previous; private final AtomicBoolean closed; - private AuthenticationContext(SecurityContext current, SecurityContext previous, boolean alreadyClosed) { - this.current = current; - this.previous = previous; - this.closed = new AtomicBoolean(alreadyClosed); - ContextManagers.onActivate(SpringSecurityContextManager.class, auth(current), auth(previous)); + private AuthenticationContext(Authentication authentication) { + this.previous = SecurityContextHolder.getContext(); + this.closed = new AtomicBoolean(false); + setCurrentAuthentication(authentication); + } + + private void setCurrentAuthentication(Authentication authentication) { + SecurityContext current = SecurityContextHolder.createEmptyContext(); + if (authentication != null) { + current.setAuthentication(authentication); + } + SecurityContextHolder.setContext(current); } public Authentication getValue() { - return auth(current); + return currentAuthentication(); } public void close() { if (closed.compareAndSet(false, true)) { SecurityContextHolder.setContext(previous); - ContextManagers.onDeactivate(SpringSecurityContextManager.class, auth(current), auth(previous)); } } - - /** - * Null-safe {@code getAuthentication()} call - * - * @param securityContext optional security context to get authentication object from. - * @return the authentication object or null if security context itself was null. - */ - private static Authentication auth(SecurityContext securityContext) { - return securityContext == null ? null : securityContext.getAuthentication(); - } } } diff --git a/spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager b/spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.ContextManager rename to spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java index 00648f26..0a70d762 100644 --- a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java +++ b/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java @@ -17,7 +17,7 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; +import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -79,7 +79,7 @@ private static void setAuthentication(String name) { @Test public void testWithoutAnyAuthentication() { - assertThat(new SpringSecurityContextManager().getActiveContext().getValue(), is(nullValue())); + assertThat(new SpringSecurityContextManager().getActiveContextValue(), is(nullValue())); } @Test @@ -112,22 +112,13 @@ public void testAuthenticationReactivation() throws Exception { hasToString(containsString("Jules Winnfield"))); } - @Test - public void testClosingCurrentAuthenticationContext() { - setAuthentication("Vincent Vega"); - assertThat(new SpringSecurityContextManager().getActiveContext().getValue().getName(), is("Vincent Vega")); - - new SpringSecurityContextManager().getActiveContext().close(); // Not ours to manage! - assertThat(new SpringSecurityContextManager().getActiveContext().getValue().getName(), is("Vincent Vega")); - } - @Test public void testClearableImplementation() { setAuthentication("Vincent Vega"); - assertThat(new SpringSecurityContextManager().getActiveContext().getValue().getName(), is("Vincent Vega")); + assertThat(new SpringSecurityContextManager().getActiveContextValue().getName(), is("Vincent Vega")); ContextManagers.clearActiveContexts(); - assertThat(new SpringSecurityContextManager().getActiveContext().getValue(), is(nullValue())); + assertThat(new SpringSecurityContextManager().getActiveContextValue(), is(nullValue())); } } From 2e541b87a3cc1262b72de2397aaa51fc6a1f2956 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 10:43:05 +0100 Subject: [PATCH 15/41] Remove deprecated clearable package. Signed-off-by: Sjoerd Talsma --- .../context/ContextManagers.java | 4 -- .../context/clearable/Clearable.java | 40 ------------------- .../clearable/ClearableContextManager.java | 29 -------------- .../context/clearable/package-info.java | 33 --------------- 4 files changed, 106 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/clearable/Clearable.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/clearable/ClearableContextManager.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/clearable/package-info.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java index 2c39e2d5..571656e6 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java @@ -16,7 +16,6 @@ package nl.talsmasoftware.context; import nl.talsmasoftware.context.api.ContextObserver; -import nl.talsmasoftware.context.clearable.Clearable; import java.util.logging.Level; import java.util.logging.Logger; @@ -86,9 +85,6 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho * An even better strategy would be to clear the context right before returning a used thread to the pool * as this will allow any unclosed contexts to be garbage collected. Besides preventing contextual issues, * this reduces the risk of memory leaks by unbalanced context calls. - *

    - * For context managers that are not {@linkplain Clearable} and contain an active {@linkplain nl.talsmasoftware.context.api.Context} - * that is not {@code Clearable} either, this active context will be closed normally. * * @deprecated Moved to the {@code nl.talsmasoftware.context.core} package. */ diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/Clearable.java b/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/Clearable.java deleted file mode 100644 index 14f7cca4..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/Clearable.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.clearable; - -/** - * Interface that marks an object to be 'clearable'. - *

    - * Context managers that support clearing the active context for the current thread - * should implement the {@link Clearable} interface. - *

    - * Clearing the context removes not only an active context from the current thread, - * but also the potential stack of any parents. - * This operation is intended to only be used when re-using threads (e.g. when returning them to a thread-pool). - * - * @author Sjoerd Talsma - * @see ClearableContextManager - * @deprecated This interface will be removed. Method clear() will be added to the ContextManager interface. - */ -@Deprecated -public interface Clearable { - - /** - * Clears the current context and any potential parent contexts that may be stacked. - */ - void clear(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/ClearableContextManager.java b/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/ClearableContextManager.java deleted file mode 100644 index 2a12756d..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/ClearableContextManager.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.clearable; - -import nl.talsmasoftware.context.ContextManager; - -/** - * Convenience interface to mark a {@linkplain Clearable} {@link ContextManager}. - * - * @param type of the context value - * @author Sjoerd Talsma - * @deprecated This interface will be removed. Method clear() will be added to the ContextManager interface. - */ -@Deprecated -public interface ClearableContextManager extends ContextManager, Clearable { -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/package-info.java deleted file mode 100644 index a12db73d..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/clearable/package-info.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * (Deprecated) The {@code Clearable} interface and a {@code ClearableContextManager} in particular. - * - *

    Deprecated

    - * This package will be removed. Method clear() will be added to the ContextManager interface. - * - *

    {@linkplain nl.talsmasoftware.context.clearable.Clearable}

    - *

    - * This interface declares the {@linkplain nl.talsmasoftware.context.clearable.Clearable#clear()} method. - * Clearing something is semantically different from closing. - * - *

    - * In the case of {@linkplain nl.talsmasoftware.context.clearable.ClearableContextManager}, - * closing any context only applies to that single context, - * while {@linkplain nl.talsmasoftware.context.clearable.ClearableContextManager#clear()} is - * equivalent to closing the active context and all parents in the current thread. - */ -package nl.talsmasoftware.context.clearable; From 4f77f7d1e3573b3a09fc8360882cd12782bc96dc Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 13:09:29 +0100 Subject: [PATCH 16/41] Remove deprecated priority comparator mechanism (including service caching). Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 41 +++--- .../context/core/PriorityComparator.java | 78 ----------- .../context/core/PriorityServiceLoader.java | 126 ------------------ .../talsmasoftware/context/core/Timers.java | 3 +- .../context/core/PriorityComparatorTest.java | 42 ------ 5 files changed, 27 insertions(+), 263 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityComparator.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityServiceLoader.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityComparatorTest.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 2e932b1e..ac667c45 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -27,6 +27,7 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,18 +46,23 @@ public final class ContextManagers { private static final Logger LOGGER = Logger.getLogger(ContextManagers.class.getName()); - /** - * The service loader that loads (and possibly caches) {@linkplain ContextManager} instances in prioritized order. - */ - private static final PriorityServiceLoader CONTEXT_MANAGERS = - new PriorityServiceLoader<>(ContextManager.class); - /** * Registered observers. */ private static final CopyOnWriteArrayList OBSERVERS = new CopyOnWriteArrayList<>(); + /** + * Sometimes a single, fixed classloader may be necessary (e.g. #97) + */ + private static volatile ClassLoader classLoaderOverride = null; + + /** + * The service loader that loads (and possibly caches) {@linkplain ContextManager} instances in prioritized order. + */ + @SuppressWarnings("rawtypes") + private static volatile ServiceLoader contextManagers = ServiceLoader.load(ContextManager.class); + /** * Private constructor to avoid instantiation of this class. */ @@ -97,7 +103,6 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho LOGGER.log(Level.FINEST, "There is no active context for " + manager + " in this snapshot."); } } catch (RuntimeException rte) { - CONTEXT_MANAGERS.clearCache(); LOGGER.log(Level.WARNING, "Exception obtaining active context from " + manager + " for snapshot.", rte); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext.exception"); } @@ -113,9 +118,11 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho /** * Clears all active contexts from the current thread. + * *

    * Contexts that are 'stacked' (i.e. restore the previous state upon close) should be * closed in a way that includes all 'parent' contexts as well. + * *

    * This operation is not intended to be used by general application code as it likely breaks any 'stacked' * active context that surrounding code may depend upon. @@ -242,20 +249,23 @@ public static boolean unregisterContextObserver(ContextObserver contextObserv * @since 1.0.5 */ public static void useClassLoader(ClassLoader classLoader) { - Level loglevel = PriorityServiceLoader.classLoaderOverride == classLoader ? Level.FINEST : Level.FINE; - if (LOGGER.isLoggable(loglevel)) { - LOGGER.log(loglevel, "Setting override classloader for loading ContextManager and ContextObserver " + - "instances to " + classLoader + " (was: " + PriorityServiceLoader.classLoaderOverride + ")."); + if (classLoaderOverride == classLoader) { + LOGGER.finest(() -> "Maintaining classloader override as " + classLoader + " (unchanged)"); + return; } - PriorityServiceLoader.classLoaderOverride = classLoader; + LOGGER.fine(() -> "Updating classloader override to " + classLoader + " (was: " + classLoaderOverride + ")"); + classLoaderOverride = classLoader; + contextManagers = classLoaderOverride == null + ? ServiceLoader.load(ContextManager.class) + : ServiceLoader.load(ContextManager.class, classLoaderOverride); } private static Iterable getContextManagers() { // TODO change to stream implementation when java 8 - return OBSERVERS.isEmpty() ? CONTEXT_MANAGERS : new Iterable() { + return OBSERVERS.isEmpty() ? contextManagers : new Iterable() { public Iterator iterator() { return new Iterator() { - private final Iterator delegate = CONTEXT_MANAGERS.iterator(); + private final Iterator delegate = contextManagers.iterator(); public boolean hasNext() { return delegate.hasNext(); @@ -266,7 +276,6 @@ public ContextManager next() { if (!(contextManager instanceof ObservableContextManager)) { for (ObservableContextManager observableContextManager : OBSERVERS) { if (observableContextManager.isWrapperOf(contextManager)) { - CONTEXT_MANAGERS.replaceInCache(contextManager, observableContextManager); return observableContextManager; } } @@ -307,7 +316,7 @@ public Reactivation reactivate() { Timers.timed(System.nanoTime() - start, nl.talsmasoftware.context.api.ContextSnapshot.class, "reactivate"); return reactivation; } catch (RuntimeException reactivationException) { - CONTEXT_MANAGERS.clearCache(); +// contextManagers.clearCache(); for (Context alreadyReactivated : reactivatedContexts) { if (alreadyReactivated != null) try { if (LOGGER.isLoggable(Level.FINEST)) { diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityComparator.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityComparator.java deleted file mode 100644 index c750d0ef..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityComparator.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core; - -import java.util.Comparator; - -import static java.lang.Math.abs; - -/** - * Comparator for classes that may or may not contain a {@literal @}Priority annotation - * on their class or superclasses. - *

    - * The priority is applied as follows: - *

      - *
    1. First, non-negative priority is applied in natural order (e.g. {@code 0}, {@code 1}, {@code 2}, ...).
    2. - *
    3. Next, objects without {@literal @}Priority annotation are applied - * by assigning a {@link #UNDEFINED_PRIORITY default priority} of {@link Integer#MAX_VALUE}.
    4. - *
    5. Finally, negative priority is applied in reverse-natural order (e.g. {@code -1}, {@code -2}, {@code -3}, ...).
    6. - *
    - *

    - * The order of objects with equal (implicit) priority is undefined. - * - * @author Sjoerd Talsma - * @deprecated We will switch to plain ServiceLoader in next major version to reduce complexity. - */ -@Deprecated -final class PriorityComparator implements Comparator { - private static final int UNDEFINED_PRIORITY = Integer.MAX_VALUE; - - static final boolean PRIORITY_AVAILABLE = isPriorityAnnotationAvailable(); - static final PriorityComparator INSTANCE = new PriorityComparator(); - - private PriorityComparator() { - } - - public int compare(Object value1, Object value2) { - return comparePriority(priorityOf(value1), priorityOf(value2)); - } - - private static int comparePriority(int prio1, int prio2) { - return prio1 == prio2 ? 0 - : prio1 < 0 ? (prio2 < 0 ? comparePriority(abs(prio1), abs(prio2)) : 1) - : prio2 < 0 ? -1 - : prio1 < prio2 ? -1 : 1; - } - - private static int priorityOf(Object value) { - if (value == null || !PRIORITY_AVAILABLE) return UNDEFINED_PRIORITY; - Class type = value instanceof Class ? (Class) value : value.getClass(); - // Don't import Priority. Loading the PriorityComparator class would fail if Priority isn't there at runtime! - javax.annotation.Priority priority = type.getAnnotation(javax.annotation.Priority.class); - return priority != null ? priority.value() : priorityOf(type.getSuperclass()); - } - - private static boolean isPriorityAnnotationAvailable() { - try { - return Class.forName("javax.annotation.Priority") != null; - } catch (ClassNotFoundException cnfe) { - return false; - } catch (LinkageError le) { - return false; - } - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityServiceLoader.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityServiceLoader.java deleted file mode 100644 index 358e0aa5..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/PriorityServiceLoader.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.Collections.sort; -import static java.util.Collections.unmodifiableList; - -/** - * Loader class to delegate to JDK 6 {@code ServiceLoader} or fallback to the old - * {@link javax.imageio.spi.ServiceRegistry ServiceRegistry}. - * - * @param The type of service to load. - * @author Sjoerd Talsma - * @deprecated We will switch to plain ServiceLoader in next major version to reduce complexity. - */ -@Deprecated -final class PriorityServiceLoader implements Iterable { - private static final Logger LOGGER = Logger.getLogger(PriorityServiceLoader.class.getName()); - private static final String SYSTEMPROPERTY_CACHING = "talsmasoftware.context.caching"; - private static final String ENVIRONMENT_CACHING_VALUE = System.getenv( - SYSTEMPROPERTY_CACHING.replace('.', '_').toUpperCase(Locale.ENGLISH)); - - // Set from ContextManagers.useClassLoader(); sometimes a single, fixed classloader may be necessary (e.g. #97) - static volatile ClassLoader classLoaderOverride = null; - private final Class serviceType; - private final Map> cache = new WeakHashMap>(); - - PriorityServiceLoader(Class serviceType) { - if (serviceType == null) throw new NullPointerException("Service type is ."); - this.serviceType = serviceType; - } - - @SuppressWarnings("unchecked") - public Iterator iterator() { - final ClassLoader classLoader = - classLoaderOverride == null ? Thread.currentThread().getContextClassLoader() : classLoaderOverride; - List services = cache.get(classLoader); - if (services == null) { - services = findServices(classLoader); - if (!isCachingDisabled()) cache.put(classLoader, services); - } - return services.iterator(); - } - - void replaceInCache(SVC current, SVC replacement) { - final ClassLoader classLoader = - classLoaderOverride == null ? Thread.currentThread().getContextClassLoader() : classLoaderOverride; - List services = cache.get(classLoader); - if (services != null) { - int idx = services.indexOf(current); - if (idx >= 0) { - ArrayList copy = new ArrayList(services); - copy.set(idx, replacement); - cache.put(classLoader, sortAndMakeUnmodifiable(copy)); - } - } - } - - /** - * Remove the cache so the next call to {@linkplain #iterator()} will attempt to load the objects again. - */ - void clearCache() { - cache.clear(); - } - - private static boolean isCachingDisabled() { - final String cachingProperty = System.getProperty(SYSTEMPROPERTY_CACHING, ENVIRONMENT_CACHING_VALUE); - return "0".equals(cachingProperty) || "false".equalsIgnoreCase(cachingProperty); - } - - private List findServices(ClassLoader classLoader) { - ArrayList found = new ArrayList(); - for (Iterator iterator = loadServices(serviceType, classLoader); iterator.hasNext(); ) { - SVC service = iterator.next(); - if (service != null) found.add(service); - } - return sortAndMakeUnmodifiable(found); - } - - private static List sortAndMakeUnmodifiable(ArrayList services) { - if (services.isEmpty()) return emptyList(); - else if (services.size() == 1) return singletonList(services.get(0)); - else if (PriorityComparator.PRIORITY_AVAILABLE) sort(services, PriorityComparator.INSTANCE); - services.trimToSize(); - return unmodifiableList(services); - } - - @SuppressWarnings("Since15") - private static Iterator loadServices(Class serviceType, ClassLoader classLoader) { - try { - return java.util.ServiceLoader.load(serviceType, classLoader).iterator(); - } catch (LinkageError le) { - LOGGER.log(Level.FINEST, "No ServiceLoader available, probably running on Java 1.5.", le); - return javax.imageio.spi.ServiceRegistry.lookupProviders(serviceType); - } catch (RuntimeException loadingException) { - LOGGER.log(Level.WARNING, "Unexpected error loading services of " + serviceType, loadingException); - return Collections.emptySet().iterator(); - } - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java index 2e6e8108..34ba48e1 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; @@ -40,7 +41,7 @@ private enum Singleton { Singleton() { List delegates = new ArrayList(); - for (ContextTimer delegate : new PriorityServiceLoader(ContextTimer.class)) { + for (ContextTimer delegate : ServiceLoader.load(ContextTimer.class)) { delegates.add(delegate); } this.delegates = delegates.toArray(new ContextTimer[0]); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityComparatorTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityComparatorTest.java deleted file mode 100644 index a95c87bc..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/PriorityComparatorTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core; - -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.List; - -import static java.util.Arrays.asList; -import static nl.talsmasoftware.context.Priorities.inheritedOne; -import static nl.talsmasoftware.context.Priorities.minus3; -import static nl.talsmasoftware.context.Priorities.minus5; -import static nl.talsmasoftware.context.Priorities.noPriority; -import static nl.talsmasoftware.context.Priorities.two; -import static nl.talsmasoftware.context.Priorities.zero; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; - -public class PriorityComparatorTest { - - @Test - public void testPrioritize() { - List objects = asList(two, minus5, noPriority, zero, minus3, inheritedOne, zero, two); - Collections.sort(objects, PriorityComparator.INSTANCE); - assertThat(objects, contains(zero, zero, inheritedOne, two, two, noPriority, minus3, minus5)); - } - -} From eb93ed3df73db7f66f7605d8072bc78e428ff9c0 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 13:23:52 +0100 Subject: [PATCH 17/41] Remove old abstract threadlocal base class. Signed-off-by: Sjoerd Talsma --- .../context/observer/ContextObserver.java | 2 - .../talsmasoftware/context/package-info.java | 2 +- .../AbstractThreadLocalContext.java | 123 ------------------ .../context/threadlocal/package-info.java | 32 ----- 4 files changed, 1 insertion(+), 158 deletions(-) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/package-info.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java index cee9a224..1b35d13e 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java @@ -32,8 +32,6 @@ * by the {@linkplain nl.talsmasoftware.context.ContextManagers#onActivate(Class, Object, Object)} * and {@linkplain nl.talsmasoftware.context.ContextManagers#onDeactivate(Class, Object, Object)} * utility methods.
    - * All subclasses of {@linkplain nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext} - * are already observable. * * @author Sjoerd Talsma * @deprecated Context observers will use simplified registration in v2. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java index 1cbaf441..d6815598 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java +++ b/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java @@ -24,7 +24,7 @@ * is activated in that thread. * *

    - * An {@linkplain nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} + * An {@linkplain nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} * base class is provided that supports nested contexts and provides predictable behaviour for out-of-order closing. * *

    {@linkplain nl.talsmasoftware.context.ContextManager}

    diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java b/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java deleted file mode 100644 index 06773ce7..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/AbstractThreadLocalContext.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.threadlocal; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; -import nl.talsmasoftware.context.api.Context; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Logger; - -/** - * Abstract base class maintaining a shared, static {@link ThreadLocal} instance for each concrete subclass. - * This threadlocal can be accessed by subclasses through the protected method: - * {@link #threadLocalInstanceOf(Class)}. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.threadlocal}. - */ -@Deprecated -public abstract class AbstractThreadLocalContext extends nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext { - private static final Logger LOGGER = Logger.getLogger(AbstractThreadLocalContext.class.getName()); - private static Class contextType; - - private final AtomicBoolean closed = new AtomicBoolean(false); - private final Class> contextManagerType; - - /** - * The parent context that was active at the time this context was created (if any) - * or null in case there was no active context when this context was created. - */ - protected final Context parentContext; - - /** - * The actual value, so subclasses can still access it after the context has been closed, - * because the default {@link #getValue()} implementation will return null in that case.
    - * Please be careful accessing the value after the context was closed: - * There is no pre-defined meaningful way to handle this situation, as this depends heavily - * on the desired features of the particular implementation. - */ - protected final T value; - - /** - * Instantiates a new context with the specified value. - * The new context will be made the active context for the current thread. - * - * @param newValue The new value to become active in this new context - * (or null to register a new context with 'no value'). - */ - protected AbstractThreadLocalContext(T newValue) { - this(null, newValue); - } - - /** - * Instantiates a new context with the specified value. - * The new context will be made the active context for the current thread. - * - * @param contextManagerType The context manager type (required to notify appropriate observers) - * @param newValue The new value to become active in this new context - * (or null to register a new context with 'no value'). - */ - @SuppressWarnings("unchecked") - protected AbstractThreadLocalContext(Class> contextManagerType, T newValue) { - super(newValue); - this.contextManagerType = contextManagerType; - this.parentContext = super.parentContext; - this.value = super.value; - ContextManagers.onActivate(contextManagerType, value, parentContext == null ? null : parentContext.getValue()); - } - - /** - * Returns whether this context is closed or not. - * - * @return Whether the context is already closed. - */ - protected boolean isClosed() { - return super.isClosed(); - } - - /** - * Closes this context and in case this context is the active context, - * restores the active context to the (unclosed) parent context.
    - * If no unclosed parent context exists, the 'active context' is cleared. - *

    - * This method has no side-effects if the context was already closed (it is safe to call multiple times). - */ - public synchronized void close() { - final boolean observe = !super.isClosed(); - super.close(); - if (observe) ContextManagers.onDeactivate(contextManagerType, this.value, getValue()); - } - - /** - * Returns the shared, static {@link ThreadLocal} instance for the specified context type. - * - * @param contextType The first concrete subclass of the abstract threadlocal context - * (So values from separate subclasses do not get mixed up). - * @param The type being managed by the context. - * @param The first non-abstract context subclass of AbstractThreadLocalContext. - * @return The non-null shared ThreadLocal instance to register these contexts on. - */ - protected static > ThreadLocal threadLocalInstanceOf( - final Class contextType) { - return nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext.threadLocalInstanceOf(contextType); - } - - protected static > CTX current(Class contextType) { - return nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext.current(contextType); - } -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/package-info.java deleted file mode 100644 index 9b5c940e..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/threadlocal/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Package for {@code ThreadLocal} specific classes. - * - *

    {@linkplain nl.talsmasoftware.context.threadlocal.AbstractThreadLocalContext}

    - *

    - * Base class for all our own context implementations.
    - * It features: - *

      - *
    • Nesting; the previously active context is remembered when activating a new one, - * so it can be restored after the new context ends. - *
    • Predictable behaviour when used in a wrong way. Out-of-order closing can happen and will - * result in 'skipping' an already closed context as the currently active context. - * Closing from a different thread than where the context was created is wrong, however the - * AbstractThreadLocalContext will deal with it. - *
    - */ -package nl.talsmasoftware.context.threadlocal; \ No newline at end of file From 34c6d3672008a0573c043f4330e0cc0e65948985 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 14:19:27 +0100 Subject: [PATCH 18/41] New module names for context-propagation-api and context-propagation-core. Signed-off-by: Sjoerd Talsma --- .../README.md | 0 .../pom.xml | 8 +- .../talsmasoftware/context/api/Context.java | 0 .../context/api/ContextManager.java | 0 .../context/api/ContextObserver.java | 2 - .../context/api/ContextSnapshot.java | 0 .../context/api/ContextTimer.java | 0 .../context/core/ContextManagers.java | 22 +- .../talsmasoftware/context/core/Timers.java | 0 .../ContextAwareExecutorService.java | 40 +--- .../CallMappingExecutorService.java | 0 .../core/delegation/CallableToRunnable.java | 0 .../delegation/DelegatingExecutorService.java | 0 .../core/delegation/DelegatingFuture.java | 0 .../context/core/delegation/Wrapper.java | 0 .../core/delegation/WrapperWithContext.java | 0 .../context/core/delegation/package-info.java | 0 .../AbstractThreadLocalContext.java | 0 .../ContextAwareExecutorService.java | 0 .../context/executors/package-info.java | 2 +- .../talsmasoftware/context/package-info.java | 9 +- .../AutoInitializingContextManager.java | 0 .../ClearableContextManagerTest.java | 0 .../ClearableDummyContextManager.java | 0 .../context/core/ContextManagersTest.java | 2 +- .../context/core/ContextSnapshotTest.java | 0 .../context/core/NoContextManagersTest.java | 4 +- .../context/core/TimersTest.java | 0 .../ContextAwareExecutorServiceTest.java | 0 .../delegation/CallableToRunnableTest.java | 0 .../DelegatingExecutorServiceTest.java | 0 .../core/delegation/DelegatingFutureTest.java | 0 .../MappingExecutorServiceTest.java | 0 .../context/core/delegation/WrapperTest.java | 0 .../delegation/WrapperWithContextTest.java | 0 .../context/dummy/DummyContext.java | 0 .../context/dummy/DummyContextManager.java | 0 .../context/dummy/ThrowingContextManager.java | 0 ...LoaderTest$ServiceWithSingleImplementation | 0 ...text.PriorityServiceLoaderTest$TestService | 0 ....talsmasoftware.context.api.ContextManager | 0 ...nl.talsmasoftware.context.api.ContextTimer | 0 ...LoaderTest$ServiceWithSingleImplementation | 0 ...core.PriorityServiceLoaderTest$TestService | 0 .../src/test/resources/logging.properties | 0 context-propagation-bom/pom.xml | 17 +- .../README.md | 0 .../pom.xml | 10 +- .../ContextAwareCompletableFuture.java | 0 .../concurrent/ContextSnapshotHolder.java | 0 .../core/function/BiConsumerWithContext.java | 0 .../core/function/BiFunctionWithContext.java | 0 .../core/function/BiPredicateWithContext.java | 0 .../function/BinaryOperatorWithContext.java | 0 .../function/BooleanSupplierWithContext.java | 0 .../core/function/ConsumerWithContext.java | 0 .../core/function/FunctionWithContext.java | 0 .../core/function/PredicateWithContext.java | 0 .../core/function/RunnableWithContext.java | 0 .../core/function/SupplierWithContext.java | 0 .../function/UnaryOperatorWithContext.java | 0 .../WrapperWithContextAndConsumer.java | 0 .../functions/BiConsumerWithContext.java | 0 .../functions/BiFunctionWithContext.java | 0 .../functions/BiPredicateWithContext.java | 0 .../functions/BinaryOperatorWithContext.java | 0 .../functions/BooleanSupplierWithContext.java | 0 .../functions/ConsumerWithContext.java | 0 .../functions/FunctionWithContext.java | 0 .../functions/PredicateWithContext.java | 0 .../functions/RunnableWithContext.java | 0 .../functions/SupplierWithContext.java | 0 .../functions/UnaryOperatorWithContext.java | 0 .../WrapperWithContextAndConsumer.java | 0 .../context/functions/package-info.java | 3 +- .../ContextAwareCompletableFuture.java | 0 .../futures/ContextSnapshotHolder.java | 0 .../context/futures/package-info.java | 0 .../core/concurrent}/CompletedFutureTest.java | 4 +- .../ContextAwareCompletableFutureTest.java | 0 .../function/BiConsumerWithContextTest.java | 0 .../BooleanSupplierWithContextTest.java | 5 +- .../function}/ConsumerWithContextTest.java | 7 +- .../context/dummy/DummyContextManager.java | 0 .../functions/BiFunctionWithContextTest.java | 0 .../functions/BiPredicateWithContextTest.java | 0 .../BinaryOperatorWithContextTest.java | 0 .../functions/FunctionWithContextTest.java | 0 .../functions/PredicateWithContextTest.java | 0 .../functions/RunnableWithContextTest.java | 0 .../functions/SupplierWithContextTest.java | 0 .../UnaryOperatorWithContextTest.java | 0 .../WrapperWithContextAndConsumerTest.java | 0 .../ContextAwareCompletableFutureTest.java | 0 .../futures/ContextSnapshotHolderTest.java | 0 .../context/futures/FailedFutureTest.java | 0 ....talsmasoftware.context.api.ContextManager | 0 .../src/test/resources/logging.properties | 0 context-propagation-metrics/pom.xml | 4 +- context-propagation-micrometer/pom.xml | 4 +- .../context/ContextManager.java | 65 ------ .../context/ContextManagers.java | 200 ------------------ .../context/PriorityComparator.java | 78 ------- .../context/PriorityServiceLoader.java | 126 ----------- .../context/observer/ContextObserver.java | 63 ------ .../context/observer/ContextObservers.java | 79 ------- .../context/observer/package-info.java | 32 --- .../nl/talsmasoftware/context/Priorities.java | 55 ----- .../context/PriorityComparatorTest.java | 42 ---- locale-context/pom.xml | 4 +- log4j2-propagation/pom.xml | 4 +- opentracing-span-propagation/pom.xml | 4 +- .../OpentracingContextTimerTest.java | 4 +- pom.xml | 22 +- servletrequest-propagation/pom.xml | 4 +- slf4j-propagation/pom.xml | 4 +- spring-security-context/pom.xml | 4 +- 117 files changed, 80 insertions(+), 853 deletions(-) rename {context-propagation => context-propagation-api}/README.md (100%) rename {context-propagation => context-propagation-api}/pom.xml (88%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/api/Context.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/api/ContextManager.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java (97%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java (96%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/Timers.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java (61%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java (100%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/executors/package-info.java (97%) rename {context-propagation => context-propagation-api}/src/main/java/nl/talsmasoftware/context/package-info.java (82%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java (99%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java (93%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/TimersTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java (100%) rename {context-propagation => context-propagation-api}/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation (100%) rename {context-propagation => context-propagation-api}/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService (100%) rename {context-propagation => context-propagation-api}/src/test/resources/logging.properties (100%) rename {context-propagation-java8 => context-propagation-core}/README.md (100%) rename {context-propagation-java8 => context-propagation-core}/pom.xml (82%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/functions/package-info.java (98%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/main/java/nl/talsmasoftware/context/futures/package-info.java (100%) rename {context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures => context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent}/CompletedFutureTest.java (96%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java (100%) rename {context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions => context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function}/BooleanSupplierWithContextTest.java (96%) rename {context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions => context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function}/ConsumerWithContextTest.java (96%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager (100%) rename {context-propagation-java8 => context-propagation-core}/src/test/resources/logging.properties (100%) delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/PriorityComparator.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/PriorityServiceLoader.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObservers.java delete mode 100644 context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/Priorities.java delete mode 100644 context-propagation/src/test/java/nl/talsmasoftware/context/PriorityComparatorTest.java diff --git a/context-propagation/README.md b/context-propagation-api/README.md similarity index 100% rename from context-propagation/README.md rename to context-propagation-api/README.md diff --git a/context-propagation/pom.xml b/context-propagation-api/pom.xml similarity index 88% rename from context-propagation/pom.xml rename to context-propagation-api/pom.xml index 42b6f9c7..eafc938f 100644 --- a/context-propagation/pom.xml +++ b/context-propagation-api/pom.xml @@ -22,17 +22,17 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT - context-propagation - Context propagation (core) + context-propagation-api + Context propagation (API) jar - ${project.groupId} + ${project.groupId}.api ${project.parent.basedir} 8 diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/api/Context.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextManager.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java similarity index 97% rename from context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java index fcb0dfd4..6a1feab6 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java @@ -15,8 +15,6 @@ */ package nl.talsmasoftware.context.api; -import nl.talsmasoftware.context.ContextManager; - /** * Observe context updates for a particular {@linkplain ContextManager}. * diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java similarity index 96% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index ac667c45..f5a54701 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -57,12 +57,6 @@ public final class ContextManagers { */ private static volatile ClassLoader classLoaderOverride = null; - /** - * The service loader that loads (and possibly caches) {@linkplain ContextManager} instances in prioritized order. - */ - @SuppressWarnings("rawtypes") - private static volatile ServiceLoader contextManagers = ServiceLoader.load(ContextManager.class); - /** * Private constructor to avoid instantiation of this class. */ @@ -241,31 +235,30 @@ public static boolean unregisterContextObserver(ContextObserver contextObserv *
      *
    • Please be aware that this configuration is global! *
    • This will also affect the lookup of - * {@linkplain nl.talsmasoftware.context.observer.ContextObserver context observers} + * {@linkplain nl.talsmasoftware.context.api.ContextObserver context observers} *
    * * @param classLoader The single, fixed ClassLoader to use for finding context managers. * Specify {@code null} to restore the default behaviour. * @since 1.0.5 */ - public static void useClassLoader(ClassLoader classLoader) { + public static synchronized void useClassLoader(ClassLoader classLoader) { if (classLoaderOverride == classLoader) { LOGGER.finest(() -> "Maintaining classloader override as " + classLoader + " (unchanged)"); return; } LOGGER.fine(() -> "Updating classloader override to " + classLoader + " (was: " + classLoaderOverride + ")"); classLoaderOverride = classLoader; - contextManagers = classLoaderOverride == null - ? ServiceLoader.load(ContextManager.class) - : ServiceLoader.load(ContextManager.class, classLoaderOverride); } private static Iterable getContextManagers() { // TODO change to stream implementation when java 8 - return OBSERVERS.isEmpty() ? contextManagers : new Iterable() { + final Iterable resolved = classLoaderOverride == null ? ServiceLoader.load(ContextManager.class) + : ServiceLoader.load(ContextManager.class, classLoaderOverride); + return OBSERVERS.isEmpty() ? resolved : new Iterable() { public Iterator iterator() { return new Iterator() { - private final Iterator delegate = contextManagers.iterator(); + private final Iterator delegate = resolved.iterator(); public boolean hasNext() { return delegate.hasNext(); @@ -316,7 +309,6 @@ public Reactivation reactivate() { Timers.timed(System.nanoTime() - start, nl.talsmasoftware.context.api.ContextSnapshot.class, "reactivate"); return reactivation; } catch (RuntimeException reactivationException) { -// contextManagers.clearCache(); for (Context alreadyReactivated : reactivatedContexts) { if (alreadyReactivated != null) try { if (LOGGER.isLoggable(Level.FINEST)) { @@ -387,7 +379,7 @@ private static final class ObservableContextManager extends Wrapper delegate, List> observers) { super(delegate); - this.observers = new CopyOnWriteArrayList>(observers); + this.observers = new CopyOnWriteArrayList<>(observers); } private boolean observes(Class> contextManagerType) { diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/Timers.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java similarity index 61% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java index a7ba41db..6902fd2c 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java @@ -15,15 +15,13 @@ */ package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.core.delegation.CallMappingExecutorService; -import java.io.Closeable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Executor service that wraps another executor service, making sure background tasks operates 'within' @@ -39,8 +37,6 @@ * @author Sjoerd Talsma */ public class ContextAwareExecutorService extends CallMappingExecutorService { - private static final Logger LOGGER = Logger.getLogger(ContextAwareExecutorService.class.getName()); - public ContextAwareExecutorService(ExecutorService delegate) { super(delegate); } @@ -56,36 +52,10 @@ public ContextAwareExecutorService(ExecutorService delegate) { @Override protected Callable map(final Callable callable) { final ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - return new Callable() { - public V call() throws Exception { - Exception exception = null; - final Closeable context = snapshot.reactivate(); - try { - return callable.call(); - } catch (Exception ex) { - throw exception = ex; - } finally { - tryClose(context, exception); - } + return () -> { + try (Reactivation reactivation = snapshot.reactivate()) { + return callable.call(); } }; } - - /** - * tryClose method to be called from a finally() block that properly manages close exceptions. - * - * @param context context to be closed - * @param exception exception if any occurred - */ - private static void tryClose(Closeable context, Exception exception) throws Exception { - if (context != null) try { - context.close(); - } catch (RuntimeException closeEx) { - if (exception != null) { - LOGGER.log(Level.WARNING, "Exception closing context after failed operation: " + closeEx.getMessage(), closeEx); - throw exception; - } - throw closeEx; - } - } } diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java similarity index 100% rename from context-propagation/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/executors/package-info.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java similarity index 97% rename from context-propagation/src/main/java/nl/talsmasoftware/context/executors/package-info.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java index 9d9428c2..1d9d6bb5 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/executors/package-info.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java similarity index 82% rename from context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java rename to context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java index d6815598..f1814c52 100644 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/package-info.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java @@ -27,11 +27,12 @@ * An {@linkplain nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} * base class is provided that supports nested contexts and provides predictable behaviour for out-of-order closing. * - *

    {@linkplain nl.talsmasoftware.context.ContextManager}

    + *

    {@linkplain nl.talsmasoftware.context.api.ContextManager}

    *

    * Manages the active context. - * Can {@linkplain nl.talsmasoftware.context.ContextManager#initializeNewContext(java.lang.Object) initialize a new context} - * and provides access to the {@linkplain nl.talsmasoftware.context.ContextManager#getActiveContext() active context}. + * Can {@linkplain nl.talsmasoftware.context.api.ContextManager#initializeNewContext(java.lang.Object) initialize a new context} + * and provides access to + * the {@linkplain nl.talsmasoftware.context.api.ContextManager#getActiveContextValue() active context value}. * *

    {@linkplain nl.talsmasoftware.context.api.ContextSnapshot}

    *

    @@ -42,7 +43,7 @@ *

    * All context aware utility classes in this library are tested to make sure they reactivate and close snapshots in a safe way. * - *

    {@linkplain nl.talsmasoftware.context.ContextManagers}

    + *

    {@linkplain nl.talsmasoftware.context.core.ContextManagers}

    *

    * Utility class that detects available context managers and lets you take a snapshot of all active contexts at once. * diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java similarity index 99% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index 5c398820..3d6c76c4 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java +++ b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -215,7 +215,7 @@ public void testConcurrentSnapshots_fixedClassLoader() throws ExecutionException int threadcount = 25; ExecutorService threadpool = Executors.newFixedThreadPool(threadcount); try { - List> snapshots = new ArrayList>(threadcount); + List> snapshots = new ArrayList<>(threadcount); for (int i = 0; i < threadcount; i++) { snapshots.add(threadpool.submit(ContextManagers::createContextSnapshot)); } diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java similarity index 93% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java index b33db0eb..6ae54665 100644 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java +++ b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java @@ -52,7 +52,7 @@ public void resetDefaultClassLoader() { @Test public void testReactivate_withoutContextManagers() throws IOException { Context ctx1 = new DummyContext("foo"); - ContextSnapshot snapshot = nl.talsmasoftware.context.ContextManagers.createContextSnapshot(); + ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx1.close(); Closeable reactivated = snapshot.reactivate(); @@ -61,7 +61,7 @@ public void testReactivate_withoutContextManagers() throws IOException { @Test public void testCreateSnapshot_withoutContextManagers() throws IOException { - ContextSnapshot snapshot = nl.talsmasoftware.context.ContextManagers.createContextSnapshot(); + ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); assertThat(snapshot, is(notNullValue())); Closeable reactivated = snapshot.reactivate(); diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/TimersTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/TimersTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/TimersTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java similarity index 100% rename from context-propagation/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java rename to context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation diff --git a/context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService similarity index 100% rename from context-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService rename to context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService diff --git a/context-propagation/src/test/resources/logging.properties b/context-propagation-api/src/test/resources/logging.properties similarity index 100% rename from context-propagation/src/test/resources/logging.properties rename to context-propagation-api/src/test/resources/logging.properties diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index cbed04c5..a7103650 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -16,12 +16,13 @@ limitations under the License. --> - + 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -43,36 +44,36 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} ${project.groupId} - context-propagation + context-propagation-api ${project.version} javadoc ${project.groupId} - context-propagation + context-propagation-api ${project.version} sources ${project.groupId} - context-propagation-java8 + context-propagation-core ${project.version} ${project.groupId} - context-propagation-java8 + context-propagation-core ${project.version} javadoc ${project.groupId} - context-propagation-java8 + context-propagation-core ${project.version} sources diff --git a/context-propagation-java8/README.md b/context-propagation-core/README.md similarity index 100% rename from context-propagation-java8/README.md rename to context-propagation-core/README.md diff --git a/context-propagation-java8/pom.xml b/context-propagation-core/pom.xml similarity index 82% rename from context-propagation-java8/pom.xml rename to context-propagation-core/pom.xml index 24c76822..efdc6782 100644 --- a/context-propagation-java8/pom.xml +++ b/context-propagation-core/pom.xml @@ -23,24 +23,24 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT - context-propagation-java8 - Context propagation (java-8) + context-propagation-core + Context propagation (core) jar - ${project.groupId}.java8 + ${project.groupId}.core ${project.parent.basedir} ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolder.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java similarity index 98% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/package-info.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java index e84133f9..564b0f45 100644 --- a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/functions/package-info.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** * Java 8 functional interface wrappers that apply context snapshots to the mapped functions. * diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java diff --git a/context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java similarity index 100% rename from context-propagation-java8/src/main/java/nl/talsmasoftware/context/futures/package-info.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/CompletedFutureTest.java similarity index 96% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/CompletedFutureTest.java index 75f3468a..bfc7d660 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/CompletedFutureTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/CompletedFutureTest.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.futures; +package nl.talsmasoftware.context.core.concurrent; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java similarity index 96% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java index 2c4676bb..32e0605c 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -53,7 +53,6 @@ public void clearDummyContext() { } @BeforeEach - @SuppressWarnings("unchecked") public void setUp() { unawareThreadpool = Executors.newCachedThreadPool(); } diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java similarity index 96% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java index 26aca887..e36775f4 100644 --- a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/ConsumerWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; -import nl.talsmasoftware.context.ContextManagers; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.dummy.DummyContextManager; +import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -88,7 +89,7 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { val -> { assertThat("Context must propagate into thread", currentValue(), is(Optional.of("Old value"))); setCurrentValue(val); - assertThat("Context changed in background thread", currentValue(), is(Optional.of(val))); + assertThat("Context changed in background thread", currentValue(), Matchers.is(Optional.of(val))); trySleep(250); }, s -> snapshotHolder[0] = s); diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java diff --git a/context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java similarity index 100% rename from context-propagation-java8/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java diff --git a/context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager similarity index 100% rename from context-propagation-java8/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename to context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation-java8/src/test/resources/logging.properties b/context-propagation-core/src/test/resources/logging.properties similarity index 100% rename from context-propagation-java8/src/test/resources/logging.properties rename to context-propagation-core/src/test/resources/logging.properties diff --git a/context-propagation-metrics/pom.xml b/context-propagation-metrics/pom.xml index d6002514..f25ac492 100644 --- a/context-propagation-metrics/pom.xml +++ b/context-propagation-metrics/pom.xml @@ -23,7 +23,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -40,7 +40,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/context-propagation-micrometer/pom.xml b/context-propagation-micrometer/pom.xml index ab00690e..0e90a38f 100644 --- a/context-propagation-micrometer/pom.xml +++ b/context-propagation-micrometer/pom.xml @@ -23,7 +23,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -42,7 +42,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java deleted file mode 100644 index cc5f8a5c..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManager.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import nl.talsmasoftware.context.api.Context; - -/** - * The contract for a ContextManager Service. - * - *

    - * Implementations can be registered by providing a fully qualified class name in a service file called:
    - * "/META-INF/services/nl.talsmasoftware.context.ContextManager"
    - * That will take care of any active context being captured in {@link nl.talsmasoftware.context.api.ContextSnapshot} instances - * managed by the {@link ContextManagers} utility class.
    - * Note: Make sure your implementation has a default (no-argument) constructor. - * - *

    - * A context manager is required to notify - * registered {@linkplain nl.talsmasoftware.context.observer.ContextObserver ContextObserver} instances - * of context updates.
    - * The {@linkplain nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext AbstractThreadLocalContext} - * already notifies these observers.
    - * Other implementations can use the {@linkplain ContextManagers#onActivate(Class, Object, Object)} - * and {@linkplain ContextManagers#onDeactivate(Class, Object, Object)} methods - * to notify the appropriate context observers. - * - * @param type of the context value - * @author Sjoerd Talsma - * @deprecated Move to the {@code nl.talsmasoftware.context.api} package. - */ -@Deprecated -public interface ContextManager { - - /** - * Initialize a new context containing the specified value. - *

    - * Whether the value is allowed to be null is up to the implementation. - * - * @param value The value to initialize a new context for. - * @return The new active context containing the specified value - * which should be closed by the caller at the end of its lifecycle from the same thread. - */ - Context initializeNewContext(T value); - - /** - * The currently active context, or null if no context is active. - * - * @return The active context or null if there is none. - */ - Context getActiveContext(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java deleted file mode 100644 index 571656e6..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/ContextManagers.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import nl.talsmasoftware.context.api.ContextObserver; - -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Core implementation to allow {@link #createContextSnapshot() taking a snapshot of all contexts}. - * - *

    - * Such a {@link nl.talsmasoftware.context.api.ContextSnapshot snapshot} can be passed to a background task to allow the context to be - * {@link nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated} in that background thread, until it gets - * {@link nl.talsmasoftware.context.api.Context#close() closed} again (preferably in a try-with-resources construct). - * - * @author Sjoerd Talsma - * @see nl.talsmasoftware.context.core.ContextManagers - * @deprecated This class has moved to the {@code nl.talsmasoftware.context.core} package. - */ -@Deprecated -public final class ContextManagers { - - /** - * The service loader that loads (and possibly caches) {@linkplain ContextManager} instances in prioritized order. - * - * @see nl.talsmasoftware.context.core.ContextManagers#registerContextObserver(ContextObserver, Class) - * @see nl.talsmasoftware.context.core.ContextManagers#unregisterContextObserver(ContextObserver) - * @deprecated To be replaced by explicitly registered observers - */ - @Deprecated - private static final PriorityServiceLoader CONTEXT_OBSERVERS = - new PriorityServiceLoader(nl.talsmasoftware.context.observer.ContextObserver.class); - - /** - * Private constructor to avoid instantiation of this class. - */ - private ContextManagers() { - throw new UnsupportedOperationException(); - } - - /** - * This method is able to create a 'snapshot' from the current - * {@link ContextManager#getActiveContext() active context} from all known {@link ContextManager} - * implementations. - *

    - * This snapshot is returned as a single object that can be temporarily - * {@link nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated}. Don't forget to {@link nl.talsmasoftware.context.api.Context#close() close} the reactivated - * context once you're done, preferably in a try-with-resources construct. - * - * @return A new snapshot that can be reactivated elsewhere (e.g. a background thread or even another node) - * within a try-with-resources construct. - * @deprecated Moved to the {@code nl.talsmasoftware.context.core} package. - */ - @Deprecated - public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapshot() { - return nl.talsmasoftware.context.core.ContextManagers.createContextSnapshot(); - } - - /** - * Clears all active contexts from the current thread. - *

    - * Contexts that are 'stacked' (i.e. restore the previous state upon close) should be - * closed in a way that includes all 'parent' contexts as well. - *

    - * This operation is not intended to be used by general application code as it likely breaks any 'stacked' - * active context that surrounding code may depend upon. - * Appropriate use includes thread management, where threads are reused by some pooling - * mechanism. For example, it is considered safe to clear the context when obtaining a 'fresh' thread from a - * thread pool (as no context expectations should exist at that point). - * An even better strategy would be to clear the context right before returning a used thread to the pool - * as this will allow any unclosed contexts to be garbage collected. Besides preventing contextual issues, - * this reduces the risk of memory leaks by unbalanced context calls. - * - * @deprecated Moved to the {@code nl.talsmasoftware.context.core} package. - */ - @Deprecated - public static void clearActiveContexts() { - nl.talsmasoftware.context.core.ContextManagers.clearActiveContexts(); - } - - /** - * Override the {@linkplain ClassLoader} used to lookup {@linkplain ContextManager contextmanagers}. - *

    - * Normally, taking a snapshot uses the {@linkplain Thread#getContextClassLoader() Context ClassLoader} from the - * {@linkplain Thread#currentThread() current thread} to look up all {@linkplain ContextManager context managers}. - * It is possible to configure a fixed, single classloader in your application for looking up the context managers. - *

    - * Using this method to specify a fixed classloader will only impact - * new {@linkplain nl.talsmasoftware.context.api.ContextSnapshot context snapshots}. Existing snapshots will not be impacted. - *

    - * Notes:
    - *

      - *
    • Please be aware that this configuration is global! - *
    • This will also affect the lookup of - * {@linkplain nl.talsmasoftware.context.observer.ContextObserver context observers} - *
    - * - * @param classLoader The single, fixed ClassLoader to use for finding context managers. - * Specify {@code null} to restore the default behaviour. - * @since 1.0.5 - * @deprecated Moved to the {@code nl.talsmasoftware.context.core} package. - */ - @Deprecated - public static void useClassLoader(ClassLoader classLoader) { - PriorityServiceLoader.classLoaderOverride = classLoader; - nl.talsmasoftware.context.core.ContextManagers.useClassLoader(classLoader); - } - - /** - * Notify all {@linkplain ContextObserver context observers} for the specified {@code contextManager} - * about the activated context value. - * - * @param contextManager The context manager type that activated the context (required to observe). - * @param activatedContextValue The activated context value or {@code null} if no value was activated. - * @param previousContextValue The previous context value or {@code null} if unknown or unsupported. - * @param The type managed by the context manager. - * @see nl.talsmasoftware.context.core.ContextManagers#registerContextObserver(ContextObserver, Class) - * @see nl.talsmasoftware.context.core.ContextManagers#unregisterContextObserver(ContextObserver) - * @since 1.0.6 - * @deprecated Replaced by explicit observer registration - */ - @Deprecated - @SuppressWarnings("unchecked") // If the observer tells us it can observe the values, we trust it. - public static void onActivate(Class> contextManager, - T activatedContextValue, - T previousContextValue) { - if (contextManager != null) { - for (nl.talsmasoftware.context.observer.ContextObserver observer : CONTEXT_OBSERVERS) { - try { - final Class observedContext = observer.getObservedContextManager(); - // TODO unwrap ObservableContextManager.type and/or skip - if (observedContext != null && observedContext.isAssignableFrom(contextManager)) { - observer.onActivate(activatedContextValue, previousContextValue); - // TODO log warning about deprecated mechanism - } - } catch (RuntimeException observationException) { - Logger.getLogger(observer.getClass().getName()).log(Level.WARNING, - "Exception in " + observer.getClass().getSimpleName() - + ".onActivate(" + activatedContextValue + ", " + previousContextValue - + ") for " + contextManager.getSimpleName() + ": " + observationException.getMessage(), - observationException); - } - } - } - } - - /** - * Notify all {@linkplain ContextObserver context observers} for the specified {@code contextManager} - * about the deactivated context value. - * - * @param contextManager The context manager type that deactivated the context (required to observe). - * @param deactivatedContextValue The deactivated context value - * @param restoredContextValue The restored context value or {@code null} if unknown or unsupported. - * @param The type managed by the context manager. - * @see nl.talsmasoftware.context.core.ContextManagers#registerContextObserver(ContextObserver, Class) - * @see nl.talsmasoftware.context.core.ContextManagers#unregisterContextObserver(ContextObserver) - * @since 1.0.6 - * @deprecated To be replaced by explicit observer registration method - */ - @Deprecated - @SuppressWarnings("unchecked") // If the observer tells us it can observe the values, we trust it. - public static void onDeactivate(Class> contextManager, - T deactivatedContextValue, - T restoredContextValue) { - if (contextManager != null) { - for (nl.talsmasoftware.context.observer.ContextObserver observer : CONTEXT_OBSERVERS) { - try { - final Class observedContext = observer.getObservedContextManager(); - // TODO unwrap ObservableContextManager.type and/or skip - if (observedContext != null && observedContext.isAssignableFrom(contextManager)) { - observer.onDeactivate(deactivatedContextValue, restoredContextValue); - // TODO log warning about deprecated mechanism - } - } catch (RuntimeException observationException) { - Logger.getLogger(observer.getClass().getName()).log(Level.WARNING, - "Exception in " + observer.getClass().getSimpleName() - + ".onDeactivate(" + deactivatedContextValue + ", " + deactivatedContextValue - + ") for " + contextManager.getSimpleName() + ": " + observationException.getMessage(), - observationException); - } - } - } - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityComparator.java b/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityComparator.java deleted file mode 100644 index 0efff7a3..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityComparator.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import java.util.Comparator; - -import static java.lang.Math.abs; - -/** - * Comparator for classes that may or may not contain a {@literal @}Priority annotation - * on their class or superclasses. - *

    - * The priority is applied as follows: - *

      - *
    1. First, non-negative priority is applied in natural order (e.g. {@code 0}, {@code 1}, {@code 2}, ...).
    2. - *
    3. Next, objects without {@literal @}Priority annotation are applied - * by assigning a {@link #UNDEFINED_PRIORITY default priority} of {@link Integer#MAX_VALUE}.
    4. - *
    5. Finally, negative priority is applied in reverse-natural order (e.g. {@code -1}, {@code -2}, {@code -3}, ...).
    6. - *
    - *

    - * The order of objects with equal (implicit) priority is undefined. - * - * @author Sjoerd Talsma - * @deprecated We will switch to plain ServiceLoader in next major version to reduce complexity. - */ -@Deprecated -final class PriorityComparator implements Comparator { - private static final int UNDEFINED_PRIORITY = Integer.MAX_VALUE; - - static final boolean PRIORITY_AVAILABLE = isPriorityAnnotationAvailable(); - static final PriorityComparator INSTANCE = new PriorityComparator(); - - private PriorityComparator() { - } - - public int compare(Object value1, Object value2) { - return comparePriority(priorityOf(value1), priorityOf(value2)); - } - - private static int comparePriority(int prio1, int prio2) { - return prio1 == prio2 ? 0 - : prio1 < 0 ? (prio2 < 0 ? comparePriority(abs(prio1), abs(prio2)) : 1) - : prio2 < 0 ? -1 - : prio1 < prio2 ? -1 : 1; - } - - private static int priorityOf(Object value) { - if (value == null || !PRIORITY_AVAILABLE) return UNDEFINED_PRIORITY; - Class type = value instanceof Class ? (Class) value : value.getClass(); - // Don't import Priority. Loading the PriorityComparator class would fail if Priority isn't there at runtime! - javax.annotation.Priority priority = type.getAnnotation(javax.annotation.Priority.class); - return priority != null ? priority.value() : priorityOf(type.getSuperclass()); - } - - private static boolean isPriorityAnnotationAvailable() { - try { - return Class.forName("javax.annotation.Priority") != null; - } catch (ClassNotFoundException cnfe) { - return false; - } catch (LinkageError le) { - return false; - } - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityServiceLoader.java b/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityServiceLoader.java deleted file mode 100644 index 17b88684..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/PriorityServiceLoader.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.Collections.sort; -import static java.util.Collections.unmodifiableList; - -/** - * Loader class to delegate to JDK 6 {@code ServiceLoader} or fallback to the old - * {@link javax.imageio.spi.ServiceRegistry ServiceRegistry}. - * - * @param The type of service to load. - * @author Sjoerd Talsma - * @deprecated We will switch to plain ServiceLoader in next major version to reduce complexity. - */ -@Deprecated -final class PriorityServiceLoader implements Iterable { - private static final Logger LOGGER = Logger.getLogger(PriorityServiceLoader.class.getName()); - private static final String SYSTEMPROPERTY_CACHING = "talsmasoftware.context.caching"; - private static final String ENVIRONMENT_CACHING_VALUE = System.getenv( - SYSTEMPROPERTY_CACHING.replace('.', '_').toUpperCase(Locale.ENGLISH)); - - // Set from ContextManagers.useClassLoader(); sometimes a single, fixed classloader may be necessary (e.g. #97) - static volatile ClassLoader classLoaderOverride = null; - private final Class serviceType; - private final Map> cache = new WeakHashMap>(); - - PriorityServiceLoader(Class serviceType) { - if (serviceType == null) throw new NullPointerException("Service type is ."); - this.serviceType = serviceType; - } - - @SuppressWarnings("unchecked") - public Iterator iterator() { - final ClassLoader classLoader = - classLoaderOverride == null ? Thread.currentThread().getContextClassLoader() : classLoaderOverride; - List services = cache.get(classLoader); - if (services == null) { - services = findServices(classLoader); - if (!isCachingDisabled()) cache.put(classLoader, services); - } - return services.iterator(); - } - - void replaceInCache(SVC current, SVC replacement) { - final ClassLoader classLoader = - classLoaderOverride == null ? Thread.currentThread().getContextClassLoader() : classLoaderOverride; - List services = cache.get(classLoader); - if (services != null) { - int idx = services.indexOf(current); - if (idx >= 0) { - ArrayList copy = new ArrayList(services); - copy.set(idx, replacement); - cache.put(classLoader, sortAndMakeUnmodifiable(copy)); - } - } - } - - /** - * Remove the cache so the next call to {@linkplain #iterator()} will attempt to load the objects again. - */ - void clearCache() { - cache.clear(); - } - - private static boolean isCachingDisabled() { - final String cachingProperty = System.getProperty(SYSTEMPROPERTY_CACHING, ENVIRONMENT_CACHING_VALUE); - return "0".equals(cachingProperty) || "false".equalsIgnoreCase(cachingProperty); - } - - private List findServices(ClassLoader classLoader) { - ArrayList found = new ArrayList(); - for (Iterator iterator = loadServices(serviceType, classLoader); iterator.hasNext(); ) { - SVC service = iterator.next(); - if (service != null) found.add(service); - } - return sortAndMakeUnmodifiable(found); - } - - private static List sortAndMakeUnmodifiable(ArrayList services) { - if (services.isEmpty()) return emptyList(); - else if (services.size() == 1) return singletonList(services.get(0)); - else if (PriorityComparator.PRIORITY_AVAILABLE) sort(services, PriorityComparator.INSTANCE); - services.trimToSize(); - return unmodifiableList(services); - } - - @SuppressWarnings("Since15") - private static Iterator loadServices(Class serviceType, ClassLoader classLoader) { - try { - return java.util.ServiceLoader.load(serviceType, classLoader).iterator(); - } catch (LinkageError le) { - LOGGER.log(Level.FINEST, "No ServiceLoader available, probably running on Java 1.5.", le); - return javax.imageio.spi.ServiceRegistry.lookupProviders(serviceType); - } catch (RuntimeException loadingException) { - LOGGER.log(Level.WARNING, "Unexpected error loading services of " + serviceType, loadingException); - return Collections.emptySet().iterator(); - } - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java deleted file mode 100644 index 1b35d13e..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObserver.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; - -/** - * Observe context updates for a particular class of {@linkplain ContextManager}. - * - *

    - * Create your context observer by implementing this interface - * and registering your class to the {@code ServiceLoader} - * SPI by adding the fully qualified class name to the resource - * {@code /META-INF/services/nl.talsmasoftware.context.observer.ContextObserver}. - * - *

    - * It is the responsibility of the context implementor to update observers of - * context updates. SPI lookup of appropriate observers is facilitated - * by the {@linkplain nl.talsmasoftware.context.ContextManagers#onActivate(Class, Object, Object)} - * and {@linkplain nl.talsmasoftware.context.ContextManagers#onDeactivate(Class, Object, Object)} - * utility methods.
    - * - * @author Sjoerd Talsma - * @deprecated Context observers will use simplified registration in v2. - */ -@Deprecated -public interface ContextObserver extends nl.talsmasoftware.context.api.ContextObserver { - - /** - * The observed context manager(s). - * - *

    - * Context observers can indicate which type of context manager must be observed using this method. - * For instance, returning {@code LocaleContextManager.class} here, updates for the {@code LocaleContext} will - * be offered to this observer. - * - *

    - * To observe all context updates, return the {@linkplain ContextManager} interface class itself, - * since all context managers must implement it. - * - *

    - * Return {@code null} to disable the observer. - * - * @return The observed context manager class or {@code null} to disable this observer. - * @deprecated This method will be removed. Observers must explicitly be registered at {@code ContextManagers} class. - */ - @Deprecated - Class> getObservedContextManager(); - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObservers.java b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObservers.java deleted file mode 100644 index f25506d5..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/ContextObservers.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.observer; - -import nl.talsmasoftware.context.ContextManager; -import nl.talsmasoftware.context.ContextManagers; - -/** - * Utility class to assist Context implementors. - *

    - * It implements the SPI behaviour, locating appropriate {@linkplain ContextObserver} - * implementations to be notified of {@linkplain #onActivate(Class, Object, Object) activate} - * and {@linkplain #onDeactivate(Class, Object, Object) deactivate} occurrances. - * - * @author Sjoerd Talsma - * @see nl.talsmasoftware.context.core.ContextManagers#registerContextObserver(nl.talsmasoftware.context.api.ContextObserver, Class) - * @see nl.talsmasoftware.context.core.ContextManagers#unregisterContextObserver(nl.talsmasoftware.context.api.ContextObserver) - * @deprecated Replaced by explicit ContextManager registration. - */ -@Deprecated -public final class ContextObservers { - - /** - * Private constructor to avoid instantiation of this class. - */ - private ContextObservers() { - throw new UnsupportedOperationException(); - } - - /** - * Notifies all {@linkplain ContextObserver context observers} for the specified {@code contextManager} - * about the activated context value. - * - * @param contextManager The context manager type that activated the context (required to observe). - * @param activatedContextValue The activated context value or {@code null} if no value was activated. - * @param previousContextValue The previous context value or {@code null} if unknown or unsupported. - * @param The type managed by the context manager. - * @see ContextManagers#onActivate(Class, Object, Object) - * @deprecated This method was moved to the {@code ContextManagers} utility class. - */ - @Deprecated - public static void onActivate(Class> contextManager, - T activatedContextValue, - T previousContextValue) { - ContextManagers.onActivate(contextManager, activatedContextValue, previousContextValue); - } - - /** - * Notifies all {@linkplain ContextObserver context observers} for the specified {@code contextManager} - * about the deactivated context value. - * - * @param contextManager The context manager type that deactivated the context (required to observe). - * @param deactivatedContextValue The deactivated context value - * @param restoredContextValue The restored context value or {@code null} if unknown or unsupported. - * @param The type managed by the context manager. - * @see ContextManagers#onDeactivate(Class, Object, Object) - * @deprecated This method was moved to the {@code ContextManagers} utility class. - */ - @Deprecated - public static void onDeactivate(Class> contextManager, - T deactivatedContextValue, - T restoredContextValue) { - ContextManagers.onDeactivate(contextManager, deactivatedContextValue, restoredContextValue); - } - -} diff --git a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java b/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java deleted file mode 100644 index ab3cc7b4..00000000 --- a/context-propagation/src/main/java/nl/talsmasoftware/context/observer/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Observe context changes - * - *

    {@linkplain nl.talsmasoftware.context.observer.ContextObserver}

    - *

    - * Interface that can be implemented to observe context changes. - * - *

    - * Each call to {@linkplain nl.talsmasoftware.context.ContextManager#initializeNewContext(java.lang.Object)} or - * {@linkplain nl.talsmasoftware.context.api.Context#close()} is sent to all relevant context observers. - * - *

    - * Each observer must specify which context manager is being observed by implementing the - * {@linkplain nl.talsmasoftware.context.observer.ContextObserver#getObservedContextManager()} method. - * Context observers are looked up by java's {@code ServiceLoader}. - */ -package nl.talsmasoftware.context.observer; diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/Priorities.java b/context-propagation/src/test/java/nl/talsmasoftware/context/Priorities.java deleted file mode 100644 index 29b14cd6..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/Priorities.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import javax.annotation.Priority; - -public final class Priorities { - public static final Object minus5 = new Minus5(); - public static final Object minus3 = new Minus3(); - public static final Object zero = new Zero(); - public static final Object one = new One(); - public static final Object inheritedOne = new InheritedOne(); - public static final Object two = new Two(); - public static final Object noPriority = new NoPriority(); - - @Priority(-5) - public static class Minus5 { - } - - @Priority(-3) - public static class Minus3 { - } - - @Priority(0) - public static class Zero { - } - - @Priority(1) - public static class One { - } - - public static class InheritedOne extends One { - } - - @Priority(2) - public static class Two { - } - - public static class NoPriority { - } - -} diff --git a/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityComparatorTest.java b/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityComparatorTest.java deleted file mode 100644 index e1534321..00000000 --- a/context-propagation/src/test/java/nl/talsmasoftware/context/PriorityComparatorTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context; - -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.List; - -import static java.util.Arrays.asList; -import static nl.talsmasoftware.context.Priorities.inheritedOne; -import static nl.talsmasoftware.context.Priorities.minus3; -import static nl.talsmasoftware.context.Priorities.minus5; -import static nl.talsmasoftware.context.Priorities.noPriority; -import static nl.talsmasoftware.context.Priorities.two; -import static nl.talsmasoftware.context.Priorities.zero; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; - -public class PriorityComparatorTest { - - @Test - public void testPrioritize() { - List objects = asList(two, minus5, noPriority, zero, minus3, inheritedOne, zero, two); - Collections.sort(objects, PriorityComparator.INSTANCE); - assertThat(objects, contains(zero, zero, inheritedOne, two, two, noPriority, minus3, minus5)); - } - -} diff --git a/locale-context/pom.xml b/locale-context/pom.xml index 2d284d32..39bd342a 100644 --- a/locale-context/pom.xml +++ b/locale-context/pom.xml @@ -21,7 +21,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -39,7 +39,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/log4j2-propagation/pom.xml b/log4j2-propagation/pom.xml index 5d467776..fd0e4422 100644 --- a/log4j2-propagation/pom.xml +++ b/log4j2-propagation/pom.xml @@ -21,7 +21,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -38,7 +38,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/opentracing-span-propagation/pom.xml b/opentracing-span-propagation/pom.xml index d5b074dd..bd48a94f 100644 --- a/opentracing-span-propagation/pom.xml +++ b/opentracing-span-propagation/pom.xml @@ -23,7 +23,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -41,7 +41,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java index ca5d41da..9299a666 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ import io.opentracing.mock.MockTracer; import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; -import nl.talsmasoftware.context.ContextManagers; +import nl.talsmasoftware.context.core.ContextManagers; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; diff --git a/pom.xml b/pom.xml index a85e4f8f..a6b71ca4 100644 --- a/pom.xml +++ b/pom.xml @@ -24,20 +24,20 @@ nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT pom - Context propagation + Context propagation (root) Standardized context propagation in concurrent systems. https://github.com/talsma-ict/context-propagation 2016 context-propagation-bom - context-propagation - context-propagation-java8 + context-propagation-api + context-propagation-core context-propagation-metrics context-propagation-micrometer locale-context @@ -154,7 +154,8 @@ ${maven-surefire-plugin.version} - ${project.build.testOutputDirectory}/logging.properties + ${project.build.testOutputDirectory}/logging.properties + @@ -238,7 +239,9 @@ - https://javadoc.io/page/${project.groupId}/context-propagation-root/${project.version} + + https://javadoc.io/page/${project.groupId}/context-propagation-root/${project.version} + ${root.basedir}/.mvn/javadoc @@ -246,11 +249,14 @@ ${root.basedir}/.mvn/javadoc/opentracing-api - https://javadoc.io/page/io.opentracing/opentracing-util/${opentracing-api.version} + https://javadoc.io/page/io.opentracing/opentracing-util/${opentracing-api.version} + ${root.basedir}/.mvn/javadoc/opentracing-util - https://javadoc.io/page/org.springframework.security/spring-security-core/${spring-security.version} + + https://javadoc.io/page/org.springframework.security/spring-security-core/${spring-security.version} + ${root.basedir}/.mvn/javadoc/spring-security-core diff --git a/servletrequest-propagation/pom.xml b/servletrequest-propagation/pom.xml index 672df092..6f5bc09a 100644 --- a/servletrequest-propagation/pom.xml +++ b/servletrequest-propagation/pom.xml @@ -23,7 +23,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -41,7 +41,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/slf4j-propagation/pom.xml b/slf4j-propagation/pom.xml index e930e746..0af97147 100644 --- a/slf4j-propagation/pom.xml +++ b/slf4j-propagation/pom.xml @@ -21,7 +21,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -39,7 +39,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} diff --git a/spring-security-context/pom.xml b/spring-security-context/pom.xml index 8a6f2914..96d23f03 100644 --- a/spring-security-context/pom.xml +++ b/spring-security-context/pom.xml @@ -21,7 +21,7 @@ 4.0.0 nl.talsmasoftware.context - context-propagation-root + context-propagation 2.0.0-SNAPSHOT @@ -40,7 +40,7 @@ ${project.groupId} - context-propagation + context-propagation-api ${project.version} From 37f254d52ea896de77ca9c2a3a94449977f3ad9e Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 14:38:53 +0100 Subject: [PATCH 19/41] Remove relocated executors package. Signed-off-by: Sjoerd Talsma --- .../ContextAwareExecutorService.java | 52 ------------------- .../context/executors/package-info.java | 31 ----------- .../ContextAwareExecutorServiceTest.java | 7 +-- 3 files changed, 2 insertions(+), 88 deletions(-) delete mode 100644 context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java delete mode 100644 context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java deleted file mode 100644 index 23b649c5..00000000 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/ContextAwareExecutorService.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.executors; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; - -/** - * Executor service that wraps another executor service, making sure background tasks operates 'within' - * a context snapshot taken from the submitting thread. - * - *

    - * The executor service will make sure to close the reactivated snapshot again after the code in the task is finished, - * even if it throws an exception. - * - *

    - * Both {@link Callable} and {@link Runnable} tasks are mapped. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.concurrent}. - */ -public class ContextAwareExecutorService extends nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService { - public ContextAwareExecutorService(ExecutorService delegate) { - super(delegate); - } - - /** - * This method maps any callable (before scheduling it) by taking a snapshot of the context in the scheduling thread - * and propagating this context into the executed callable by snapshot reactivation. - * - * @param callable The callable to be mapped. - * @param the actual return type of the callable object being scheduled. - * @return A callable that will reactivate the scheduling thread context snapshot before executing. - */ - @Override - protected Callable map(final Callable callable) { - return super.map(callable); - } -} diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java deleted file mode 100644 index 1d9d6bb5..00000000 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/executors/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Package for context aware executors. - * - *

    {@linkplain nl.talsmasoftware.context.executors.ContextAwareExecutorService}

    - *

    - * Executor service that wraps another {@linkplain java.util.concurrent.ExecutorService}, - * making sure the background task operates 'within' a context snapshot taken from the submitting thread. - * - *

    - * The executor service will make sure to close the reactivated snapshot again after the code in the task is finished, - * even if it throws an exception. - * - *

    - * Both {@link java.util.concurrent.Callable} and {@link java.lang.Runnable} tasks are mapped. - */ -package nl.talsmasoftware.context.executors; \ No newline at end of file diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java index 89868ac0..cf15f253 100644 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java +++ b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java @@ -18,7 +18,6 @@ import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.dummy.DummyContextManager; import nl.talsmasoftware.context.dummy.ThrowingContextManager; -import nl.talsmasoftware.context.executors.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -94,10 +93,8 @@ public void testCloseException() throws InterruptedException { @Test public void testCallException() throws InterruptedException { - Future dummy = executor.submit(new Callable() { - public String call() { - throw new IllegalStateException("DOH!"); - } + Future dummy = executor.submit(() -> { + throw new IllegalStateException("DOH!"); }); try { From 9425d34e499a9330a54cad5705054679cd6d6765 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Wed, 6 Nov 2024 16:37:22 +0100 Subject: [PATCH 20/41] Binning the context observer. Possibly reintroduce a ContextSnapshot observer at some point. Signed-off-by: Sjoerd Talsma --- .../context/api/ContextObserver.java | 49 ---- .../context/core/ContextManagers.java | 221 ++++-------------- .../talsmasoftware/context/core/Timers.java | 26 +-- .../AutoInitializingContextManager.java | 70 ------ .../ClearableContextManagerTest.java | 1 - .../context/core/ContextManagersTest.java | 7 +- ....talsmasoftware.context.api.ContextManager | 1 - .../opentracing/ContextScopeManager.java | 22 +- .../ContextScopeManagerObserver.java | 103 -------- .../opentracing/ContextScopeManagerTest.java | 93 +++----- 10 files changed, 86 insertions(+), 507 deletions(-) delete mode 100644 context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java delete mode 100644 context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java delete mode 100644 opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java deleted file mode 100644 index 6a1feab6..00000000 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextObserver.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.api; - -/** - * Observe context updates for a particular {@linkplain ContextManager}. - * - *

    - * Context observers can be registered / unregistered with the {@code ContextManagers} class. - * - *

    - * Implementation note: A correct {@link Object#equals(Object)} implementation is required - * for reliable registration functionality. - * - * @author Sjoerd Talsma - * @since 1.1.0 - */ -public interface ContextObserver { - - /** - * Indicates that a context was just activated. - * - * @param activatedContextValue The now active context value. - * @param previousContextValue The previous context value or {@code null} if unknown or unsupported. - */ - void onActivate(T activatedContextValue, T previousContextValue); - - /** - * Indicates that a context was just deactivated. - * - * @param deactivatedContextValue The deactivated context value. - * @param restoredContextValue The now active restored context value or {@code null} if unknown or unsupported. - */ - void onDeactivate(T deactivatedContextValue, T restoredContextValue); - -} diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index f5a54701..99c6d87d 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -17,18 +17,15 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; -import nl.talsmasoftware.context.api.ContextObserver; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; -import nl.talsmasoftware.context.core.delegation.Wrapper; +import nl.talsmasoftware.context.api.ContextTimer; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; +import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.ServiceLoader; -import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; @@ -46,17 +43,15 @@ public final class ContextManagers { private static final Logger LOGGER = Logger.getLogger(ContextManagers.class.getName()); - /** - * Registered observers. - */ - private static final CopyOnWriteArrayList OBSERVERS = - new CopyOnWriteArrayList<>(); - /** * Sometimes a single, fixed classloader may be necessary (e.g. #97) */ private static volatile ClassLoader classLoaderOverride = null; + private static volatile List> contextManagers = null; + + private static volatile List contextTimers = null; + /** * Private constructor to avoid instantiation of this class. */ @@ -140,6 +135,7 @@ public static void clearActiveContexts() { Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear"); } catch (RuntimeException rte) { LOGGER.log(Level.WARNING, "Exception clearing active context from " + manager + ".", rte); + contextManagers = null; Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear.exception"); } } @@ -150,77 +146,6 @@ public static void clearActiveContexts() { Timers.timed(System.nanoTime() - start, ContextManagers.class, "clearActiveContexts"); } - /** - * Register an observer for contexts managed by the specified ContextManager type. - * - * @param contextObserver The observer to register. - * @param observedContextManagerType The context manager type to observe. - * @param Type of the value in the context. - * @return {@code true} if the observer was registered. - * @since 1.1.0 - */ - public static boolean registerContextObserver(ContextObserver contextObserver, Class> observedContextManagerType) { - if (contextObserver == null) { - throw new NullPointerException("Context observer must not be null."); - } else if (observedContextManagerType == null) { - throw new NullPointerException("Observed ContextManager type must not be null."); - } - - // Find ContextManager to register. - ObservableContextManager observableContextManager = null; - ContextManager contextManager = null; - for (ContextManager manager : getContextManagers()) { - if (manager instanceof ObservableContextManager - && ((ObservableContextManager) manager).observes(observedContextManagerType)) { - observableContextManager = (ObservableContextManager) manager; - break; - } else if (observedContextManagerType.isInstance(manager)) { - contextManager = (ContextManager) manager; - break; - } - } - if (observableContextManager == null && contextManager == null) { - LOGGER.warning("Trying to register observer to missing ContextManager type: " + observedContextManagerType + "."); - return false; - } - - if (observableContextManager == null) { - // Register new observer by wrapping the context manager. - ObservableContextManager newObserver = new ObservableContextManager(contextManager, (List) Arrays.asList(contextObserver)); - if (OBSERVERS.addIfAbsent(newObserver)) { - return true; - } - - // There is already an existing ObservableContextManager, add the observer to it. - observableContextManager = OBSERVERS.get(OBSERVERS.indexOf(newObserver)); - } - - // Add the context observer to the existing observable context manager. - synchronized (observableContextManager) { - return observableContextManager.observers.addIfAbsent(contextObserver); - } - } - - /** - * Unregister an observer for any context. - * - * @param contextObserver The previously registered context observer. - * @return {@code true} if the observer was unregistered. - * @since 1.1.0 - */ - public static boolean unregisterContextObserver(ContextObserver contextObserver) { - boolean unregistered = false; - for (ObservableContextManager observer : OBSERVERS) { - unregistered |= observer.observers.remove(contextObserver); - synchronized (observer) { - if (observer.observers.isEmpty()) { - OBSERVERS.remove(observer); - } - } - } - return unregistered; - } - /** * Override the {@linkplain ClassLoader} used to lookup {@linkplain ContextManager contextmanagers}. *

    @@ -235,7 +160,7 @@ public static boolean unregisterContextObserver(ContextObserver contextObserv *

      *
    • Please be aware that this configuration is global! *
    • This will also affect the lookup of - * {@linkplain nl.talsmasoftware.context.api.ContextObserver context observers} + * {@linkplain nl.talsmasoftware.context.api.ContextTimer context timers} *
    * * @param classLoader The single, fixed ClassLoader to use for finding context managers. @@ -249,45 +174,49 @@ public static synchronized void useClassLoader(ClassLoader classLoader) { } LOGGER.fine(() -> "Updating classloader override to " + classLoader + " (was: " + classLoaderOverride + ")"); classLoaderOverride = classLoader; + contextManagers = null; + contextTimers = null; } - private static Iterable getContextManagers() { - // TODO change to stream implementation when java 8 - final Iterable resolved = classLoaderOverride == null ? ServiceLoader.load(ContextManager.class) - : ServiceLoader.load(ContextManager.class, classLoaderOverride); - return OBSERVERS.isEmpty() ? resolved : new Iterable() { - public Iterator iterator() { - return new Iterator() { - private final Iterator delegate = resolved.iterator(); - - public boolean hasNext() { - return delegate.hasNext(); - } - - public ContextManager next() { - ContextManager contextManager = delegate.next(); - if (!(contextManager instanceof ObservableContextManager)) { - for (ObservableContextManager observableContextManager : OBSERVERS) { - if (observableContextManager.isWrapperOf(contextManager)) { - return observableContextManager; - } - } - } - return contextManager; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + private static List> getContextManagers() { + if (contextManagers == null) { + synchronized (ContextManagers.class) { + if (contextManagers == null) { + contextManagers = (List) load(ContextManager.class); + } + } + } + return contextManagers; + } - public void remove() { - delegate.remove(); - } - }; + static List getContextTimers() { + if (contextTimers == null) { + synchronized (ContextManagers.class) { + if (contextTimers == null) { + contextTimers = load(ContextTimer.class); + } } - }; + } + return contextTimers; + } + + private static List load(Class type) { + ArrayList list = new ArrayList<>(); + if (classLoaderOverride == null) { + ServiceLoader.load(type).forEach(list::add); + } else { + ServiceLoader.load(type, classLoaderOverride).forEach(list::add); + } + list.trimToSize(); + return Collections.unmodifiableList(list); } /** * Implementation of the createContextSnapshot functionality that can reactivate all values from the * snapshot in each corresponding {@link ContextManager}. */ + @SuppressWarnings("rawtypes") private static final class ContextSnapshotImpl implements nl.talsmasoftware.context.api.ContextSnapshot { private static final ContextManager[] MANAGER_ARRAY = new ContextManager[0]; private final ContextManager[] managers; @@ -320,6 +249,7 @@ public Reactivation reactivate() { reactivationException.addSuppressed(rte); } } + contextManagers = null; throw reactivationException; } } @@ -374,73 +304,6 @@ public String toString() { } } - private static final class ObservableContextManager extends Wrapper> implements ContextManager { - private final CopyOnWriteArrayList> observers; - - private ObservableContextManager(ContextManager delegate, List> observers) { - super(delegate); - this.observers = new CopyOnWriteArrayList<>(observers); - } - - private boolean observes(Class> contextManagerType) { - return contextManagerType.isInstance(delegate()); - } - - @Override - public T getActiveContextValue() { - return delegate().getActiveContextValue(); - } - - @Override - public void clear() { - delegate().clear(); - } - - private void notifyActivated(T newValue, T oldValue) { - for (ContextObserver observer : observers) { - try { - observer.onActivate(newValue, oldValue); - } catch (RuntimeException observerError) { - LOGGER.log(Level.SEVERE, "Error in observer.onActivate of " + observer, observerError); - } - } - } - - private void notifyDeactivated(T deactivatedValue, T restoredValue) { - for (ContextObserver observer : observers) { - try { - observer.onDeactivate(deactivatedValue, restoredValue); - } catch (RuntimeException observerError) { - LOGGER.log(Level.SEVERE, "Error in observer.onActivate of " + observer, observerError); - } - } - } - - @Override - public Context initializeNewContext(final T newValue) { - final T oldValue = getActiveContextValue(); - final Context context = delegate().initializeNewContext(newValue); - notifyActivated(newValue, oldValue); - - return new Context() { - public T getValue() { - return context.getValue(); - } - - public void close() { - T deactivated = context.getValue(); // get before closing! - context.close(); - notifyDeactivated(deactivated, getActiveContextValue()); - } - }; - } - - @Override - public String toString() { - return getClass().getSimpleName() + '{' + delegate() + ", " + observers + '}'; - } - } - /** * Exception that we don't actually throw, but it helps track the issue if we log it including the stacktrace. */ diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java index 34ba48e1..4b4da233 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java @@ -17,39 +17,15 @@ import nl.talsmasoftware.context.api.ContextTimer; -import java.util.ArrayList; -import java.util.List; -import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -/** - * Singleton initialized to look up all {@link ContextTimer} delegates. - * - * @author Sjoerd Talsma - */ final class Timers { private static final Logger TIMING_LOGGER = Logger.getLogger(Timers.class.getName()); - /** - * Singleton containing resolved ContextTimer delegates. - */ - private enum Singleton { - INSTANCE; - private final ContextTimer[] delegates; - - Singleton() { - List delegates = new ArrayList(); - for (ContextTimer delegate : ServiceLoader.load(ContextTimer.class)) { - delegates.add(delegate); - } - this.delegates = delegates.toArray(new ContextTimer[0]); - } - } - static void timed(long durationNanos, Class type, String method) { - for (ContextTimer delegate : Singleton.INSTANCE.delegates) { + for (ContextTimer delegate : ContextManagers.getContextTimers()) { delegate.update(type, method, durationNanos, TimeUnit.NANOSECONDS); } if (TIMING_LOGGER.isLoggable(Level.FINEST)) { diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java deleted file mode 100644 index cbe94a62..00000000 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/AutoInitializingContextManager.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.clearable; - -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.api.ContextManager; - -public class AutoInitializingContextManager implements ContextManager { - private static final ThreadLocal CTX = new ThreadLocal() { - @Override - protected DummyContext initialValue() { - return new DummyContext(null, null); - } - }; - - @Override - public Context initializeNewContext(String value) { - CTX.set(new DummyContext(CTX.get(), value)); - return CTX.get(); - } - - @Override - public String getActiveContextValue() { - DummyContext dummyContext = CTX.get(); - return dummyContext != null ? dummyContext.getValue() : null; - } - - @Override - public void clear() { - CTX.remove(); - } - - private static class DummyContext implements Context { - private final DummyContext previous; - private String value; - - private DummyContext(DummyContext previous, String value) { - this.previous = previous; - this.value = value; - } - - public String getValue() { - return value; - } - - /** - * Only for testing! DO NOT COPY! This is not a safe implementation. - *

    - * Please see AbstractThreadLocalContext for reference code if you wish manage a stack of contexts! - */ - public void close() { - if (previous == null) CTX.remove(); - else CTX.set(previous); - this.value = null; - } - } -} diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java index 2278696c..5f335690 100644 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java +++ b/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java @@ -32,7 +32,6 @@ */ public class ClearableContextManagerTest { private static ContextManager CLEARABLE = new ClearableDummyContextManager(); - private static ContextManager AUTO_INITIALIZING = new AutoInitializingContextManager(); @Test public void testClearActiveContexts_byManager() { diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index 3d6c76c4..01a42f5b 100644 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java +++ b/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -215,13 +215,14 @@ public void testConcurrentSnapshots_fixedClassLoader() throws ExecutionException int threadcount = 25; ExecutorService threadpool = Executors.newFixedThreadPool(threadcount); try { - List> snapshots = new ArrayList<>(threadcount); + Future[] snapshots = new Future[threadcount]; for (int i = 0; i < threadcount; i++) { - snapshots.add(threadpool.submit(ContextManagers::createContextSnapshot)); + snapshots[i] = threadpool.submit(ContextManagers::createContextSnapshot); } for (int i = 0; i < threadcount; i++) { - assertThat(snapshots.get(i).get(), is(notNullValue())); + assertThat("Future " + i, snapshots[i], notNullValue()); + assertThat("Snapshot " + i, snapshots[i].get(), notNullValue()); } } finally { threadpool.shutdown(); diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager index bdc96303..6f9a5447 100644 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -1,4 +1,3 @@ nl.talsmasoftware.context.dummy.DummyContextManager nl.talsmasoftware.context.dummy.ThrowingContextManager -nl.talsmasoftware.context.clearable.AutoInitializingContextManager nl.talsmasoftware.context.clearable.ClearableDummyContextManager diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java index c0344cb4..cba515be 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java +++ b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java @@ -39,8 +39,6 @@ *

  • More predictable behaviour for out-of-order closing of scopes. * Although this is explicitly unsupported by the opentracing specification, * we think having consistent and predictable behaviour is an advantage. - *
  • Support for {@link nl.talsmasoftware.context.api.ContextObserver}. - * See https://github.com/opentracing/opentracing-java/issues/334 explicitly wanting this. * * *

    @@ -63,8 +61,7 @@ public Scope activate(Span span) { @Override public Span activeSpan() { - Context current = ThreadLocalSpanContext.current(); - return current == null ? null : current.getValue(); + return ThreadLocalSpanContext.currentSpan(); } /** @@ -75,8 +72,9 @@ public Span activeSpan() { * @see #activate(Span) */ @Override + @SuppressWarnings("unchecked") public Context initializeNewContext(Span value) { - return new ThreadLocalSpanContext(value); + return (Context) activate(value); } @Override @@ -86,7 +84,7 @@ public Span getActiveContextValue() { @Override public void clear() { - ThreadLocalSpanContext.removeThreadLocal(); + ThreadLocalSpanContext.remove(); } /** @@ -97,16 +95,20 @@ public String toString() { } private static final class ThreadLocalSpanContext extends AbstractThreadLocalContext implements Scope { + private static final ThreadLocal SPAN_CONTEXT = + AbstractThreadLocalContext.threadLocalInstanceOf(ThreadLocalSpanContext.class); + private ThreadLocalSpanContext(Span newValue) { super(newValue); } - private static ThreadLocalSpanContext current() { - return current(ThreadLocalSpanContext.class); + private static Span currentSpan() { + ThreadLocalSpanContext current = SPAN_CONTEXT.get(); + return current != null ? current.getValue() : null; } - private static void removeThreadLocal() { - threadLocalInstanceOf(ThreadLocalSpanContext.class).remove(); + private static void remove() { + SPAN_CONTEXT.remove(); } } } diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java deleted file mode 100644 index 99b52886..00000000 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerObserver.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.opentracing; - -import io.opentracing.Span; -import io.opentracing.mock.MockSpan; -import nl.talsmasoftware.context.api.ContextObserver; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import java.util.ArrayList; -import java.util.List; - -import static java.util.Collections.synchronizedList; - -public class ContextScopeManagerObserver implements ContextObserver { - static final List observed = synchronizedList(new ArrayList<>()); - - @Override - public void onActivate(Span activatedContextValue, Span previousContextValue) { - observed.add(new Event(Event.Type.ACTIVATE, activatedContextValue)); - } - - @Override - public void onDeactivate(Span deactivatedContextValue, Span restoredContextValue) { - observed.add(new Event(Event.Type.DEACTIVATE, deactivatedContextValue)); - } - - static class Event { - enum Type {ACTIVATE, DEACTIVATE} - - final Thread thread; - final Type type; - final Span value; - - Event(Type type, Span value) { - this.thread = Thread.currentThread(); - this.type = type; - this.value = value; - } - - @Override - public String toString() { - return "Event{" + type + ", thread=" + thread.getName() + ", span=" + value + '}'; - } - } - - static class EventMatcher extends BaseMatcher { - Thread inThread; - Event.Type type; - Matcher spanMatcher; - - private EventMatcher(Event.Type type, Matcher spanMatcher) { - this.type = type; - this.spanMatcher = spanMatcher; - } - - static EventMatcher activated(Matcher span) { - return new EventMatcher(Event.Type.ACTIVATE, span); - } - - static EventMatcher deactivated(Matcher span) { - return new EventMatcher(Event.Type.DEACTIVATE, span); - } - - EventMatcher inThread(Thread thread) { - EventMatcher copy = new EventMatcher(type, spanMatcher); - copy.inThread = thread; - return copy; - } - - @Override - public boolean matches(Object actual) { - if (!(actual instanceof Event)) return actual == null; - Event actualEv = (Event) actual; - return (inThread == null || inThread.equals(actualEv.thread)) - && type.equals(actualEv.type) - && spanMatcher.matches(actualEv.value); - } - - @Override - public void describeTo(Description description) { - description.appendText("Event "); - if (inThread != null) description.appendText("in thread ").appendText(inThread.getName()); - description.appendValue(type).appendText(" "); - spanMatcher.describeTo(description); - } - } -} diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java index 6b6ff9cc..b311ab72 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java @@ -23,9 +23,7 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -37,35 +35,18 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static nl.talsmasoftware.context.opentracing.ContextScopeManagerObserver.EventMatcher.activated; -import static nl.talsmasoftware.context.opentracing.ContextScopeManagerObserver.EventMatcher.deactivated; -import static nl.talsmasoftware.context.opentracing.MockSpanMatcher.withOperationName; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.fail; public class ContextScopeManagerTest { - static ContextScopeManagerObserver observer = new ContextScopeManagerObserver(); MockTracer mockTracer; ContextScopeManager scopeManager; ExecutorService threadpool; - @BeforeAll - static void registerObserver() { - ContextManagers.registerContextObserver(observer, ContextScopeManager.class); - } - - @AfterAll - static void unregisterObserver() { - ContextManagers.unregisterContextObserver(observer); - } - @BeforeEach public void registerMockGlobalTracer() { GlobalTracerTestUtil.resetGlobalTracer(); @@ -80,26 +61,6 @@ public void cleanup() { threadpool.shutdown(); ContextManagers.clearActiveContexts(); GlobalTracerTestUtil.resetGlobalTracer(); - ContextScopeManagerObserver.observed.clear(); - } - - @Test - @Disabled("TODO replace observer by MockTracer .finishedSpans inspection!") - public void testObservedSpans() { - assertThat(ContextScopeManagerObserver.observed, is(empty())); - Span parentSpan = GlobalTracer.get().buildSpan("parent").start(); - Scope parent = GlobalTracer.get().activateSpan(parentSpan); - Span innerSpan = GlobalTracer.get().buildSpan("inner").start(); - Scope inner = GlobalTracer.get().activateSpan(innerSpan); - inner.close(); - parent.close(); - - assertThat(ContextScopeManagerObserver.observed, contains( - activated(withOperationName("parent")), - activated(withOperationName("inner")), - deactivated(withOperationName("inner")), - deactivated(withOperationName("parent")) - )); } @Test @@ -123,9 +84,9 @@ public void run() { } }); } - assertThat(ContextScopeManagerObserver.observed, contains( - activated(withOperationName("parent")) - )); +// assertThat(ContextScopeManagerObserver.observed, contains( +// activated(withOperationName("parent")) +// )); assertThat(GlobalTracer.get().activeSpan(), equalTo(parentSpan)); for (Thread t : threads) t.start(); @@ -133,30 +94,30 @@ public void run() { parentSpan.finish(); parent.close(); assertThat(GlobalTracer.get().activeSpan(), is(nullValue())); - assertThat(ContextScopeManagerObserver.observed, contains( - activated(withOperationName("parent")), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - activated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName(startsWith("inner"))), - deactivated(withOperationName("parent")) - )); +// assertThat(ContextScopeManagerObserver.observed, contains( +// activated(withOperationName("parent")), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// activated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName(startsWith("inner"))), +// deactivated(withOperationName("parent")) +// )); } @Test From c2d96f2bc7e056999f47e0dc17fbe1ac1f505ca5 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 10:27:25 +0100 Subject: [PATCH 21/41] Restructuring into context-propagation-api / context-propagation-core modules. Signed-off-by: Sjoerd Talsma --- context-propagation-api/pom.xml | 2 +- .../context/api/package-info.java | 53 + .../context/dummy/DummyContextManager.java | 54 - ...LoaderTest$ServiceWithSingleImplementation | 1 - ...text.PriorityServiceLoaderTest$TestService | 3 - ....talsmasoftware.context.api.ContextManager | 3 - ...LoaderTest$ServiceWithSingleImplementation | 1 - ...core.PriorityServiceLoaderTest$TestService | 3 - .../src/test/resources/logging.properties | 2 - .../context/core/ContextManagers.java | 0 .../talsmasoftware/context/core/Timers.java | 0 .../ContextAwareCompletableFuture.java | 12 +- .../ContextAwareExecutorService.java | 0 .../CallMappingExecutorService.java | 0 .../core/delegation/CallableToRunnable.java | 0 .../delegation/DelegatingExecutorService.java | 0 .../core/delegation/DelegatingFuture.java | 0 .../context/core/delegation/Wrapper.java | 0 .../core/delegation/WrapperWithContext.java | 0 .../context/core/delegation/package-info.java | 0 .../context/core/function/package-info.java | 39 + .../context/core}/package-info.java | 4 +- .../AbstractThreadLocalContext.java | 0 .../functions/BiConsumerWithContext.java | 44 - .../functions/BiFunctionWithContext.java | 46 - .../functions/BiPredicateWithContext.java | 44 - .../functions/BinaryOperatorWithContext.java | 46 - .../functions/BooleanSupplierWithContext.java | 46 - .../functions/ConsumerWithContext.java | 45 - .../functions/FunctionWithContext.java | 46 - .../functions/PredicateWithContext.java | 46 - .../functions/RunnableWithContext.java | 70 - .../functions/SupplierWithContext.java | 45 - .../functions/UnaryOperatorWithContext.java | 45 - .../WrapperWithContextAndConsumer.java | 73 - .../context/functions/package-info.java | 39 - .../ContextAwareCompletableFuture.java | 803 -------- .../futures/ContextSnapshotHolder.java | 69 - .../context/futures/package-info.java | 25 - .../ClearableContextManagerTest.java | 0 .../ClearableDummyContextManager.java | 0 .../context/core/ContextManagersTest.java | 50 +- .../context/core/ContextSnapshotTest.java | 0 .../context/core/NoContextManagersTest.java | 0 .../context/core/TimersTest.java | 0 .../ContextAwareCompletableFutureTest.java | 730 ++++--- .../ContextAwareExecutorServiceTest.java | 0 .../ContextSnapshotHolderTest.java | 2 +- .../concurrent}/FailedFutureTest.java | 2 +- .../delegation/CallableToRunnableTest.java | 0 .../DelegatingExecutorServiceTest.java | 0 .../core/delegation/DelegatingFutureTest.java | 0 .../MappingExecutorServiceTest.java | 0 .../context/core/delegation/WrapperTest.java | 0 .../delegation/WrapperWithContextTest.java | 0 .../function/BiConsumerWithContextTest.java | 18 +- .../function}/BiFunctionWithContextTest.java | 14 +- .../function}/BiPredicateWithContextTest.java | 14 +- .../BinaryOperatorWithContextTest.java | 15 +- .../BooleanSupplierWithContextTest.java | 14 +- .../function/ConsumerWithContextTest.java | 18 +- .../function}/FunctionWithContextTest.java | 14 +- .../function}/PredicateWithContextTest.java | 14 +- .../function}/RunnableWithContextTest.java | 12 +- .../function}/SupplierWithContextTest.java | 20 +- .../UnaryOperatorWithContextTest.java | 14 +- .../WrapperWithContextAndConsumerTest.java | 12 +- .../context/dummy/DummyContext.java | 6 +- .../context/dummy/DummyContextManager.java | 58 +- .../context/dummy/ThrowingContextManager.java | 0 .../ContextAwareCompletableFutureTest.java | 1831 ----------------- ....talsmasoftware.context.api.ContextManager | 2 + ...nl.talsmasoftware.context.api.ContextTimer | 0 context-propagation-metrics/pom.xml | 7 + context-propagation-micrometer/pom.xml | 7 + locale-context/pom.xml | 5 +- log4j2-propagation/pom.xml | 8 +- opentracing-span-propagation/pom.xml | 3 +- servletrequest-propagation/pom.xml | 8 + .../servletrequest/ServletRequestContext.java | 38 +- slf4j-propagation/pom.xml | 10 +- .../context/slf4j/mdc/Slf4jMdcManager.java | 3 +- spring-security-context/pom.xml | 10 +- 83 files changed, 760 insertions(+), 3908 deletions(-) create mode 100644 context-propagation-api/src/main/java/nl/talsmasoftware/context/api/package-info.java delete mode 100644 context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java delete mode 100644 context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation delete mode 100644 context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService delete mode 100644 context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager delete mode 100644 context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation delete mode 100644 context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService delete mode 100644 context-propagation-api/src/test/resources/logging.properties rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/Timers.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java (100%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java (100%) create mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/package-info.java rename {context-propagation-api/src/main/java/nl/talsmasoftware/context => context-propagation-core/src/main/java/nl/talsmasoftware/context/core}/package-info.java (95%) rename {context-propagation-api => context-propagation-core}/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java (100%) delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java delete mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java (79%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/TimersTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java (100%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{futures => core/concurrent}/ContextSnapshotHolderTest.java (97%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{futures => core/concurrent}/FailedFutureTest.java (98%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java (100%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java (100%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/BiFunctionWithContextTest.java (92%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/BiPredicateWithContextTest.java (94%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/BinaryOperatorWithContextTest.java (92%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/FunctionWithContextTest.java (93%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/PredicateWithContextTest.java (94%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/RunnableWithContextTest.java (91%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/SupplierWithContextTest.java (81%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/UnaryOperatorWithContextTest.java (90%) rename context-propagation-core/src/test/java/nl/talsmasoftware/context/{functions => core/function}/WrapperWithContextAndConsumerTest.java (84%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java (90%) rename {context-propagation-api => context-propagation-core}/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java (100%) delete mode 100644 context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java rename {context-propagation-api => context-propagation-core}/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer (100%) diff --git a/context-propagation-api/pom.xml b/context-propagation-api/pom.xml index eafc938f..5c764ab8 100644 --- a/context-propagation-api/pom.xml +++ b/context-propagation-api/pom.xml @@ -28,7 +28,7 @@ context-propagation-api - Context propagation (API) + Context propagation (api) jar diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/package-info.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/package-info.java new file mode 100644 index 00000000..52ad1d0d --- /dev/null +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/package-info.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016-2024 Talsma ICT + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Main API concepts used throughout the {@code context-propagation} library. + * + *

    {@linkplain nl.talsmasoftware.context.api.Context}

    + *

    + * A {@linkplain nl.talsmasoftware.context.api.Context context} contains + * a {@linkplain nl.talsmasoftware.context.api.Context#getValue() value}.
    + * There can be one active context per thread. A context remains active until it is closed or another context + * is activated in that thread. + * + *

    + * An {@code AbstractThreadLocalContext} base class is provided in the core module that supports + * nested contexts and provides predictable behaviour for out-of-order closing. + * + *

    {@linkplain nl.talsmasoftware.context.api.ContextManager}

    + *

    + * Manages the active context. + * Can {@linkplain nl.talsmasoftware.context.api.ContextManager#initializeNewContext(java.lang.Object) initialize a new context} + * and provides access to + * the {@linkplain nl.talsmasoftware.context.api.ContextManager#getActiveContextValue() active context value}. + * + *

    + * For most application code it should not be necessary to interact with context managers directly. + * Instead, using the various context-aware utility classes will automatically propagate context values. + * + *

    {@linkplain nl.talsmasoftware.context.api.ContextSnapshot}

    + *

    + * A snapshot contains the current value from all known context managers.
    + * These values can be reactivated in another thread.
    + * Reactivated snapshots must be closed to avoid leaking context. + * + *

    + * All context aware utility classes in this library are tested + * to make sure they reactivate and close snapshots in a safe way. + * + * @author Sjoerd Talsma + */ +package nl.talsmasoftware.context.api; diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java b/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java deleted file mode 100644 index aa678ceb..00000000 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.dummy; - -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.api.ContextManager; - -/** - * Trivial manager around the {@link DummyContext} implementation to be registered as service provider. - * - * @author Sjoerd Talsma - */ -public class DummyContextManager implements ContextManager { - - public Context initializeNewContext(String value) { - return new DummyContext(value); - } - - public String getActiveContextValue() { - return DummyContext.currentValue(); - } - - public void clear() { - DummyContext.reset(); - } - - @Override - public int hashCode() { - return DummyContextManager.class.hashCode(); - } - - @Override - public boolean equals(Object other) { - return this == other || other instanceof DummyContextManager; - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } -} diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation deleted file mode 100644 index deec575e..00000000 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$ServiceWithSingleImplementation +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.PriorityServiceLoaderTest$SingleImplementationWithLowestPriority diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService deleted file mode 100644 index 58ca52ae..00000000 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.PriorityServiceLoaderTest$TestService +++ /dev/null @@ -1,3 +0,0 @@ -nl.talsmasoftware.context.PriorityServiceLoaderTest$LowestPrioImplementation -nl.talsmasoftware.context.PriorityServiceLoaderTest$HighestPrioImplementation -nl.talsmasoftware.context.PriorityServiceLoaderTest$ImplementationWithoutPriority \ No newline at end of file diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index 6f9a5447..00000000 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1,3 +0,0 @@ -nl.talsmasoftware.context.dummy.DummyContextManager -nl.talsmasoftware.context.dummy.ThrowingContextManager -nl.talsmasoftware.context.clearable.ClearableDummyContextManager diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation deleted file mode 100644 index 6b758b57..00000000 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ServiceWithSingleImplementation +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.core.PriorityServiceLoaderTest$SingleImplementationWithLowestPriority diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService b/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService deleted file mode 100644 index f359d3f7..00000000 --- a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.core.PriorityServiceLoaderTest$TestService +++ /dev/null @@ -1,3 +0,0 @@ -nl.talsmasoftware.context.core.PriorityServiceLoaderTest$LowestPrioImplementation -nl.talsmasoftware.context.core.PriorityServiceLoaderTest$HighestPrioImplementation -nl.talsmasoftware.context.core.PriorityServiceLoaderTest$ImplementationWithoutPriority diff --git a/context-propagation-api/src/test/resources/logging.properties b/context-propagation-api/src/test/resources/logging.properties deleted file mode 100644 index 4786544f..00000000 --- a/context-propagation-api/src/test/resources/logging.properties +++ /dev/null @@ -1,2 +0,0 @@ -# Use no logging by default during tests to keep the output as clean as possible. -.level=OFF diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/Timers.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java index 395297f1..ab89d60b 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFuture.java @@ -17,12 +17,12 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.functions.BiConsumerWithContext; -import nl.talsmasoftware.context.functions.BiFunctionWithContext; -import nl.talsmasoftware.context.functions.ConsumerWithContext; -import nl.talsmasoftware.context.functions.FunctionWithContext; -import nl.talsmasoftware.context.functions.RunnableWithContext; -import nl.talsmasoftware.context.functions.SupplierWithContext; +import nl.talsmasoftware.context.core.function.BiConsumerWithContext; +import nl.talsmasoftware.context.core.function.BiFunctionWithContext; +import nl.talsmasoftware.context.core.function.ConsumerWithContext; +import nl.talsmasoftware.context.core.function.FunctionWithContext; +import nl.talsmasoftware.context.core.function.RunnableWithContext; +import nl.talsmasoftware.context.core.function.SupplierWithContext; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorService.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/CallMappingExecutorService.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/CallableToRunnable.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorService.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/DelegatingFuture.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/Wrapper.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/WrapperWithContext.java diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/delegation/package-info.java diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/package-info.java new file mode 100644 index 00000000..36b8fb94 --- /dev/null +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/package-info.java @@ -0,0 +1,39 @@ +/* + * Copyright 2016-2024 Talsma ICT + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Functional interface wrappers that apply context snapshots to the mapped functions. + * + *

    + * The following functional interfaces are available: + *

      + *
    • {@link nl.talsmasoftware.context.core.function.BiConsumerWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.BiFunctionWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.BinaryOperatorWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.BiPredicateWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.BooleanSupplierWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.ConsumerWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.FunctionWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.PredicateWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.RunnableWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.SupplierWithContext} + *
    • {@link nl.talsmasoftware.context.core.function.UnaryOperatorWithContext} + *
    + * + *

    + * The base class {@link nl.talsmasoftware.context.core.function.WrapperWithContextAndConsumer} allows + * capturing a new context snapshot after the function has finished. + */ +package nl.talsmasoftware.context.core.function; diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/package-info.java similarity index 95% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/package-info.java index f1814c52..75e7d4b8 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/package-info.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/package-info.java @@ -30,7 +30,7 @@ *

    {@linkplain nl.talsmasoftware.context.api.ContextManager}

    *

    * Manages the active context. - * Can {@linkplain nl.talsmasoftware.context.api.ContextManager#initializeNewContext(java.lang.Object) initialize a new context} + * Can {@linkplain nl.talsmasoftware.context.api.ContextManager#initializeNewContext(Object) initialize a new context} * and provides access to * the {@linkplain nl.talsmasoftware.context.api.ContextManager#getActiveContextValue() active context value}. * @@ -49,4 +49,4 @@ * * @author Sjoerd Talsma */ -package nl.talsmasoftware.context; +package nl.talsmasoftware.context.core; diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java similarity index 100% rename from context-propagation-api/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java rename to context-propagation-core/src/main/java/nl/talsmasoftware/context/core/threadlocal/AbstractThreadLocalContext.java diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java deleted file mode 100644 index 2065af38..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiConsumerWithContext.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link BiConsumer} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class BiConsumerWithContext extends nl.talsmasoftware.context.core.function.BiConsumerWithContext { - public BiConsumerWithContext(ContextSnapshot snapshot, BiConsumer delegate) { - super(snapshot, delegate); - } - - public BiConsumerWithContext(ContextSnapshot snapshot, BiConsumer delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected BiConsumerWithContext(Supplier supplier, BiConsumer delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java deleted file mode 100644 index fe505cc4..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiFunctionWithContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link BiFunction} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class BiFunctionWithContext extends nl.talsmasoftware.context.core.function.BiFunctionWithContext { - - public BiFunctionWithContext(ContextSnapshot snapshot, BiFunction delegate) { - super(snapshot, delegate); - } - - public BiFunctionWithContext(ContextSnapshot snapshot, BiFunction delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected BiFunctionWithContext(Supplier supplier, BiFunction delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java deleted file mode 100644 index 3c898bc8..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BiPredicateWithContext.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.BiPredicate; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link BiPredicate} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class BiPredicateWithContext extends nl.talsmasoftware.context.core.function.BiPredicateWithContext { - public BiPredicateWithContext(ContextSnapshot snapshot, BiPredicate delegate) { - super(snapshot, delegate); - } - - public BiPredicateWithContext(ContextSnapshot snapshot, BiPredicate delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected BiPredicateWithContext(Supplier supplier, BiPredicate delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java deleted file mode 100644 index 7768af10..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.BinaryOperator; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link BinaryOperator} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class BinaryOperatorWithContext extends nl.talsmasoftware.context.core.function.BinaryOperatorWithContext { - - public BinaryOperatorWithContext(ContextSnapshot snapshot, BinaryOperator delegate) { - super(snapshot, delegate); - } - - public BinaryOperatorWithContext(ContextSnapshot snapshot, BinaryOperator delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected BinaryOperatorWithContext(Supplier supplier, BinaryOperator delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java deleted file mode 100644 index 9225412f..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/BooleanSupplierWithContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link BooleanSupplier} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class BooleanSupplierWithContext extends nl.talsmasoftware.context.core.function.BooleanSupplierWithContext { - - public BooleanSupplierWithContext(ContextSnapshot snapshot, BooleanSupplier delegate) { - super(snapshot, delegate); - } - - public BooleanSupplierWithContext(ContextSnapshot snapshot, BooleanSupplier delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected BooleanSupplierWithContext(Supplier supplier, BooleanSupplier delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java deleted file mode 100644 index 82ced5ea..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/ConsumerWithContext.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link Consumer} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class ConsumerWithContext extends nl.talsmasoftware.context.core.function.ConsumerWithContext { - - public ConsumerWithContext(ContextSnapshot snapshot, Consumer delegate) { - super(snapshot, delegate); - } - - public ConsumerWithContext(ContextSnapshot snapshot, Consumer delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected ConsumerWithContext(Supplier supplier, Consumer delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java deleted file mode 100644 index a7563c42..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/FunctionWithContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * A wrapper for {@link Function} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class FunctionWithContext extends nl.talsmasoftware.context.core.function.FunctionWithContext { - - public FunctionWithContext(ContextSnapshot snapshot, Function delegate) { - super(snapshot, delegate); - } - - public FunctionWithContext(ContextSnapshot snapshot, Function delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected FunctionWithContext(Supplier supplier, Function delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java deleted file mode 100644 index f71f62cb..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/PredicateWithContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; - -/** - * A wrapper for {@link Predicate} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class PredicateWithContext extends nl.talsmasoftware.context.core.function.PredicateWithContext { - - public PredicateWithContext(ContextSnapshot snapshot, Predicate delegate) { - super(snapshot, delegate); - } - - public PredicateWithContext(ContextSnapshot snapshot, Predicate delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected PredicateWithContext(Supplier supplier, Predicate delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java deleted file mode 100644 index 69b9d8c4..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/RunnableWithContext.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.core.ContextManagers; - -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link Runnable} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class RunnableWithContext extends nl.talsmasoftware.context.core.function.RunnableWithContext { - - /** - * Creates a new runnable that performs the following steps, in-order: - *

      - *
    1. first {@linkplain ContextSnapshot#reactivate() reactivate} the given snapshot - *
    2. then run the delegate - *
    - * - * @param snapshot A snapshot for the contexts to run the delegate in. - * @param delegate The delegate to run. - * @see #RunnableWithContext(ContextSnapshot, Runnable, Consumer) - */ - public RunnableWithContext(ContextSnapshot snapshot, Runnable delegate) { - super(snapshot, delegate); - } - - /** - * Creates a new runnable that performs the following steps, in-order: - *
      - *
    1. first {@linkplain ContextSnapshot#reactivate() reactivate} the given snapshot - *
    2. then run the delegate - *
    3. finally, if a consumer was provided - * {@linkplain ContextManagers#createContextSnapshot() capture a new ContextSnapshot} - *
    - * - * @param snapshot A snapshot for the contexts to run the delegate in. - * @param delegate The delegate to run. - * @param consumer An optional consumer for the resulting contexts after the delegate ran (in case it changed) - */ - public RunnableWithContext(ContextSnapshot snapshot, Runnable delegate, Consumer consumer) { - super(snapshot, delegate, consumer); - } - - protected RunnableWithContext(Supplier supplier, Runnable delegate, Consumer consumer) { - super(supplier, delegate, consumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java deleted file mode 100644 index cf76d39b..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/SupplierWithContext.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A wrapper for {@link Supplier} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class SupplierWithContext extends nl.talsmasoftware.context.core.function.SupplierWithContext { - - public SupplierWithContext(ContextSnapshot snapshot, Supplier delegate) { - super(snapshot, delegate); - } - - public SupplierWithContext(ContextSnapshot snapshot, Supplier delegate, Consumer snapshotConsumer) { - super(snapshot, delegate, snapshotConsumer); - } - - protected SupplierWithContext(Supplier snapshotSupplier, Supplier delegate, Consumer snapshotConsumer) { - super(snapshotSupplier, delegate, snapshotConsumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java deleted file mode 100644 index a50359e2..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContext.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; - -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; - -/** - * A wrapper for {@link UnaryOperator} that {@link ContextSnapshot#reactivate() reactivates a context snapshot} before - * calling a delegate. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -public class UnaryOperatorWithContext extends nl.talsmasoftware.context.core.function.UnaryOperatorWithContext { - - public UnaryOperatorWithContext(ContextSnapshot snapshot, UnaryOperator delegate) { - super(snapshot, delegate); - } - - public UnaryOperatorWithContext(ContextSnapshot snapshot, UnaryOperator delegate, Consumer snapshotConsumer) { - super(snapshot, delegate, snapshotConsumer); - } - - protected UnaryOperatorWithContext(Supplier supplier, UnaryOperator delegate, Consumer snapshotConsumer) { - super(supplier, delegate, snapshotConsumer); - } -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java deleted file mode 100644 index 3da0bf55..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumer.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.functions; - -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.core.delegation.WrapperWithContext; - -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * Package-convenience subclass for {@linkplain WrapperWithContext} that takes Java 8 generic functional interfaces - * {@link Supplier} and {@link Consumer} instead of the specific Java 5 versions. - * - * @param The type of the wrapped delegate object. - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.function}. - */ -@Deprecated -abstract class WrapperWithContextAndConsumer extends WrapperWithContext { - - /** - * The context snapshot consumer to provide a new snapshot to after the function is completed, may be {@code null}. - */ - protected final Consumer contextSnapshotConsumer; - - /** - * A new wrapper around a delegate object with a {@linkplain ContextSnapshot}. - * - * @param snapshot The context snapshot to be reactivated around the delegate (required). - * @param delegate The delegate action to perform. - * @param contextSnapshotConsumer An optional post-action consumer to receive a new context snapshot taken after the action. - */ - protected WrapperWithContextAndConsumer(ContextSnapshot snapshot, T delegate, Consumer contextSnapshotConsumer) { - super(snapshot, delegate); - this.contextSnapshotConsumer = contextSnapshotConsumer; - } - - /** - * A new wrapper around a delegate object with a {@linkplain ContextSnapshot}. - * - * @param contextSnapshotSupplier Supplies the context snapshot to be reactivated around the delegate (required). - * @param delegate The delegate action to perform. - * @param contextSnapshotConsumer An optional post-action consumer to receive a new context snapshot taken after the action. - */ - protected WrapperWithContextAndConsumer(Supplier contextSnapshotSupplier, T delegate, Consumer contextSnapshotConsumer) { - super(contextSnapshotSupplier == null ? null : contextSnapshotSupplier::get, delegate); - this.contextSnapshotConsumer = contextSnapshotConsumer; - } - - /** - * @return An optional post-action consumer to receive a new context snapshot taken after the action. - * @deprecated The functional wrappers currently no longer use this method. - */ - @Deprecated - protected Optional> consumer() { - return Optional.ofNullable(contextSnapshotConsumer); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java deleted file mode 100644 index 564b0f45..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/functions/package-info.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Java 8 functional interface wrappers that apply context snapshots to the mapped functions. - * - *

    - * The following functional interfaces are available: - *

      - *
    • {@link nl.talsmasoftware.context.functions.BiConsumerWithContext} - *
    • {@link nl.talsmasoftware.context.functions.BiFunctionWithContext} - *
    • {@link nl.talsmasoftware.context.functions.BinaryOperatorWithContext} - *
    • {@link nl.talsmasoftware.context.functions.BiPredicateWithContext} - *
    • {@link nl.talsmasoftware.context.functions.BooleanSupplierWithContext} - *
    • {@link nl.talsmasoftware.context.functions.ConsumerWithContext} - *
    • {@link nl.talsmasoftware.context.functions.FunctionWithContext} - *
    • {@link nl.talsmasoftware.context.functions.PredicateWithContext} - *
    • {@link nl.talsmasoftware.context.functions.RunnableWithContext} - *
    • {@link nl.talsmasoftware.context.functions.SupplierWithContext} - *
    • {@link nl.talsmasoftware.context.functions.UnaryOperatorWithContext} - *
    - * - *

    - * The base class {@link nl.talsmasoftware.context.functions.WrapperWithContextAndConsumer} allows - * capturing a new context snapshot after the function has finished. - */ -package nl.talsmasoftware.context.functions; \ No newline at end of file diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java deleted file mode 100644 index bf8fb66f..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFuture.java +++ /dev/null @@ -1,803 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.futures; - -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.functions.BiConsumerWithContext; -import nl.talsmasoftware.context.functions.BiFunctionWithContext; -import nl.talsmasoftware.context.functions.ConsumerWithContext; -import nl.talsmasoftware.context.functions.FunctionWithContext; -import nl.talsmasoftware.context.functions.RunnableWithContext; -import nl.talsmasoftware.context.functions.SupplierWithContext; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.Executor; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -import static java.util.Objects.requireNonNull; - -/** - * This class extends the standard {@link CompletableFuture} that was introduced in java version 8. - *

    - * The class is a 'normal' Completable Future, but every successive call made on the result will be made within the - * {@link ContextSnapshot context during creation} of this {@link ContextAwareCompletableFuture}. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.concurrent}. - */ -@Deprecated -public class ContextAwareCompletableFuture extends CompletableFuture { - - /** - * Holder for context snapshots to be propagated from one CompletionStage to the next. - */ - private final ContextSnapshotHolder snapshotHolder; - - /** - * Whether to take a new snapshot after each completion stage. - */ - private final boolean takeNewSnapshot; - - /** - * Creates a new {@link ContextSnapshot} and remembers that in this completable future, - * running all completion methods within this snapshot. - * - * @see ContextManagers#createContextSnapshot() - */ - public ContextAwareCompletableFuture() { - this((ContextSnapshot) null); - } - - /** - * Creates a new {@link CompletableFuture} where all completion methods are run within the specified - * snapshot context. - * - * @param snapshot the snapshot to run completion methods in. - * Optional, the completable future will take a new snaphot if {@code null} is provided. - * @see ContextManagers#createContextSnapshot() - */ - public ContextAwareCompletableFuture(ContextSnapshot snapshot) { - this(new ContextSnapshotHolder(snapshot), false); - } - - private ContextAwareCompletableFuture(ContextSnapshotHolder holder, boolean takeNewSnapshot) { - this.snapshotHolder = requireNonNull(holder, "Snapshot holder is "); - this.takeNewSnapshot = takeNewSnapshot; - } - - /** - * Runs the {@code supplier} task in the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} - * within the current context and also applies that context to all successive - * calls to the {@code CompletableFuture}. - * - * @param supplier a function to be performed asynchronously returning the result of the CompletableFuture - * @param the function's return type - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#supplyAsync(Supplier) - * @see ContextAwareCompletableFuture#supplyAsync(Supplier, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture supplyAsync(Supplier supplier) { - return supplyAsync(supplier, null, null, false); - } - - /** - * Runs the {@code supplier} task in the specified {@link Executor executor} - * within the current context and also applies that context to all successive - * calls to the {@code CompletableFuture}. - * - * @param supplier a function returning the value to be used to complete the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @param the function's return type - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#supplyAsync(Supplier, Executor) - * @see ContextAwareCompletableFuture#supplyAsync(Supplier, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture supplyAsync(Supplier supplier, Executor executor) { - return supplyAsync(supplier, executor, null, false); - } - - /** - * Runs the {@code supplier} task in the specified {@link Executor executor} - * within the specified {@link ContextSnapshot context snapshot} and also applies that context - * to all successive calls to the {@code CompletableFuture}. - *

    - * This method is lenient to {@code null} values for {@code executor} and {@code snapshot}:
    - * If {@code executor == null} the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} is used as - * specified by {@link CompletableFuture#supplyAsync(Supplier)}.
    - * If {@code snapshot == null} a {@link ContextManagers#createContextSnapshot() new context snapshot} is - * created for the {@link Supplier} (if not already a {@link SupplierWithContext}). - * - * @param supplier a function returning the value to be used to complete the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @param snapshot a snapshot of the context to be propagated in the supplier function - * and all successive calls of this completable future - * @param the function's return type - * @return The new CompletableFuture that propagates the specified context snapshot - * @see CompletableFuture#supplyAsync(Supplier, Executor) - * @see ContextAwareCompletableFuture#supplyAsync(Supplier, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture supplyAsync(Supplier supplier, Executor executor, ContextSnapshot snapshot) { - return supplyAsync(supplier, executor, snapshot, false); - } - - /** - * Runs the {@code supplier} task in the specified {@link Executor executor} - * within the specified {@link ContextSnapshot context snapshot} and also applies that context - * to all successive calls to the {@code CompletableFuture}. - *

    - * This method is lenient to {@code null} values for {@code executor} and {@code snapshot}:
    - * If {@code executor == null} the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} is used as - * specified by {@link CompletableFuture#supplyAsync(Supplier)}.
    - * If {@code snapshot == null} a {@link ContextManagers#createContextSnapshot() new context snapshot} is - * created for the {@link Supplier} (if not already a {@link SupplierWithContext}). - * - * @param supplier a function returning the value to be used to complete the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @param snapshot a snapshot of the context to be propagated in the supplier function - * and all successive calls of this completable future - * @param takeNewSnapshot whether a new ContextSnapshot should be taken after the supplier function is done. - * If {@code false}, the snapshot from the caller propagate to all following completion stages. - * If {@code true}, a new snapshot is taken after each completion stage to propagate into the next. - * @param the function's return type - * @return The new CompletableFuture that propagates the specified context snapshot - * @see CompletableFuture#supplyAsync(Supplier, Executor) - * @since 1.0.4 - */ - public static ContextAwareCompletableFuture supplyAsync( - Supplier supplier, Executor executor, ContextSnapshot snapshot, boolean takeNewSnapshot) { - - final ContextSnapshotHolder holder = new ContextSnapshotHolder(snapshot); - supplier = new SupplierWithContext(holder, supplier, takeNewSnapshot ? holder : null) { - }; - return wrap(executor == null - ? CompletableFuture.supplyAsync(supplier) - : CompletableFuture.supplyAsync(supplier, executor), - holder, - takeNewSnapshot); - } - - /** - * Runs the {@code runnable} task in the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} - * within the current context and also applies that context to all successive - * calls to the {@code CompletableFuture}. - * - * @param runnable the action to run before completing the returned CompletableFuture - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#runAsync(Runnable) - * @see ContextAwareCompletableFuture#runAsync(Runnable, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture runAsync(Runnable runnable) { - return runAsync(runnable, null, null, false); - } - - /** - * Runs the {@code runnable} task in the specified {@link Executor executor} - * within the current context and also applies that context to all successive - * calls to the {@code CompletableFuture}. - * - * @param runnable the action to run before completing the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#runAsync(Runnable, Executor) - * @see ContextAwareCompletableFuture#runAsync(Runnable, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture runAsync(Runnable runnable, Executor executor) { - return runAsync(runnable, executor, null, false); - } - - /** - * Runs the {@code runnable} task in the specified {@link Executor executor} - * within the specified {@link ContextSnapshot context snapshot} and also applies that context - * to all successive calls to the {@code CompletableFuture}. - *

    - * This method is lenient to {@code null} values for {@code executor} and {@code snapshot}:
    - * If {@code executor == null} the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} is used as - * specified by {@link CompletableFuture#supplyAsync(Supplier)}.
    - * If {@code snapshot == null} a {@link ContextManagers#createContextSnapshot() new context snapshot} is - * created for the {@link Supplier} (if not already a {@link SupplierWithContext}). - * - * @param runnable the action to run before completing the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @param snapshot the context snapshot to apply to the runnable action - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#runAsync(Runnable, Executor) - * @see ContextAwareCompletableFuture#runAsync(Runnable, Executor, ContextSnapshot, boolean) - */ - public static ContextAwareCompletableFuture runAsync(Runnable runnable, Executor executor, ContextSnapshot snapshot) { - return runAsync(runnable, executor, snapshot, false); - } - - /** - * Runs the {@code runnable} task in the specified {@link Executor executor} - * within the specified {@link ContextSnapshot context snapshot} and also applies that context - * to all successive calls to the {@code CompletableFuture}. - *

    - * This method is lenient to {@code null} values for {@code executor} and {@code snapshot}:
    - * If {@code executor == null} the common {@link java.util.concurrent.ForkJoinPool ForkJoinPool} is used as - * specified by {@link CompletableFuture#supplyAsync(Supplier)}.
    - * If {@code snapshot == null} a {@link ContextManagers#createContextSnapshot() new context snapshot} is - * created for the {@link Supplier} (if not already a {@link SupplierWithContext}). - * - * @param runnable the action to run before completing the returned CompletableFuture - * @param executor the executor to use for asynchronous execution - * @param snapshot the context snapshot to apply to the runnable action - * @param takeNewSnapshot whether a new ContextSnapshot should be taken after the supplier function is done. - * If {@code false}, the snapshot from the caller propagate to all following completion stages. - * If {@code true}, a new snapshot is taken after each completion stage to propagate into the next. - * @return The new CompletableFuture that propagates a snapshot of the current context - * @see CompletableFuture#runAsync(Runnable, Executor) - * @since 1.0.4 - */ - public static ContextAwareCompletableFuture runAsync( - Runnable runnable, Executor executor, ContextSnapshot snapshot, boolean takeNewSnapshot) { - - final ContextSnapshotHolder holder = new ContextSnapshotHolder(snapshot); - runnable = new RunnableWithContext(holder, runnable, takeNewSnapshot ? holder : null) { - }; - return wrap(executor == null - ? CompletableFuture.runAsync(runnable) - : CompletableFuture.runAsync(runnable, executor), - holder, - takeNewSnapshot); - } - - /** - * Creates a new {@code ContextAwareCompletableFuture} from the already-completed value. - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param value the value to return from the already-completed future. - * @param the type of the value - * @return New {@code ContextAwareCompletableFuture} returning the completed value - * and containing a new {@code ContextSnapshot}. - * @see #completedFuture(Object, ContextSnapshot) - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture completedFuture(U value) { - return completedFuture(value, null); - } - - /** - * Creates a new {@code ContextAwareCompletableFuture} from the already-completed value. - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param value the value to return from the already-completed future. - * @param snapshot the context snapshot to apply to following completion stages - * (optional, specify {@code null} to take a new snapshot) - * @param the type of the value - * @return New {@code ContextAwareCompletableFuture} returning the completed value - * and containing the specified {@code ContextSnapshot}. - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture completedFuture(U value, ContextSnapshot snapshot) { - final ContextAwareCompletableFuture completedFuture = new ContextAwareCompletableFuture<>(snapshot); - completedFuture.complete(value); - return completedFuture; - } - - /** - * Creates a new {@code CompletionStage} from the already-completed value. - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param value the value to return from the already-completed stage. - * @param the type of the value - * @return New {@code CompletionStage} returning the completed value - * and containing a new {@code ContextSnapshot}. - * @see #completedFuture(Object, ContextSnapshot) - * @since 1.0.5 - */ - public static CompletionStage completedStage(U value) { - return completedFuture(value, null); - } - - /** - * Creates a new {@code ContextAwareCompletableFuture} that is already completed - * exceptionally with the given exception. - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param ex the exception - * @param the type of the value - * @return New {@code ContextAwareCompletableFuture} throwing the exception - * and containing a new {@code ContextSnapshot}. - * @see #failedFuture(Throwable, ContextSnapshot) - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture failedFuture(Throwable ex) { - return failedFuture(ex, null); - } - - /** - * Creates a new {@code ContextAwareCompletableFuture} that is already completed - * exceptionally with the given exception. - * The specified {@code snapshot} is applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param ex the exception - * @param snapshot the context snapshot to apply to following completion stages - * (optional, specify {@code null} to take a new snapshot) - * @param the type of the value - * @return New {@code ContextAwareCompletableFuture} throwing the exception - * and containing the specified {@code snapshot}. - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture failedFuture(Throwable ex, ContextSnapshot snapshot) { - final ContextAwareCompletableFuture failedFuture = new ContextAwareCompletableFuture<>(snapshot); - failedFuture.completeExceptionally(ex); - return failedFuture; - } - - /** - * Creates a new {@code CompletionStage} that is already completed - * exceptionally with the given exception. - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param ex the exception - * @param the type of the value - * @return New {@code CompletionStage} throwing the exception - * and containing a new {@code ContextSnapshot}. - * @see #failedFuture(Throwable, ContextSnapshot) - * @since 1.0.5 - */ - public static CompletionStage failedStage(Throwable ex) { - return failedFuture(ex, null); - } - - /** - * Returns a new CompletableFuture that is completed when all of - * the given CompletableFutures complete. If any of the given - * CompletableFutures complete exceptionally, then the returned - * CompletableFuture also does so, with a CompletionException - * holding this exception as its cause. Otherwise, the results, - * if any, of the given CompletableFutures are not reflected in - * the returned CompletableFuture, but may be obtained by - * inspecting them individually. If no CompletableFutures are - * provided, returns a CompletableFuture completed with the value - * {@code null}. - *

    - * Among the applications of this method is to await completion - * of a set of independent CompletableFutures before continuing a - * program, as in: {@code CompletableFuture.allOf(c1, c2, - * c3).join();}. - *

    - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param cfs the CompletableFutures - * @return A new {@code ContextAwareCompletableFuture} that is completed when all of the - * given CompletableFutures complete - * @throws NullPointerException if the array or any of its elements are {@code null} - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture allOf(CompletableFuture... cfs) { - return allOf((ContextSnapshot) null, cfs); - } - - /** - * Returns a new CompletableFuture that is completed when all of - * the given CompletableFutures complete. If any of the given - * CompletableFutures complete exceptionally, then the returned - * CompletableFuture also does so, with a CompletionException - * holding this exception as its cause. Otherwise, the results, - * if any, of the given CompletableFutures are not reflected in - * the returned CompletableFuture, but may be obtained by - * inspecting them individually. If no CompletableFutures are - * provided, returns a CompletableFuture completed with the value - * {@code null}. - *

    - * Among the applications of this method is to await completion - * of a set of independent CompletableFutures before continuing a - * program, as in: {@code CompletableFuture.allOf(c1, c2, - * c3).join();}. - *

    - * The specified {@linkplain ContextSnapshot} is applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param snapshot the context snapshot to apply to following completion stages - * (optional, specify {@code null} to take a new snapshot) - * @param cfs the CompletableFutures - * @return A new {@code ContextAwareCompletableFuture} that is completed when all of the - * given CompletableFutures complete - * @throws NullPointerException if the array or any of its elements are {@code null} - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture allOf(ContextSnapshot snapshot, CompletableFuture... cfs) { - final ContextSnapshotHolder holder = new ContextSnapshotHolder(snapshot); - return wrap(CompletableFuture.allOf(cfs), holder, false); - } - - /** - * Returns a new CompletableFuture that is completed when any of - * the given CompletableFutures complete, with the same result. - * Otherwise, if it completed exceptionally, the returned - * CompletableFuture also does so, with a CompletionException - * holding this exception as its cause. If no CompletableFutures - * are provided, returns an incomplete CompletableFuture. - *

    - * A new {@linkplain ContextSnapshot} is taken and applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param cfs the CompletableFutures - * @return a new CompletableFuture that is completed with the result or exception - * of any of the given CompletableFutures when one completes - * @throws NullPointerException if the array or any of its elements are {@code null} - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture anyOf(CompletableFuture... cfs) { - return anyOf((ContextSnapshot) null, cfs); - } - - /** - * Returns a new CompletableFuture that is completed when any of - * the given CompletableFutures complete, with the same result. - * Otherwise, if it completed exceptionally, the returned - * CompletableFuture also does so, with a CompletionException - * holding this exception as its cause. If no CompletableFutures - * are provided, returns an incomplete CompletableFuture. - *

    - * The specified {@linkplain ContextSnapshot} is applied to all - * following {@linkplain CompletionStage completion stages}. - * - * @param snapshot the context snapshot to apply to following completion stages - * (optional, specify {@code null} to take a new snapshot) - * @param cfs the CompletableFutures - * @return a new CompletableFuture that is completed with the result or exception - * of any of the given CompletableFutures when one completes - * @throws NullPointerException if the array or any of its elements are {@code null} - * @since 1.0.5 - */ - public static ContextAwareCompletableFuture anyOf(ContextSnapshot snapshot, CompletableFuture... cfs) { - final ContextSnapshotHolder holder = new ContextSnapshotHolder(snapshot); - return wrap(CompletableFuture.anyOf(cfs), holder, false); - } - - private static ContextAwareCompletableFuture wrap(CompletableFuture completableFuture, ContextSnapshotHolder holder, boolean takeNewSnapshot) { - ContextAwareCompletableFuture contextAwareCompletableFuture = new ContextAwareCompletableFuture<>(holder, takeNewSnapshot); - completableFuture.whenComplete((result, throwable) -> { - if (throwable != null) contextAwareCompletableFuture.completeExceptionally(throwable); - else contextAwareCompletableFuture.complete(result); - }); - return contextAwareCompletableFuture; - } - - /** - * @return The {@code snapshotHolder} if {@code takeNewSnapshot == true} or otherwise {@code null}. - */ - private Consumer resultSnapshotConsumer() { - return takeNewSnapshot ? snapshotHolder : null; - } - - /** - * Returns a context-aware CompletableFuture that takes a new snapshot after each completion stage. - *

    - * This means that after each {@code then...}, {@code run...}, {@code apply...} method, - * after calling the function, a new context snapshot is taken for follow-up calls. - *

    - * Only use this when chaining completable futures where the completion stages may update contextual values.
    - * Warning: This may result in unnecessary context snapshots being taken. - * - * @return A new context-aware completable future where context changes also propagate accross completion stages. - * @see CompletionStage - */ - public ContextAwareCompletableFuture takeNewSnapshot() { - return takeNewSnapshot(true); - } - - /** - * Returns a context-aware CompletableFuture that may take a new snapshot after each completion stage. - *

    - * This means that after each {@code then...}, {@code run...}, {@code apply...} method, - * after calling the function, a new context snapshot is taken for follow-up calls. - *

    - * Only set this to {@code true} when chaining completable futures where the completion stages - * may update contextual values.
    - * Warning: This may result in unnecessary context snapshots being taken. - * - * @param takeSnapshot whether new context snapshots must be taken after each completion stage. - * @return A context-aware completable future where context changes also propagate accross completion stages - * if {@code takeSnapshot} is {@code true}. - * @see CompletionStage - */ - public ContextAwareCompletableFuture takeNewSnapshot(boolean takeSnapshot) { - return this.takeNewSnapshot == takeSnapshot ? this : wrap(this, snapshotHolder, takeSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenApply(Function fn) { - return wrap(super.thenApply(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenApplyAsync(Function fn) { - return wrap(super.thenApplyAsync(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenApplyAsync(Function fn, Executor executor) { - return wrap(super.thenApplyAsync(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAccept(Consumer action) { - return wrap(super.thenAccept(new ConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAcceptAsync(Consumer action) { - return wrap(super.thenAcceptAsync(new ConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAcceptAsync(Consumer action, Executor executor) { - return wrap(super.thenAcceptAsync(new ConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture thenRun(Runnable action) { - return wrap(super.thenRun(new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - public CompletableFuture thenRunAsync(Runnable action) { - return wrap(super.thenRunAsync(new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture thenRunAsync(Runnable action, Executor executor) { - return wrap(super.thenRunAsync(new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenCombine( - CompletionStage other, BiFunction fn) { - return wrap(super.thenCombine(other, new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenCombineAsync( - CompletionStage other, BiFunction fn) { - return wrap(super.thenCombineAsync(other, new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenCombineAsync( - CompletionStage other, BiFunction fn, Executor executor) { - return wrap(super.thenCombineAsync(other, new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAcceptBoth( - CompletionStage other, BiConsumer action) { - return wrap(super.thenAcceptBoth(other, new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAcceptBothAsync( - CompletionStage other, BiConsumer action) { - return wrap(super.thenAcceptBothAsync(other, new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenAcceptBothAsync( - CompletionStage other, BiConsumer action, Executor executor) { - return wrap(super.thenAcceptBothAsync(other, new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterBoth(CompletionStage other, Runnable action) { - return wrap(super.runAfterBoth(other, new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterBothAsync(CompletionStage other, Runnable action) { - return wrap(super.runAfterBothAsync(other, new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor) { - return wrap(super.runAfterBothAsync(other, new RunnableWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture applyToEither(CompletionStage other, Function fn) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.applyToEither(other, new FunctionWithContext(newHolder, fn, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture applyToEitherAsync(CompletionStage other, Function fn) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.applyToEitherAsync(other, new FunctionWithContext(newHolder, fn, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture applyToEitherAsync( - CompletionStage other, Function fn, Executor executor) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.applyToEitherAsync(other, new FunctionWithContext(newHolder, fn, takeNewSnapshot ? newHolder : null) { - }, executor), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture acceptEither(CompletionStage other, Consumer action) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.acceptEither(other, new ConsumerWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture acceptEitherAsync(CompletionStage other, Consumer action) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.acceptEitherAsync(other, new ConsumerWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture acceptEitherAsync( - CompletionStage other, Consumer action, Executor executor) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.acceptEitherAsync(other, new ConsumerWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }, executor), newHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterEither(CompletionStage other, Runnable action) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.runAfterEither(other, new RunnableWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.runAfterEitherAsync(other, new RunnableWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }), newHolder, takeNewSnapshot); - } - - @Override - public ContextAwareCompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor) { - // Don't gamble which completion stage might win, create a new holder for the resulting function instead. - final ContextSnapshotHolder newHolder = new ContextSnapshotHolder(snapshotHolder.get()); - return wrap(super.runAfterEitherAsync(other, new RunnableWithContext(newHolder, action, takeNewSnapshot ? newHolder : null) { - }, executor), newHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenCompose(Function> fn) { - return wrap(super.thenCompose(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenComposeAsync(Function> fn) { - return wrap(super.thenComposeAsync(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture thenComposeAsync(Function> fn, Executor executor) { - return wrap(super.thenComposeAsync(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture whenComplete(BiConsumer action) { - return wrap(super.whenComplete(new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture whenCompleteAsync(BiConsumer action) { - return wrap(super.whenCompleteAsync(new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture whenCompleteAsync(BiConsumer action, Executor executor) { - return wrap(super.whenCompleteAsync(new BiConsumerWithContext(snapshotHolder, action, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture handle(BiFunction fn) { - return wrap(super.handle(new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture handleAsync(BiFunction fn) { - return wrap(super.handleAsync(new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture handleAsync(BiFunction fn, Executor executor) { - return wrap(super.handleAsync(new BiFunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }, executor), snapshotHolder, takeNewSnapshot); - } - - @Override - @SuppressWarnings("unchecked") - public ContextAwareCompletableFuture exceptionally(Function fn) { - return wrap(super.exceptionally(new FunctionWithContext(snapshotHolder, fn, resultSnapshotConsumer()) { - }), snapshotHolder, takeNewSnapshot); - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java deleted file mode 100644 index a937357c..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/ContextSnapshotHolder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.futures; - -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.core.ContextManagers; - -import java.util.function.Consumer; -import java.util.function.Supplier; - -import static java.util.Objects.requireNonNull; - -/** - * Snapshot holder that is used internally to temporarily 'hold' a context snapshot - * to be propagated from one {@code CompletionStage} to another. - * - * @author Sjoerd Talsma - * @deprecated Moved to package {@code nl.talsmasoftware.context.core.concurrent}. - */ -@Deprecated -final class ContextSnapshotHolder implements Consumer, Supplier { - private volatile ContextSnapshot snapshot; - - /** - * Create a new snapshot holder initially containing either the provided snapshot, - * or takes a new snapshot as initial value. - * - * @param snapshot The snapshot to hold initially. - * Optional, if {@code null} the holder will initialize with a new snapshot. - */ - ContextSnapshotHolder(ContextSnapshot snapshot) { - this.snapshot = (snapshot == null ? ContextManagers.createContextSnapshot() : snapshot); - } - - /** - * Accept a new snapshot (i.e. after a single stage is completed) to be propagated - * into another completion stage. - * - * @param snapshot The snapshot to hold (required, must not be {@code null}) - */ - @Override - public void accept(ContextSnapshot snapshot) { - this.snapshot = requireNonNull(snapshot, "Context snapshot is ."); - } - - /** - * Returns the current snapshot, normally to activate when beginning a new completion stage. - * - * @return The held snapshot (should never be {@code null}) - */ - @Override - public ContextSnapshot get() { - return snapshot; - } - -} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java deleted file mode 100644 index de9881ad..00000000 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/futures/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Package for context-aware java {@link java.util.concurrent.Future} code. - * - *

    {@linkplain nl.talsmasoftware.context.futures.ContextAwareCompletableFuture}

    - *

    - * A {@linkplain java.util.concurrent.CompletableFuture} that applies a certain - * {@linkplain nl.talsmasoftware.context.api.ContextSnapshot} to all - * {@linkplain java.util.concurrent.CompletionStage completion stages} of the completable future. - */ -package nl.talsmasoftware.context.futures; diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/clearable/ClearableContextManagerTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/clearable/ClearableDummyContextManager.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java similarity index 79% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index 01a42f5b..9380df80 100644 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -21,6 +21,7 @@ import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import nl.talsmasoftware.context.dummy.ThrowingContextManager; +import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,7 +46,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; - /** * @author Sjoerd Talsma */ @@ -84,37 +84,37 @@ public void testUnsupportedConstructor() { @Test public void testSnapshot_inSameThread() throws IOException { dummyManager.clear(); - assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); DummyContext ctx1 = new DummyContext("initial value"); - assertThat(DummyContext.currentValue(), is("initial value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); DummyContext ctx2 = new DummyContext("second value"); - assertThat(DummyContext.currentValue(), is("second value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - assertThat(DummyContext.currentValue(), is("second value")); // No context change because of snapshot. + MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); // No context change because of snapshot. DummyContext ctx3 = new DummyContext("third value"); - assertThat(DummyContext.currentValue(), is("third value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // Reactivate snapshot: ctx1 -> ctx2 -> ctx3 -> ctx2' Closeable reactivation = snapshot.reactivate(); - assertThat(DummyContext.currentValue(), is("second value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); reactivation.close(); - assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! + MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! // out-of-order closing! ctx2.close(); - assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! + MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! ctx3.close(); - assertThat(DummyContext.currentValue(), is("initial value")); // back to ctx1 because ctx2 is closed + MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); // back to ctx1 because ctx2 is closed - assertThat(ctx1.isClosed(), is(false)); - assertThat(ctx2.isClosed(), is(true)); - assertThat(ctx3.isClosed(), is(true)); + MatcherAssert.assertThat(ctx1.isClosed(), is(false)); + MatcherAssert.assertThat(ctx2.isClosed(), is(true)); + MatcherAssert.assertThat(ctx3.isClosed(), is(true)); ctx1.close(); } @@ -122,10 +122,10 @@ public void testSnapshot_inSameThread() throws IOException { public void testSnapshotThreadPropagation() throws ExecutionException, InterruptedException { DummyContext.reset(); ExecutorService threadpool = new ContextAwareExecutorService(Executors.newCachedThreadPool()); - assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); DummyContext ctx1 = new DummyContext("initial value"); - assertThat(DummyContext.currentValue(), is("initial value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); Future threadResult = threadpool.submit(new Callable() { public String call() throws Exception { return DummyContext.currentValue(); @@ -143,7 +143,7 @@ public String call() throws Exception { return res + ", " + DummyContext.currentValue(); } }); - assertThat(DummyContext.currentValue(), is("second value")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); assertThat(threadResult.get(), is("second value, in-thread value, second value")); ctx2.close(); @@ -179,11 +179,11 @@ public void testCreateSnapshot_ExceptionHandling() throws IOException { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx.close(); - assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); Closeable reactivation = snapshot.reactivate(); - assertThat(DummyContext.currentValue(), is("blah")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("blah")); reactivation.close(); - assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); } @Test @@ -195,18 +195,18 @@ public void testReactivateSnapshot_ExceptionHandling() { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ThrowingContextManager.onInitialize = reactivationException; - assertThat(DummyContext.currentValue(), is("foo")); - assertThat(mgr.getActiveContextValue(), is("bar")); + MatcherAssert.assertThat(DummyContext.currentValue(), is("foo")); + MatcherAssert.assertThat(mgr.getActiveContextValue(), is("bar")); ctx1.close(); ctx2.close(); - assertThat(DummyContext.currentValue(), is(nullValue())); - assertThat(mgr.getActiveContextValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(mgr.getActiveContextValue(), is(nullValue())); RuntimeException expected = assertThrows(RuntimeException.class, snapshot::reactivate); // foo + bar mustn't be set after exception! - assertThat(DummyContext.currentValue(), is(nullValue())); - assertThat(mgr.getActiveContextValue(), is(nullValue())); + MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + MatcherAssert.assertThat(mgr.getActiveContextValue(), is(nullValue())); } @Test diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/TimersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/TimersTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java index 9384b30c..c2322a88 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareCompletableFutureTest.java @@ -18,6 +18,7 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -68,7 +69,7 @@ private static void assertContext(String expectedValue) { private static Supplier stringSupplier(String name, String requiredContext) { return () -> { assertContext(requiredContext); - manager.initializeNewContext(name); // intentionally not closed here + DummyContext.setCurrentValue(name); // intentionally not closed here assertContext(name); assertDoesNotThrow(() -> Thread.sleep(50 + RND.nextInt(200))); return String.format(name + " (Thread: %s)", Thread.currentThread().getName()); @@ -95,16 +96,16 @@ public void testDefaultConstructor() throws ExecutionException, InterruptedExcep @Test public void testSupplyAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Vincent Vega")) { - Future> future = supplyAsync(DummyContextManager::currentValue); - assertThat(future.get().get(), is("Vincent Vega")); + Future future = supplyAsync(DummyContext::currentValue); + assertThat(future.get(), is("Vincent Vega")); } } @Test public void testSupplyAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = supplyAsync(DummyContextManager::currentValue, contextUnawareThreadpool); - assertThat(future.get().get(), is("Marcellus Wallace")); + Future future = supplyAsync(DummyContext::currentValue, contextUnawareThreadpool); + assertThat(future.get(), is("Marcellus Wallace")); } } @@ -112,11 +113,11 @@ public void testSupplyAsync_executor() throws ExecutionException, InterruptedExc public void testSupplyAsync_executor_snapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Vincent Vega")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); assertContext("Jules Winnfield"); - Future> future = supplyAsync(DummyContextManager::currentValue, contextUnawareThreadpool, snapshot); - assertThat(future.get().get(), is("Vincent Vega")); + Future future = supplyAsync(DummyContext::currentValue, contextUnawareThreadpool, snapshot); + assertThat(future.get(), is("Vincent Vega")); } } @@ -124,26 +125,26 @@ public void testSupplyAsync_executor_snapshot() throws ExecutionException, Inter public void testSupplyAsync_executor_snapshot_takeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Vincent Vega")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); assertContext("Jules Winnfield"); - ContextAwareCompletableFuture> future = supplyAsync(() -> { + ContextAwareCompletableFuture future = supplyAsync(() -> { try { - return DummyContextManager.currentValue(); + return DummyContext.currentValue(); } finally { - DummyContextManager.setCurrentValue("Marcellus Wallace"); + DummyContext.setCurrentValue("Marcellus Wallace"); } }, contextUnawareThreadpool, snapshot, true); - assertThat(future.get(), is(Optional.of("Vincent Vega"))); - assertThat(future.thenApply(x -> DummyContextManager.currentValue()).get(), is(Optional.of("Marcellus Wallace"))); + assertThat(future.get(), is("Vincent Vega")); + assertThat(future.thenApply(x -> DummyContext.currentValue()).get(), is("Marcellus Wallace")); } } @Test public void testRunAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Mia Wallace")) { - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Mia Wallace")))); + ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContext.currentValue(), is("Mia Wallace"))); future.get(); // trigger asynchronous assertion } } @@ -151,7 +152,7 @@ public void testRunAsync() throws ExecutionException, InterruptedException { @Test public void testRunAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Jimmie"))), contextUnawareThreadpool); + ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContext.currentValue(), is("Jimmie")), contextUnawareThreadpool); future.get(); // trigger asynchronous assertion } } @@ -160,10 +161,10 @@ public void testRunAsync_executor() throws ExecutionException, InterruptedExcept public void testRunAsync_executor_snapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pumpkin")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Honey Bunny"); + DummyContext.setCurrentValue("Honey Bunny"); assertContext("Honey Bunny"); - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Pumpkin"))), contextUnawareThreadpool, snapshot); + ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> assertThat(DummyContext.currentValue(), is("Pumpkin")), contextUnawareThreadpool, snapshot); future.get(); // trigger asynchronous assertion } } @@ -172,81 +173,90 @@ public void testRunAsync_executor_snapshot() throws ExecutionException, Interrup public void testRunAsync_executor_snapshot_takeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pumpkin")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Honey Bunny"); + DummyContext.setCurrentValue("Honey Bunny"); assertContext("Honey Bunny"); ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync(() -> { - try { - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pumpkin"))); - } finally { - DummyContextManager.setCurrentValue("Bad Motherfucker"); - } + assertThat(DummyContext.currentValue(), is("Pumpkin")); + DummyContext.setCurrentValue("Bad Motherfucker"); }, contextUnawareThreadpool, snapshot, true); - future.get(); // trigger asynchronous assertion - future.thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Bad Motherfucker")))).get(); + future.get(); // trigger asynchronous assertion and makes sure the function already ended. + future.thenRun(() -> assertThat(DummyContext.currentValue(), is("Bad Motherfucker"))).get(); } } @Test public void testThenApply() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Jimmie")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Bonnie")).thenApply(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Jimmie"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Bonnie")) + .thenApply(voidvalue -> DummyContext.currentValue()); + assertThat(future.get(), is("Jimmie")); } try (Context ctx = manager.initializeNewContext("Jimmie")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Bonnie"), null, null, true).thenApply(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Bonnie"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Bonnie"), null, null, true) + .thenApply(voidvalue -> DummyContext.currentValue()); + assertThat(future.get(), is("Bonnie")); } } @Test public void testThenApplyAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos")).thenApplyAsync(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get().get(), is("Butch")); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Esmerelda Villalobos")) + .thenApplyAsync(voidvalue -> DummyContext.currentValue()); + assertThat(future.get(), is("Butch")); } try (Context ctx = manager.initializeNewContext("Butch")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos"), null, null, true).thenApplyAsync(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get().get(), is("Esmerelda Villalobos")); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Esmerelda Villalobos"), null, null, true) + .thenApplyAsync(voidvalue -> DummyContext.currentValue()); + assertThat(future.get(), is("Esmerelda Villalobos")); } } @Test public void testThenApplyAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Maynard")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Zed")).thenApplyAsync(voidvalue -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get().get(), is("Maynard")); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Zed")) + .thenApplyAsync(voidvalue -> DummyContext.currentValue(), contextUnawareThreadpool); + assertThat(future.get(), is("Maynard")); } try (Context ctx = manager.initializeNewContext("Maynard")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Zed"), null, null, true).thenApplyAsync(voidvalue -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get().get(), is("Zed")); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Zed"), null, null, true) + .thenApplyAsync(voidvalue -> DummyContext.currentValue(), contextUnawareThreadpool); + assertThat(future.get(), is("Zed")); } } @Test public void testThenApplyAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Bonnie")).takeNewSnapshot().thenApply(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Bonnie")).takeNewSnapshot().thenApply(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }).thenAccept(s -> { assertThat(s, is("Jimmie")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Jimmie"))); + assertThat(DummyContext.currentValue(), is("-Jimmie")); }).get(); } try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Bonnie"), null, null, true).thenApply(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Bonnie"), null, null, true).thenApply(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }).thenAccept(s -> { assertThat(s, is("Bonnie")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Bonnie"))); + assertThat(DummyContext.currentValue(), is("-Bonnie")); }).get(); } } @@ -254,24 +264,24 @@ public void testThenApplyAndTakeNewSnapshot() throws ExecutionException, Interru @Test public void testThenApplyAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos")).takeNewSnapshot().thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Esmerelda Villalobos")).takeNewSnapshot().thenApplyAsync(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }).thenAccept(s -> { assertThat(s, is("Butch")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch"))); + assertThat(DummyContext.currentValue(), is("-Butch")); }).get(); } try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos"), null, null, true).thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Esmerelda Villalobos"), null, null, true).thenApplyAsync(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }).thenAccept(s -> { assertThat(s, is("Esmerelda Villalobos")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Esmerelda Villalobos"))); + assertThat(DummyContext.currentValue(), is("-Esmerelda Villalobos")); }).get(); } } @@ -279,24 +289,24 @@ public void testThenApplyAsyncAndTakeNewSnapshot() throws ExecutionException, In @Test public void testThenApplyAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Maynard")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Zed")).takeNewSnapshot().thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Zed")).takeNewSnapshot().thenApplyAsync(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }, contextUnawareThreadpool).thenAccept(s -> { assertThat(s, is("Maynard")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Maynard"))); + assertThat(DummyContext.currentValue(), is("-Maynard")); }).get(); } try (Context ctx = manager.initializeNewContext("Maynard")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Zed"), null, null, true).thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Zed"), null, null, true).thenApplyAsync(voidvalue -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; }, contextUnawareThreadpool).thenAccept(s -> { assertThat(s, is("Zed")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Zed"))); + assertThat(DummyContext.currentValue(), is("-Zed")); }).get(); } } @@ -304,12 +314,14 @@ public void testThenApplyAsyncAndTakeNewSnapshot_executor() throws ExecutionExce @Test public void testThenAccept() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("The Gimp")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch")).thenAccept(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("The Gimp")))); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Butch")) + .thenAccept(voidvalue -> assertThat(DummyContext.currentValue(), is("The Gimp"))); future.get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("The Gimp")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch"), null, null, true).thenAccept(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Butch"), null, null, true) + .thenAccept(voidvalue -> assertThat(DummyContext.currentValue(), is("Butch"))); future.get(); // trigger asynchronous assertion } } @@ -317,12 +329,16 @@ public void testThenAccept() throws ExecutionException, InterruptedException { @Test public void testThenAcceptAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Fabienne")).thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Fabienne")) + .thenAcceptAsync(voidvalue -> assertThat(DummyContext.currentValue(), is("Butch"))); future.get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Butch")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Fabienne"), null, null, true).thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Fabienne")))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Fabienne"), null, null, true) + .thenAcceptAsync(voidvalue -> assertThat(DummyContext.currentValue(), is("Fabienne"))); future.get(); // trigger asynchronous assertion } } @@ -330,12 +346,16 @@ public void testThenAcceptAsync() throws ExecutionException, InterruptedExceptio @Test public void testThenAcceptAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Marvin")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Winston Wolfe")).thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Marvin"))), contextUnawareThreadpool); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Winston Wolfe")) + .thenAcceptAsync(voidvalue -> assertThat(DummyContext.currentValue(), is("Marvin")), contextUnawareThreadpool); future.get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Marvin")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Winston Wolfe"), null, null, true).thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Winston Wolfe"))), contextUnawareThreadpool); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Winston Wolfe"), null, null, true) + .thenAcceptAsync(voidvalue -> assertThat(DummyContext.currentValue(), is("Winston Wolfe")), contextUnawareThreadpool); future.get(); // trigger asynchronous assertion } } @@ -343,186 +363,247 @@ public void testThenAcceptAsync_executor() throws ExecutionException, Interrupte @Test public void testThenAcceptAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("The Gimp")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch")).takeNewSnapshot().thenAccept(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("The Gimp")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-The Gimp")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Butch")).takeNewSnapshot().thenAccept(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("The Gimp")); + DummyContext.setCurrentValue("-" + val); + }).thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-The Gimp"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("The Gimp")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch"), null, null, true).thenAccept(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Butch"), null, null, true).thenAccept(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Butch")); + DummyContext.setCurrentValue("-" + val); + }).thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Butch"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenAcceptAsynAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Fabienne")).takeNewSnapshot().thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Fabienne")).takeNewSnapshot().thenAcceptAsync(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Butch")); + DummyContext.setCurrentValue("-" + val); + }).thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Butch"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Fabienne"), null, null, true).thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Fabienne")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Fabienne")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Fabienne"), null, null, true).thenAcceptAsync(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Fabienne")); + DummyContext.setCurrentValue("-" + val); + }).thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Fabienne"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenAcceptAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Marvin")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Winston Wolfe")).takeNewSnapshot().thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Marvin")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Winston Wolfe")).takeNewSnapshot().thenAcceptAsync(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Marvin")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Marvin"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Marvin")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Winston Wolfe"), null, null, true).thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Winston Wolfe")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Winston Wolfe")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Winston Wolfe"), null, null, true).thenAcceptAsync(voidvalue -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Winston Wolfe")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool).thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Winston Wolfe"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenRun() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Lance")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jody")).thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Lance")))); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Jody")).thenRun(() -> assertThat(DummyContext.currentValue(), is("Lance"))); future.get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Lance")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jody"), null, null, true).thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Jody")))); - future.get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Jody"), null, null, true) + .thenRun(() -> assertThat(DummyContext.currentValue(), is("Jody"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenRunAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Ringo")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Yolanda")).thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Ringo")))); - future.get(); // trigger asynchronous assertion + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Yolanda")) + .thenRunAsync(() -> assertThat(DummyContext.currentValue(), is("Ringo"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Ringo")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Yolanda"), null, null, true).thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Yolanda")))); - future.get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Yolanda"), null, null, true) + .thenRunAsync(() -> assertThat(DummyContext.currentValue(), is("Yolanda"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenRunAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch")).thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Capt. Koons"))), contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Butch")) + .thenRunAsync(() -> assertThat(DummyContext.currentValue(), is("Capt. Koons")), contextUnawareThreadpool) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch"), null, null, true).thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch"))), contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Butch"), null, null, true) + .thenRunAsync(() -> assertThat(DummyContext.currentValue(), is("Butch")), contextUnawareThreadpool) + .get(); // trigger asynchronous assertion } } @Test public void testThenRunAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Lance")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jody")).takeNewSnapshot().thenRun(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Lance")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Lance")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Jody")) + .takeNewSnapshot() + .thenRun(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Lance")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Lance"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Lance")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jody"), null, null, true).thenRun(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Jody")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Jody")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Jody"), null, null, true) + .thenRun(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Jody")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Jody"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenRunAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Ringo")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Yolanda")).takeNewSnapshot().thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Ringo")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Ringo")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Yolanda")) + .takeNewSnapshot() + .thenRunAsync(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Ringo")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Ringo"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Ringo")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Yolanda"), null, null, true).thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Yolanda")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Yolanda")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Yolanda"), null, null, true) + .thenRunAsync(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Yolanda")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Yolanda"))) + .get(); // trigger asynchronous assertion } } @Test public void testThenRunAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch")).takeNewSnapshot().thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Capt. Koons")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Capt. Koons")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Butch")) + .takeNewSnapshot() + .thenRunAsync(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Capt. Koons")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Capt. Koons"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Butch"), null, null, true).thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Butch"), null, null, true) + .thenRunAsync(() -> { + String val = DummyContext.currentValue(); + assertThat(val, is("Butch")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool) + .thenAccept(aVoid -> assertThat(DummyContext.currentValue(), is("-Butch"))) + .get(); // trigger asynchronous assertion } } @Test public void testWhenComplete() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Floyd")).whenComplete((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Floyd")) + .whenComplete((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Butch"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Floyd"), null, null, true).whenComplete((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Floyd")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Floyd"), null, null, true) + .whenComplete((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Floyd"))) + .get(); // trigger asynchronous assertion } } @Test public void testWhenCompleteAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Zed")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Pipe hittin' niggers")).whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Zed")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Pipe hittin' niggers")) + .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Zed"))) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Zed")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Pipe hittin' niggers"), null, null, true).whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Pipe hittin' niggers")))).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Pipe hittin' niggers"), null, null, true) + .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Pipe hittin' niggers"))) + .get(); // trigger asynchronous assertion } } @Test public void testWhenCompleteAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Floyd")).whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch"))), contextUnawareThreadpool).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Floyd")) + .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Butch")), contextUnawareThreadpool) + .get(); // trigger asynchronous assertion } try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Floyd"), null, null, true).whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Floyd"))), contextUnawareThreadpool).get(); // trigger asynchronous assertion + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Floyd"), null, null, true) + .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContext.currentValue(), is("Floyd")), contextUnawareThreadpool) + .get(); // trigger asynchronous assertion } } @@ -531,14 +612,14 @@ public void testHandle() throws ExecutionException, InterruptedException { final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Trudy")); } @@ -549,14 +630,14 @@ public void testHandleAsync() throws ExecutionException, InterruptedException { final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue()).get(), is("Trudy")); } @@ -567,14 +648,14 @@ public void testHandleAsync_executor() throws ExecutionException, InterruptedExc final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).handleAsync((voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> manager.getActiveContextValue(), contextUnawareThreadpool).get(), is("Trudy")); } @@ -585,22 +666,22 @@ public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedEx final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).takeNewSnapshot().handle((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handle((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); } @@ -611,22 +692,22 @@ public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, Interrup final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).takeNewSnapshot().handleAsync((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); } @@ -637,22 +718,22 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, final RuntimeException exception = new RuntimeException("Bad Motherfucker"); try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }).takeNewSnapshot().handleAsync((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }, contextUnawareThreadpool).whenComplete((result, throwable) -> assertContext("-Jody")).get(), is("Jody")); } try (Context ctx = manager.initializeNewContext("Jody")) { assertThat(ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Trudy"); + DummyContext.setCurrentValue("Trudy"); throw exception; }, null, null, true).handleAsync((voidValue, throwable) -> { String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return val; }, contextUnawareThreadpool).whenComplete((result, throwable) -> assertContext("-Trudy")).get(), is("Trudy")); } @@ -662,7 +743,7 @@ public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, public void testExceptionally() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Gringo")) { ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }).exceptionally(ex -> { String val = manager.getActiveContextValue(); @@ -673,7 +754,7 @@ public void testExceptionally() throws ExecutionException, InterruptedException try (Context ctx = manager.initializeNewContext("Gringo")) { ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }, null, null, true).exceptionally(ex -> { String val = manager.getActiveContextValue(); @@ -687,24 +768,24 @@ public void testExceptionally() throws ExecutionException, InterruptedException public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Gringo")) { ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }).takeNewSnapshot().exceptionally(ex -> { String val = manager.getActiveContextValue(); assertThat(val, is("Gringo")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return null; }).thenAccept(aVoid -> assertContext("-Gringo")).get(); } try (Context ctx = manager.initializeNewContext("Gringo")) { ContextAwareCompletableFuture.runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); throw new RuntimeException("Bad Motherfucker"); }, null, null, true).exceptionally(ex -> { String val = manager.getActiveContextValue(); assertThat(val, is("Jules Winnfield")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); return null; }).thenAccept(aVoid -> assertContext("-Jules Winnfield")).get(); } @@ -713,66 +794,87 @@ public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, Int @Test public void testThenCombine() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Vincent Vega")).thenCombine(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Marcellus Wallace"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Marcellus Wallace"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Vincent Vega")) + .thenCombine(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Jules Winnfield")), (voidA, voidB) -> DummyContext.currentValue()); + assertThat(future.get(), is("Marcellus Wallace")); + assertThat(DummyContext.currentValue(), is("Marcellus Wallace")); } try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Vincent Vega"), null, null, true).thenCombine(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Vincent Vega"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Marcellus Wallace"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Vincent Vega"), null, null, true) + .thenCombine(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Jules Winnfield")), (voidA, voidB) -> DummyContext.currentValue()); + assertThat(future.get(), is("Vincent Vega")); + assertThat(DummyContext.currentValue(), is("Marcellus Wallace")); } } @Test public void testThenCombineAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin")).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Brett"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Marvin")) + .thenCombineAsync(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> DummyContext.currentValue()); + assertThat(future.get(), is("Brett")); + assertThat(DummyContext.currentValue(), is("Brett")); } try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Marvin"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Marvin"), null, null, true) + .thenCombineAsync(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> DummyContext.currentValue()); + assertThat(future.get(), is("Marvin")); + assertThat(DummyContext.currentValue(), is("Brett")); } } @Test public void testThenCombineAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin")).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get(), is(Optional.of("Brett"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Marvin")) + .thenCombineAsync(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> DummyContext.currentValue(), contextUnawareThreadpool); + assertThat(future.get(), is("Brett")); + assertThat(DummyContext.currentValue(), is("Brett")); } try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get(), is(Optional.of("Marvin"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Marvin"), null, null, true) + .thenCombineAsync(ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> DummyContext.currentValue(), contextUnawareThreadpool); + assertThat(future.get(), is("Marvin")); + assertThat(DummyContext.currentValue(), is("Brett")); } } @Test public void testThenCombineAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Vincent Vega")).takeNewSnapshot().thenCombine(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }).whenComplete((result, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marcellus Wallace")))); + Future future = ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Vincent Vega")) + .takeNewSnapshot() + .thenCombine(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Jules Winnfield")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); + return val; + }).whenComplete((result, exception) -> assertThat(DummyContext.currentValue(), is("-Marcellus Wallace"))); assertThat(future.get(), is("Marcellus Wallace")); } try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Vincent Vega"), null, null, true).thenCombine(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Vincent Vega"), null, null, true).thenCombine(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Jules Winnfield")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; - }).whenComplete((result, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Vincent Vega")))); + }).whenComplete((result, exception) -> assertThat(DummyContext.currentValue(), is("-Vincent Vega"))); assertThat(future.get(), is("Vincent Vega")); } @@ -781,132 +883,168 @@ public void testThenCombineAndTakeNewSnapshot() throws ExecutionException, Inter @Test public void testThenCombineAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin")).takeNewSnapshot().thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Marvin")).takeNewSnapshot().thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; - }).whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Brett")))); + }).whenComplete((result, exeption) -> assertThat(DummyContext.currentValue(), is("-Brett"))); assertThat(future.get(), is("Brett")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + assertThat(DummyContext.currentValue(), is("Brett")); } try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; - }).whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))); + }).whenComplete((result, exeption) -> assertThat(DummyContext.currentValue(), is("-Marvin"))); assertThat(future.get(), is("Marvin")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + assertThat(DummyContext.currentValue(), is("Brett")); } } @Test public void testThenCombineAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin")).takeNewSnapshot().thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Marvin")).takeNewSnapshot().thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; - }, contextUnawareThreadpool).whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Brett")))); + }, contextUnawareThreadpool).whenComplete((result, exeption) -> assertThat(DummyContext.currentValue(), is("-Brett"))); assertThat(future.get(), is("Brett")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + assertThat(DummyContext.currentValue(), is("Brett")); } try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); + Future future = ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Marvin"), null, null, true).thenCombineAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Flock of Seagulls")), (voidA, voidB) -> { + String val = DummyContext.currentValue(); + DummyContext.setCurrentValue("-" + val); return val; - }, contextUnawareThreadpool).whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))); + }, contextUnawareThreadpool).whenComplete((result, exeption) -> assertThat(DummyContext.currentValue(), is("-Marvin"))); assertThat(future.get(), is("Marvin")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); + assertThat(DummyContext.currentValue(), is("Brett")); } } @Test public void testThenAcceptBoth() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))).get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))) + .get(); + assertThat(DummyContext.currentValue(), is("Pulp Fiction")); } } @Test public void testThenAcceptBothAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))).get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino"))) + .get(); + assertThat(DummyContext.currentValue(), is("Pulp Fiction")); } } @Test public void testThenAcceptBothAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino")), contextUnawareThreadpool).get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> assertThat(manager.getActiveContextValue() + stringB, is("QuentinTarantino")), contextUnawareThreadpool) + .get(); + assertThat(DummyContext.currentValue(), is("Pulp Fiction")); } } @Test public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin")) + .takeNewSnapshot() + .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("Pulp Fiction by Tarantino")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) + .get(); } try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Quentin by Tarantino")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertContext("-Quentin by Tarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("Quentin by Tarantino")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertContext("-Quentin by Tarantino")) + .get(); } } @Test public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin")) + .takeNewSnapshot() + .thenAcceptBoth(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("Pulp Fiction by Tarantino")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) + .get(); } try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("QuentinTarantino")); - manager.initializeNewContext("-" + val); - }).thenAccept(aVoid -> assertContext("-QuentinTarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBoth(completedFuture("Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("QuentinTarantino")); + DummyContext.setCurrentValue("-" + val); + }) + .thenAccept(aVoid -> assertContext("-QuentinTarantino")) + .get(); } } @Test public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue()).takeNewSnapshot().thenAcceptBothAsync(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin")) + .takeNewSnapshot() + .thenAcceptBothAsync(completedFuture(" by Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("Pulp Fiction by Tarantino")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool) + .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) + .get(); assertContext("Pulp Fiction"); } try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true).thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("QuentinTarantino")); - manager.initializeNewContext("-" + val); - }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-QuentinTarantino")).get(); + ContextAwareCompletableFuture + .runAsync(() -> DummyContext.setCurrentValue("Quentin"), null, null, true) + .thenAcceptBothAsync(completedFuture("Tarantino"), (Void voidA, String stringB) -> { + String val = manager.getActiveContextValue() + stringB; + assertThat(val, is("QuentinTarantino")); + DummyContext.setCurrentValue("-" + val); + }, contextUnawareThreadpool) + .thenAccept(aVoid -> assertContext("-QuentinTarantino")) + .get(); assertContext("Pulp Fiction"); } } @@ -914,51 +1052,51 @@ public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws Executio @Test public void testRunAfterBoth() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("French Fries")).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("French Fries")).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("Ketchup")).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("Ketchup")).get(); } } @Test public void testRunAfterBothAsync() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("French Fries")).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("French Fries")).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("Ketchup")).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("Ketchup")).get(); } } @Test public void testRunAfterBothAsync_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("French Fries"), contextUnawareThreadpool).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("French Fries"), contextUnawareThreadpool).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> assertContext("Ketchup"), contextUnawareThreadpool).get(); + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> assertContext("Ketchup"), contextUnawareThreadpool).get(); } } @Test public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).takeNewSnapshot().runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }).thenAccept(aVoid -> assertContext("-French Fries")).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBoth(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }).thenAccept(aVoid -> assertContext("-Ketchup")).get(); } } @@ -966,18 +1104,18 @@ public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, Inte @Test public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }).thenAccept(aVoid -> assertContext("-French Fries")).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }).thenAccept(aVoid -> assertContext("-Ketchup")).get(); } } @@ -985,18 +1123,18 @@ public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, @Test public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup")).takeNewSnapshot().runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-French Fries")).get(); } try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), () -> { + ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Ketchup"), null, null, true).runAfterBothAsync(ContextAwareCompletableFuture.runAsync(() -> DummyContext.setCurrentValue("Mayonaise")), () -> { String val = manager.getActiveContextValue(); assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); + DummyContext.setCurrentValue("-" + val); }, contextUnawareThreadpool).thenAccept(aVoid -> assertContext("-Ketchup")).get(); } } @@ -1159,7 +1297,7 @@ public void testThenCompose() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnJohn")); } @@ -1167,7 +1305,7 @@ public void testThenCompose() throws ExecutionException, InterruptedException { try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }, null, null, true).thenCompose(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnTravolta")); } @@ -1178,7 +1316,7 @@ public void testThenComposeAsync() throws ExecutionException, InterruptedExcepti try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnJohn")); } @@ -1186,7 +1324,7 @@ public void testThenComposeAsync() throws ExecutionException, InterruptedExcepti try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }, null, null, true).thenComposeAsync(value -> supplyAsync(() -> value + manager.getActiveContextValue())).get(), is("JohnTravolta")); } @@ -1197,7 +1335,7 @@ public void testThenComposeAsync_executor() throws ExecutionException, Interrupt try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }).thenComposeAsync(value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool).get(), is("JohnJohn")); } @@ -1205,7 +1343,7 @@ public void testThenComposeAsync_executor() throws ExecutionException, Interrupt try (Context ctx = manager.initializeNewContext("John")) { assertThat(supplyAsync(() -> { String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); + DummyContext.setCurrentValue("Travolta"); return current; }, null, null, true).thenComposeAsync(value -> completedFuture(value + manager.getActiveContextValue()), contextUnawareThreadpool).get(), is("JohnTravolta")); } @@ -1216,18 +1354,18 @@ public void testTimingIssue55() throws ExecutionException, InterruptedException, try (Context ctx = manager.initializeNewContext("Vincent Vega")) { final CountDownLatch latch1 = new CountDownLatch(1), latch2 = new CountDownLatch(1); ContextAwareCompletableFuture future1 = supplyAsync(() -> { - String result = DummyContextManager.currentValue().orElse("NO VALUE"); - DummyContextManager.setCurrentValue("Jules Winnfield"); + String result = Optional.ofNullable(DummyContext.currentValue()).orElse("NO VALUE"); + DummyContext.setCurrentValue("Jules Winnfield"); waitFor(latch1); return result; }, null, null, true); ContextAwareCompletableFuture future2 = future1.thenApplyAsync(value -> { - String result = value + ", " + DummyContextManager.currentValue().orElse("NO VALUE"); - DummyContextManager.setCurrentValue("Marcellus Wallace"); + String result = value + ", " + Optional.ofNullable(DummyContext.currentValue()).orElse("NO VALUE"); + DummyContext.setCurrentValue("Marcellus Wallace"); waitFor(latch2); return result; }); - Future future3 = future2.thenApplyAsync(value -> value + ", " + DummyContextManager.currentValue().orElse("NO VALUE")); + Future future3 = future2.thenApplyAsync(value -> value + ", " + Optional.ofNullable(DummyContext.currentValue()).orElse("NO VALUE")); assertThat("Future creation may not block on previous stages", future1.isDone(), is(false)); assertThat("Future creation may not block on previous stages", future2.isDone(), is(false)); @@ -1243,20 +1381,20 @@ public void testTimingIssue55() throws ExecutionException, InterruptedException, future2.get(500, TimeUnit.MILLISECONDS); assertThat("Future creation may not block on previous stages", future2.isDone(), is(true)); assertThat(future3.get(500, TimeUnit.MILLISECONDS), is("Vincent Vega, Jules Winnfield, Marcellus Wallace")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Vincent Vega"))); + assertThat(DummyContext.currentValue(), is("Vincent Vega")); } } @Test public void testAllOf() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); + DummyContext.setCurrentValue("Vincent Vega"); CompletableFuture cf1 = new CompletableFuture<>(); CompletableFuture cf2 = new ContextAwareCompletableFuture().takeNewSnapshot().thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored + DummyContext.setCurrentValue("-" + s); // This context should be ignored return s; }); ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); @@ -1268,16 +1406,16 @@ public void testAllOf() throws ExecutionException, InterruptedException { @Test public void testAllOfWithSpecificSnapshot() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); + DummyContext.setCurrentValue("Vincent Vega"); final ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Marcellus Wallace"); + DummyContext.setCurrentValue("Marcellus Wallace"); CompletableFuture cf1 = new CompletableFuture<>(); CompletableFuture cf2 = new ContextAwareCompletableFuture().takeNewSnapshot().thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored + DummyContext.setCurrentValue("-" + s); // This context should be ignored return s; }); ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(snapshot, cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); @@ -1289,14 +1427,14 @@ public void testAllOfWithSpecificSnapshot() throws ExecutionException, Interrupt @Test public void testAnyOf() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); + DummyContext.setCurrentValue("Vincent Vega"); CompletableFuture cf1 = new CompletableFuture<>(); CompletableFuture cf2 = new ContextAwareCompletableFuture().takeNewSnapshot().thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored + DummyContext.setCurrentValue("-" + s); // This context should be ignored return s; }); ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); @@ -1307,16 +1445,16 @@ public void testAnyOf() throws ExecutionException, InterruptedException { @Test public void testAnyOfWithSpecificSnapshot() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); + DummyContext.setCurrentValue("Vincent Vega"); final ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Marcellus Wallace"); + DummyContext.setCurrentValue("Marcellus Wallace"); CompletableFuture cf1 = new CompletableFuture<>(); CompletableFuture cf2 = new ContextAwareCompletableFuture().takeNewSnapshot().thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored + DummyContext.setCurrentValue("-" + s); // This context should be ignored return s; }); ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(snapshot, cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); + DummyContext.setCurrentValue("Jules Winnfield"); ContextAwareCompletableFuture result = future.thenApplyAsync(s -> manager.getActiveContextValue()); assertThat(result.isDone(), is(false)); diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextAwareExecutorServiceTest.java diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolderTest.java similarity index 97% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolderTest.java index 1bd17267..aae22b6d 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextSnapshotHolderTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/ContextSnapshotHolderTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.futures; +package nl.talsmasoftware.context.core.concurrent; import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.Test; diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/FailedFutureTest.java similarity index 98% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/FailedFutureTest.java index 9db6fdb9..ebc334d9 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/FailedFutureTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/concurrent/FailedFutureTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.futures; +package nl.talsmasoftware.context.core.concurrent; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/CallableToRunnableTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingExecutorServiceTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/MappingExecutorServiceTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperTest.java diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/WrapperWithContextTest.java diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java index 9a732d09..39700b13 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiConsumerWithContextTest.java @@ -31,8 +31,8 @@ import java.util.function.BiConsumer; import static java.lang.String.format; -import static nl.talsmasoftware.context.dummy.DummyContextManager.currentValue; -import static nl.talsmasoftware.context.dummy.DummyContextManager.setCurrentValue; +import static nl.talsmasoftware.context.dummy.DummyContext.currentValue; +import static nl.talsmasoftware.context.dummy.DummyContext.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -100,15 +100,15 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { Thread t = new Thread(() -> consumer.accept("New", "value")); t.start(); - assertThat("Setting context in other thread musn't impact caller", currentValue(), is(Optional.of("Old value"))); + assertThat("Setting context in other thread musn't impact caller", currentValue(), is("Old value")); t.join(); // Block and trigger assertions - assertThat("Setting context in other thread musn't impact caller", currentValue(), is(Optional.of("Old value"))); + assertThat("Setting context in other thread musn't impact caller", currentValue(), is("Old value")); assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { try (Reactivation reactivation = snapshotHolder[0].reactivate()) { - assertThat("Thread context must propagate", currentValue(), is(Optional.of("New value"))); + assertThat("Thread context must propagate", currentValue(), is("New value")); } }); t.start(); @@ -122,18 +122,18 @@ public void testAndThen() throws InterruptedException { setCurrentValue("Old value"); BiConsumer consumer1 = new BiConsumerWithContext<>( ContextManagers.createContextSnapshot(), - (a, b) -> setCurrentValue(a + " " + b + ", " + currentValue().orElse("NO VALUE")), + (a, b) -> setCurrentValue(a + " " + b + ", " + Optional.ofNullable(currentValue()).orElse("NO VALUE")), s -> snapshotHolder[0] = s); BiConsumer consumer2 = consumer1.andThen( - (a, b) -> setCurrentValue(a.toUpperCase() + " " + b.toLowerCase() + ", " + currentValue().orElse("NO VALUE"))); + (a, b) -> setCurrentValue(a.toUpperCase() + " " + b.toLowerCase() + ", " + Optional.ofNullable(currentValue()).orElse("NO VALUE"))); Thread t = new Thread(() -> consumer2.accept("New", "value")); t.start(); t.join(); - assertThat(currentValue(), is(Optional.of("Old value"))); + assertThat(currentValue(), is("Old value")); try (Reactivation reactivated = snapshotHolder[0].reactivate()) { - assertThat(currentValue(), is(Optional.of("NEW value, New value, Old value"))); + assertThat(currentValue(), is("NEW value, New value, Old value")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java similarity index 92% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java index b472bc6a..6705f3b0 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiFunctionWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Function; @@ -98,22 +98,22 @@ public void testApplyWithoutSnapshotSupplier() { @Test public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new BiFunctionWithContext<>(snapshot, (input1, input2) -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return input2; }, snapshot -> snapshotHolder[0] = snapshot).apply("input1", "input2")); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java similarity index 94% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java index c018849b..2c403b22 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BiPredicateWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiPredicate; import java.util.function.Supplier; @@ -97,22 +97,22 @@ public void testTestWithoutSnapshotSupplier() { @Test public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new BiPredicateWithContext<>(snapshot, (a, b) -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return true; }, snapshot -> snapshotHolder[0] = snapshot).test("input1", "input2")); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java similarity index 92% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java index d640666c..4da0d8e7 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/BinaryOperatorWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.BinaryOperator; @@ -100,22 +100,21 @@ public void testApplyWithoutSnapshotSupplier() { @Test public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new BinaryOperatorWithContext<>(snapshot, (input1, input2) -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return input2; }, snapshot -> snapshotHolder[0] = snapshot).apply("input1", "input2")); t.start(); t.join(); - - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java index 32e0605c..9b3b150b 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java @@ -17,6 +17,7 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -86,25 +86,25 @@ public void testConstructWithoutSnapshotSupplier() { @Test public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { - DummyContextManager.setCurrentValue("true"); + DummyContext.setCurrentValue("true"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; BooleanSupplier supplier = new BooleanSupplierWithContext(ContextManagers.createContextSnapshot(), () -> { try { - return Boolean.parseBoolean(DummyContextManager.currentValue().get()); + return Boolean.parseBoolean(DummyContext.currentValue()); } finally { - DummyContextManager.setCurrentValue("false"); + DummyContext.setCurrentValue("false"); } }, s -> snapshotHolder[0] = s); Future future = unawareThreadpool.submit(supplier::getAsBoolean); assertThat(future.get(), is(true)); - assertThat(DummyContextManager.currentValue(), is(Optional.of("true"))); + assertThat(DummyContext.currentValue(), is("true")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("false"))); + assertThat(DummyContext.currentValue(), is("false")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("true"))); + assertThat(DummyContext.currentValue(), is("true")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java index e36775f4..46874bfd 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java @@ -32,8 +32,8 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import static nl.talsmasoftware.context.dummy.DummyContextManager.currentValue; -import static nl.talsmasoftware.context.dummy.DummyContextManager.setCurrentValue; +import static nl.talsmasoftware.context.dummy.DummyContext.currentValue; +import static nl.talsmasoftware.context.dummy.DummyContext.setCurrentValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -96,15 +96,15 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { Thread t = new Thread(() -> consumer.accept("New value")); t.start(); - assertThat("Setting context in other thread musn't impact caller", currentValue(), is(Optional.of("Old value"))); + assertThat("Setting context in other thread musn't impact caller", currentValue(), is("Old value")); t.join(); // Block and trigger assertions - assertThat("Setting context in other thread musn't impact caller", currentValue(), is(Optional.of("Old value"))); + assertThat("Setting context in other thread musn't impact caller", currentValue(), is("Old value")); assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat("Thread context must propagate", currentValue(), is(Optional.of("New value"))); + assertThat("Thread context must propagate", currentValue(), is("New value")); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } @@ -120,17 +120,17 @@ public void testAndThen() throws InterruptedException, IOException { Consumer consumer = new ConsumerWithContext( ContextManagers.createContextSnapshot(), - val -> setCurrentValue(val + ", " + currentValue().orElse("NO VALUE")), + val -> setCurrentValue(val + ", " + Optional.ofNullable(currentValue()).orElse("NO VALUE")), s -> snapshotHolder[0] = s) - .andThen(val -> setCurrentValue(val.toUpperCase() + ", " + currentValue().orElse("NO VALUE"))); + .andThen(val -> setCurrentValue(val.toUpperCase() + ", " + Optional.ofNullable(currentValue()).orElse("NO VALUE"))); Thread t = new Thread(() -> consumer.accept("New value")); t.start(); t.join(); - assertThat(currentValue(), is(Optional.of("Old value"))); + assertThat(currentValue(), is("Old value")); try (Closeable reactivated = snapshotHolder[0].reactivate()) { - assertThat(currentValue(), is(Optional.of("NEW VALUE, New value, Old value"))); + assertThat(currentValue(), is("NEW VALUE, New value, Old value")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java similarity index 93% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java index c03c211a..a18848f5 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/FunctionWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Supplier; @@ -97,22 +97,22 @@ public void testApplyWithoutSnapshotSupplier() { @Test public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new FunctionWithContext<>(snapshot, input -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return input; }, snapshot -> snapshotHolder[0] = snapshot).apply("input")); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java similarity index 94% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java index 37217035..4c761bc3 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/PredicateWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -25,7 +26,6 @@ import java.io.Closeable; import java.io.IOException; import java.util.Objects; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.function.Supplier; @@ -98,22 +98,22 @@ public void testTestWithoutSnapshotSupplier() { @Test public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new PredicateWithContext<>(snapshot, input -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return true; }, snapshot -> snapshotHolder[0] = snapshot).test("input")); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java similarity index 91% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java index 63f63f60..f2adff7d 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/RunnableWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.function.Supplier; import static org.hamcrest.MatcherAssert.assertThat; @@ -96,17 +96,17 @@ public void testRunWithoutSnapshotSupplier() { @Test public void testRunWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(new RunnableWithContext(snapshot, - () -> DummyContextManager.setCurrentValue("New value"), + () -> DummyContext.setCurrentValue("New value"), snapshot -> snapshotHolder[0] = snapshot)); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } verify(snapshot).reactivate(); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java similarity index 81% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java index 565beed5..9b1fb443 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/SupplierWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -77,24 +77,24 @@ public void testGetNull() { @Test public void testGetWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - Supplier> supplier = new SupplierWithContext<>(snapshot, () -> { + Supplier supplier = new SupplierWithContext<>(snapshot, () -> { try { - return DummyContextManager.currentValue(); + return DummyContext.currentValue(); } finally { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); } }, s -> snapshotHolder[0] = s); - Future> future = unawareThreadpool.submit(supplier::get); - assertThat(future.get(), is(Optional.empty())); + Future future = unawareThreadpool.submit(supplier::get); + assertThat(future.get(), is(nullValue())); verify(snapshot).reactivate(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java similarity index 90% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java index ec414dbf..48005a91 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/UnaryOperatorWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; +import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -24,7 +25,6 @@ import java.io.Closeable; import java.io.IOException; -import java.util.Optional; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -95,22 +95,22 @@ public void testApplyWithoutSnapshotSupplier() { @Test public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; - DummyContextManager.setCurrentValue("Old value"); + DummyContext.setCurrentValue("Old value"); Thread t = new Thread(() -> new UnaryOperatorWithContext<>(snapshot, input -> { - DummyContextManager.setCurrentValue("New value"); + DummyContext.setCurrentValue("New value"); return input; }, snapshot -> snapshotHolder[0] = snapshot).apply("input")); t.start(); t.join(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); try (Closeable reactivation = snapshotHolder[0].reactivate()) { - assertThat(DummyContextManager.currentValue(), is(Optional.of("New value"))); + assertThat(DummyContext.currentValue(), is("New value")); } - assertThat(DummyContextManager.currentValue(), is(Optional.of("Old value"))); + assertThat(DummyContext.currentValue(), is("Old value")); verify(snapshot).reactivate(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java similarity index 84% rename from context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java index 576636ec..acbe44dd 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/functions/WrapperWithContextAndConsumerTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java @@ -13,18 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.functions; +package nl.talsmasoftware.context.core.function; import nl.talsmasoftware.context.api.ContextSnapshot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Optional; import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -36,7 +37,6 @@ public class WrapperWithContextAndConsumerTest { private ContextSnapshot snapshot; @BeforeEach - @SuppressWarnings("unchecked") public void setUp() { snapshot = mock(ContextSnapshot.class); } @@ -50,14 +50,14 @@ public void verifyMocks() { @Deprecated public void testDeprecatedConsumerMethod() { assertThat(new WrapperWithContextAndConsumer(snapshot, "string", null) { - }.consumer(), is(Optional.empty())); + }.contextSnapshotConsumer, is(nullValue())); final Consumer contextSnapshotConsumer = snapshot -> { }; assertThat(new WrapperWithContextAndConsumer(snapshot, "string", contextSnapshotConsumer) { - }.consumer(), - is(Optional.of(contextSnapshotConsumer))); + }.contextSnapshotConsumer, + is(sameInstance(contextSnapshotConsumer))); } } diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java similarity index 90% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java index 8f14990e..b6108fff 100644 --- a/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContext.java @@ -23,7 +23,7 @@ */ public final class DummyContext extends AbstractThreadLocalContext { private static final ThreadLocal INSTANCE = - AbstractThreadLocalContext.threadLocalInstanceOf(DummyContext.class); + threadLocalInstanceOf(DummyContext.class); public DummyContext(String newValue) { super(newValue); @@ -39,6 +39,10 @@ public static String currentValue() { return currentContext != null ? currentContext.getValue() : null; } + public static void setCurrentValue(String value) { + new DummyContext(value); + } + public static void reset() { INSTANCE.remove(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java index b2535253..f1b766bf 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/DummyContextManager.java @@ -17,62 +17,42 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; -import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; - -import java.util.Optional; -import java.util.logging.Logger; +/** + * Trivial manager around the {@link DummyContext} implementation to be registered as service provider. + * + * @author Sjoerd Talsma + */ public class DummyContextManager implements ContextManager { - private static final Logger LOGGER = Logger.getLogger(DummyContextManager.class.getName()); public Context initializeNewContext(String value) { - return setCurrentValue(value); + return new DummyContext(value); } public String getActiveContextValue() { - return currentValue().orElse(null); + return DummyContext.currentValue(); } public void clear() { - clearAllContexts(); + DummyContext.reset(); } - public static Optional currentValue() { - Optional currentValue = Optional.ofNullable(DummyContext.current()).map(Context::getValue); - LOGGER.fine(() -> "Current value in " + Thread.currentThread() + ": " + currentValue); - return currentValue; + public static void clearAllContexts() { + DummyContext.reset(); } - /** - * For easier testing - * - * @param value The new value to be set (can be null) - * @return A context to optionally be closed - */ - public static Context setCurrentValue(String value) { - LOGGER.fine(() -> "Setting current value in " + Thread.currentThread() + ": " + value); - return new DummyContext(value); + @Override + public int hashCode() { + return DummyContextManager.class.hashCode(); } - /** - * For easier testing - */ - public static void clearAllContexts() { - LOGGER.fine(() -> "Clearing values in " + Thread.currentThread() + ", currently: " + DummyContext.current()); - DummyContext.clear(); + @Override + public boolean equals(Object other) { + return this == other || other instanceof DummyContextManager; } - private static final class DummyContext extends AbstractThreadLocalContext { - private DummyContext(String newValue) { - super(newValue); - } - - private static void clear() { - AbstractThreadLocalContext.threadLocalInstanceOf(DummyContext.class).remove(); - } - - private static Context current() { - return AbstractThreadLocalContext.current(DummyContext.class); - } + @Override + public String toString() { + return getClass().getSimpleName(); } } diff --git a/context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java similarity index 100% rename from context-propagation-api/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java rename to context-propagation-core/src/test/java/nl/talsmasoftware/context/dummy/ThrowingContextManager.java diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java deleted file mode 100644 index 0e0b24ca..00000000 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/futures/ContextAwareCompletableFutureTest.java +++ /dev/null @@ -1,1831 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.futures; - -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.api.ContextSnapshot; -import nl.talsmasoftware.context.core.ContextManagers; -import nl.talsmasoftware.context.dummy.DummyContextManager; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Supplier; - -import static java.util.concurrent.CompletableFuture.completedFuture; -import static nl.talsmasoftware.context.futures.ContextAwareCompletableFuture.supplyAsync; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; - -/** - * @author Sjoerd Talsma - */ -public class ContextAwareCompletableFutureTest { - private static final Random RND = new Random(); - private static final DummyContextManager manager = new DummyContextManager(); - private static final ExecutorService contextUnawareThreadpool = Executors.newCachedThreadPool(); - - @BeforeEach - @AfterEach - public void clearDummyContext() { - DummyContextManager.clearAllContexts(); - } - - private static void assertContext(String expectedValue) { - assertThat("Active context value", manager.getActiveContextValue(), is(expectedValue)); - } - - private static Supplier stringSupplier(String name, String requiredContext) { - return () -> { - assertContext(requiredContext); - manager.initializeNewContext(name); // intentionally not closed here - assertContext(name); - assertDoesNotThrow(() -> Thread.sleep(50 + RND.nextInt(200))); - return String.format(name + " (Thread: %s)", Thread.currentThread().getName()); - }; - } - - @Test - public void testDefaultConstructor() throws ExecutionException, InterruptedException { - Context ctx = manager.initializeNewContext("foo"); - CompletableFuture future1 = new ContextAwareCompletableFuture<>(); // should have a new snapshot with foo - ctx.close(); - - CompletableFuture future2 = future1.thenApply(value -> manager.getActiveContextValue() + value); - assertThat(manager.getActiveContextValue(), is(nullValue())); - assertThat(future1.isDone(), is(false)); - assertThat(future2.isDone(), is(false)); - - assertThat(future1.complete("bar"), is(true)); - assertThat(future1.isDone(), is(true)); - assertThat(future2.isDone(), is(true)); - assertThat(future2.get(), is("foobar")); - } - - @Test - public void testSupplyAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Vincent Vega")) { - Future> future = supplyAsync(DummyContextManager::currentValue); - assertThat(future.get().get(), is("Vincent Vega")); - } - } - - @Test - public void testSupplyAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = supplyAsync(DummyContextManager::currentValue, contextUnawareThreadpool); - assertThat(future.get().get(), is("Marcellus Wallace")); - } - } - - @Test - public void testSupplyAsync_executor_snapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Vincent Vega")) { - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Jules Winnfield"); - assertContext("Jules Winnfield"); - - Future> future = supplyAsync(DummyContextManager::currentValue, contextUnawareThreadpool, snapshot); - assertThat(future.get().get(), is("Vincent Vega")); - } - } - - @Test - public void testSupplyAsync_executor_snapshot_takeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Vincent Vega")) { - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Jules Winnfield"); - assertContext("Jules Winnfield"); - - ContextAwareCompletableFuture> future = supplyAsync(() -> { - try { - return DummyContextManager.currentValue(); - } finally { - DummyContextManager.setCurrentValue("Marcellus Wallace"); - } - }, contextUnawareThreadpool, snapshot, true); - - assertThat(future.get(), is(Optional.of("Vincent Vega"))); - assertThat(future.thenApply(x -> DummyContextManager.currentValue()).get(), - is(Optional.of("Marcellus Wallace"))); - } - } - - @Test - public void testRunAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Mia Wallace")) { - ContextAwareCompletableFuture future = ContextAwareCompletableFuture - .runAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Mia Wallace")))); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testRunAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync( - () -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Jimmie"))), - contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testRunAsync_executor_snapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pumpkin")) { - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Honey Bunny"); - assertContext("Honey Bunny"); - - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync( - () -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Pumpkin"))), - contextUnawareThreadpool, - snapshot); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testRunAsync_executor_snapshot_takeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pumpkin")) { - ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Honey Bunny"); - assertContext("Honey Bunny"); - - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.runAsync( - () -> { - try { - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pumpkin"))); - } finally { - DummyContextManager.setCurrentValue("Bad Motherfucker"); - } - }, - contextUnawareThreadpool, - snapshot, - true); - future.get(); // trigger asynchronous assertion - future.thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Bad Motherfucker")))).get(); - } - } - - @Test - public void testThenApply() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Jimmie")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Bonnie")) - .thenApply(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Jimmie"))); - } - - try (Context ctx = manager.initializeNewContext("Jimmie")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Bonnie"), null, null, true) - .thenApply(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Bonnie"))); - } - } - - @Test - public void testThenApplyAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos")) - .thenApplyAsync(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get().get(), is("Butch")); - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos"), null, null, true) - .thenApplyAsync(voidvalue -> DummyContextManager.currentValue()); - assertThat(future.get().get(), is("Esmerelda Villalobos")); - } - } - - @Test - public void testThenApplyAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Maynard")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Zed")) - .thenApplyAsync(voidvalue -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get().get(), is("Maynard")); - } - - try (Context ctx = manager.initializeNewContext("Maynard")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Zed"), null, null, true) - .thenApplyAsync(voidvalue -> DummyContextManager.currentValue(), contextUnawareThreadpool); - assertThat(future.get().get(), is("Zed")); - } - } - - @Test - public void testThenApplyAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Bonnie")) - .takeNewSnapshot() - .thenApply(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .thenAccept(s -> { - assertThat(s, is("Jimmie")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Jimmie"))); - }) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Jimmie")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Bonnie"), null, null, true) - .thenApply(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .thenAccept(s -> { - assertThat(s, is("Bonnie")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Bonnie"))); - }) - .get(); - } - } - - @Test - public void testThenApplyAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos")) - .takeNewSnapshot() - .thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .thenAccept(s -> { - assertThat(s, is("Butch")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch"))); - }) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Esmerelda Villalobos"), null, null, true) - .thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .thenAccept(s -> { - assertThat(s, is("Esmerelda Villalobos")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Esmerelda Villalobos"))); - }) - .get(); - } - } - - @Test - public void testThenApplyAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Maynard")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Zed")) - .takeNewSnapshot() - .thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }, contextUnawareThreadpool) - .thenAccept(s -> { - assertThat(s, is("Maynard")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Maynard"))); - }) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Maynard")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Zed"), null, null, true) - .thenApplyAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }, contextUnawareThreadpool) - .thenAccept(s -> { - assertThat(s, is("Zed")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("-Zed"))); - }) - .get(); - } - } - - @Test - public void testThenAccept() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("The Gimp")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch")) - .thenAccept(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("The Gimp")))); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("The Gimp")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch"), null, null, true) - .thenAccept(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenAcceptAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Fabienne")) - .thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Fabienne"), null, null, true) - .thenAcceptAsync(voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Fabienne")))); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenAcceptAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Marvin")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Winston Wolfe")) - .thenAcceptAsync( - voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Marvin"))), - contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Marvin")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Winston Wolfe"), null, null, true) - .thenAcceptAsync( - voidvalue -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Winston Wolfe"))), - contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenAcceptAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("The Gimp")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch")) - .takeNewSnapshot() - .thenAccept(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("The Gimp")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-The Gimp")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("The Gimp")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch"), null, null, true) - .thenAccept(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenAcceptAsynAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Fabienne")) - .takeNewSnapshot() - .thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Fabienne"), null, null, true) - .thenAcceptAsync(voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Fabienne")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Fabienne")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenAcceptAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Marvin")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Winston Wolfe")) - .takeNewSnapshot() - .thenAcceptAsync( - voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Marvin")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Marvin")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Winston Wolfe"), null, null, true) - .thenAcceptAsync( - voidvalue -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Winston Wolfe")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Winston Wolfe")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRun() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Lance")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Jody")) - .thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Lance")))); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Lance")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Jody"), null, null, true) - .thenRun(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Jody")))); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRunAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Ringo")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Yolanda")) - .thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Ringo")))); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Ringo")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Yolanda"), null, null, true) - .thenRunAsync(() -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Yolanda")))); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRunAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch")) - .thenRunAsync( - () -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Capt. Koons"))), - contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch"), null, null, true) - .thenRunAsync( - () -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch"))), - contextUnawareThreadpool); - future.get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRunAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Lance")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Jody")) - .takeNewSnapshot() - .thenRun(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Lance")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Lance")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Lance")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Jody"), null, null, true) - .thenRun(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Jody")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Jody")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRunAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Ringo")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Yolanda")) - .takeNewSnapshot() - .thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Ringo")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Ringo")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Ringo")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Yolanda"), null, null, true) - .thenRunAsync(() -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Yolanda")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Yolanda")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testThenRunAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch")) - .takeNewSnapshot() - .thenRunAsync( - () -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Capt. Koons")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Capt. Koons")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Capt. Koons")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Butch"), null, null, true) - .thenRunAsync( - () -> { - String val = DummyContextManager.currentValue().get(); - assertThat(val, is("Butch")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Butch")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testWhenComplete() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Floyd")) - .whenComplete((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Floyd"), null, null, true) - .whenComplete((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Floyd")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testWhenCompleteAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Zed")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Pipe hittin' niggers")) - .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Zed")))) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Zed")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Pipe hittin' niggers"), null, null, true) - .whenCompleteAsync((voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Pipe hittin' niggers")))) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testWhenCompleteAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Floyd")) - .whenCompleteAsync( - (voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Butch"))), - contextUnawareThreadpool) - .get(); // trigger asynchronous assertion - } - - try (Context ctx = manager.initializeNewContext("Butch")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Floyd"), null, null, true) - .whenCompleteAsync( - (voidValue, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("Floyd"))), - contextUnawareThreadpool) - .get(); // trigger asynchronous assertion - } - } - - @Test - public void testHandle() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) - .get(), - is("Trudy")); - } - } - - @Test - public void testHandleAsync() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handleAsync((voidValue, throwable) -> manager.getActiveContextValue()) - .get(), - is("Trudy")); - } - } - - @Test - public void testHandleAsync_executor() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .handleAsync( - (voidValue, throwable) -> manager.getActiveContextValue(), - contextUnawareThreadpool) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handleAsync( - (voidValue, throwable) -> manager.getActiveContextValue(), - contextUnawareThreadpool) - .get(), - is("Trudy")); - } - } - - @Test - public void testHandleAndTakeSnapshot() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .takeNewSnapshot() - .handle((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, throwable) -> assertContext("-Jody")) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handle((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, throwable) -> assertContext("-Trudy")) - .get(), - is("Trudy")); - } - } - - @Test - public void testHandleAsyncAndTakeSnapshot() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .takeNewSnapshot() - .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, throwable) -> assertContext("-Jody")) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, throwable) -> assertContext("-Trudy")) - .get(), - is("Trudy")); - } - } - - @Test - public void testHandleAsyncAndTakeSnapshot_executor() throws ExecutionException, InterruptedException { - final RuntimeException exception = new RuntimeException("Bad Motherfucker"); - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }) - .takeNewSnapshot() - .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }, contextUnawareThreadpool) - .whenComplete((result, throwable) -> assertContext("-Jody")) - .get(), - is("Jody")); - } - - try (Context ctx = manager.initializeNewContext("Jody")) { - assertThat(ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Trudy"); - throw exception; - }, null, null, true) - .handleAsync((voidValue, throwable) -> { - String val = manager.getActiveContextValue(); - manager.initializeNewContext("-" + val); - return val; - }, contextUnawareThreadpool) - .whenComplete((result, throwable) -> assertContext("-Trudy")) - .get(), - is("Trudy")); - } - } - - @Test - public void testExceptionally() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Gringo")) { - ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); - throw new RuntimeException("Bad Motherfucker"); - }) - .exceptionally(ex -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Gringo")); - return null; - }) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Gringo")) { - ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); - throw new RuntimeException("Bad Motherfucker"); - }, null, null, true) - .exceptionally(ex -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Jules Winnfield")); - return null; - }) - .get(); - } - } - - @Test - public void testExceptionallyAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Gringo")) { - ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); - throw new RuntimeException("Bad Motherfucker"); - }) - .takeNewSnapshot() - .exceptionally(ex -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Gringo")); - manager.initializeNewContext("-" + val); - return null; - }) - .thenAccept(aVoid -> assertContext("-Gringo")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Gringo")) { - ContextAwareCompletableFuture - .runAsync(() -> { - manager.initializeNewContext("Jules Winnfield"); - throw new RuntimeException("Bad Motherfucker"); - }, null, null, true) - .exceptionally(ex -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Jules Winnfield")); - manager.initializeNewContext("-" + val); - return null; - }) - .thenAccept(aVoid -> assertContext("-Jules Winnfield")) - .get(); - } - } - - @Test - public void testThenCombine() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Vincent Vega")) - .thenCombine( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), - (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Marcellus Wallace"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Marcellus Wallace"))); - } - - try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Vincent Vega"), null, null, true) - .thenCombine( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), - (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Vincent Vega"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Marcellus Wallace"))); - } - } - - @Test - public void testThenCombineAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin")) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Brett"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - - try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> DummyContextManager.currentValue()); - assertThat(future.get(), is(Optional.of("Marvin"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - } - - @Test - public void testThenCombineAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin")) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> DummyContextManager.currentValue(), - contextUnawareThreadpool); - assertThat(future.get(), is(Optional.of("Brett"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - - try (Context ctx = manager.initializeNewContext("Brett")) { - Future> future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> DummyContextManager.currentValue(), - contextUnawareThreadpool); - assertThat(future.get(), is(Optional.of("Marvin"))); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - } - - @Test - public void testThenCombineAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Vincent Vega")) - .takeNewSnapshot() - .thenCombine( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marcellus Wallace")))); - - assertThat(future.get(), is("Marcellus Wallace")); - } - - try (Context ctx = manager.initializeNewContext("Marcellus Wallace")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Vincent Vega"), null, null, true) - .thenCombine( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Jules Winnfield")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, exception) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Vincent Vega")))); - - assertThat(future.get(), is("Vincent Vega")); - } - } - - @Test - public void testThenCombineAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin")) - .takeNewSnapshot() - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Brett")))); - - assertThat(future.get(), is("Brett")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - - try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }) - .whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))); - - assertThat(future.get(), is("Marvin")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - } - - @Test - public void testThenCombineAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin")) - .takeNewSnapshot() - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }, - contextUnawareThreadpool) - .whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Brett")))); - - assertThat(future.get(), is("Brett")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - - try (Context ctx = manager.initializeNewContext("Brett")) { - Future future = ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Marvin"), null, null, true) - .thenCombineAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Flock of Seagulls")), - (voidA, voidB) -> { - String val = DummyContextManager.currentValue().get(); - manager.initializeNewContext("-" + val); - return val; - }, - contextUnawareThreadpool) - .whenComplete((result, exeption) -> assertThat(DummyContextManager.currentValue(), is(Optional.of("-Marvin")))); - - assertThat(future.get(), is("Marvin")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Brett"))); - } - } - - @Test - public void testThenAcceptBoth() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBoth(completedFuture("Tarantino"), - (Void voidA, String stringB) -> - assertThat(manager.getActiveContextValue() + stringB, - is("QuentinTarantino"))) - .get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); - } - } - - @Test - public void testThenAcceptBothAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBothAsync(completedFuture("Tarantino"), - (Void voidA, String stringB) -> - assertThat(manager.getActiveContextValue() + stringB, - is("QuentinTarantino"))) - .get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); - } - } - - @Test - public void testThenAcceptBothAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBothAsync(completedFuture("Tarantino"), - (Void voidA, String stringB) -> - assertThat(manager.getActiveContextValue() + stringB, - is("QuentinTarantino")), - contextUnawareThreadpool) - .get(); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Pulp Fiction"))); - } - } - - @Test - public void testThenAcceptBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue()) - .takeNewSnapshot() - .thenAcceptBoth(completedFuture(" by Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBoth(completedFuture(" by Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Quentin by Tarantino")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-Quentin by Tarantino")) - .get(); - } - } - - @Test - public void testThenAcceptBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue()) - .takeNewSnapshot() - .thenAcceptBoth(completedFuture(" by Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBoth(completedFuture("Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("QuentinTarantino")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-QuentinTarantino")) - .get(); - } - } - - @Test - public void testThenAcceptBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue()) - .takeNewSnapshot() - .thenAcceptBothAsync(completedFuture(" by Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("Pulp Fiction by Tarantino")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertContext("-Pulp Fiction by Tarantino")) - .get(); - assertContext("Pulp Fiction"); - } - - try (Context ctx = manager.initializeNewContext("Pulp Fiction")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Quentin").getValue(), null, null, true) - .thenAcceptBothAsync(completedFuture("Tarantino"), - (Void voidA, String stringB) -> { - String val = manager.getActiveContextValue() + stringB; - assertThat(val, is("QuentinTarantino")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertContext("-QuentinTarantino")) - .get(); - assertContext("Pulp Fiction"); - } - } - - @Test - public void testRunAfterBoth() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .runAfterBoth( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("French Fries")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBoth( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("Ketchup")) - .get(); - } - } - - @Test - public void testRunAfterBothAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("French Fries")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("Ketchup")) - .get(); - } - } - - @Test - public void testRunAfterBothAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("French Fries"), - contextUnawareThreadpool) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> assertContext("Ketchup"), - contextUnawareThreadpool) - .get(); - } - } - - @Test - public void testRunAfterBothAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .takeNewSnapshot() - .runAfterBoth( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-French Fries")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBoth( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-Ketchup")) - .get(); - } - } - - @Test - public void testRunAfterBothAsyncAndTakeNewSnapshot() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .takeNewSnapshot() - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-French Fries")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); - }) - .thenAccept(aVoid -> assertContext("-Ketchup")) - .get(); - } - } - - @Test - public void testRunAfterBothAsyncAndTakeNewSnapshot_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup")) - .takeNewSnapshot() - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("French Fries")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertContext("-French Fries")) - .get(); - } - - try (Context ctx = manager.initializeNewContext("French Fries")) { - ContextAwareCompletableFuture - .runAsync(() -> manager.initializeNewContext("Ketchup"), null, null, true) - .runAfterBothAsync( - ContextAwareCompletableFuture.runAsync(() -> manager.initializeNewContext("Mayonaise")), - () -> { - String val = manager.getActiveContextValue(); - assertThat(val, is("Ketchup")); - manager.initializeNewContext("-" + val); - }, - contextUnawareThreadpool) - .thenAccept(aVoid -> assertContext("-Ketchup")) - .get(); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testApplyToEither(boolean takeNewSnapshot) throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1 - .takeNewSnapshot(takeNewSnapshot) - .applyToEither(future2, - input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContextValue())); - - // verify - assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testApplyToEitherAsync(boolean takeNewSnapshot) throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1 - .takeNewSnapshot(takeNewSnapshot) - .applyToEitherAsync( - future2, - input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContextValue())); - - // verify - assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testApplyToEitherAsync_executor(boolean takeNewSnapshot) throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1 - .takeNewSnapshot(takeNewSnapshot) - .applyToEitherAsync( - future2, - input -> String.format("Winner: %s, Thread: %s, Context: %s", - input, Thread.currentThread().getName(), manager.getActiveContextValue()), - contextUnawareThreadpool); - - // verify - assertThat(result.get(), allOf(startsWith("Winner: Function"), endsWith("Context: Parent"))); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testAcceptEither(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .acceptEither( - future2, - input -> { - assertThat(input, startsWith("Function")); - assertContext("Parent"); - }); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testAcceptEitherAsync(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .acceptEitherAsync( - future2, - input -> { - assertThat(input, startsWith("Function")); - assertContext("Parent"); - }); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testAcceptEitherAsync_executor(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .acceptEitherAsync( - future2, - input -> { - assertThat(input, startsWith("Function")); - assertContext("Parent"); - }, - contextUnawareThreadpool); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testRunAfterEither(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .runAfterEither(future2, () -> assertContext("Parent")); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testRunAfterEitherAsync(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .runAfterEitherAsync(future2, () -> assertContext("Parent")); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - public void testRunAfterEitherAsync_executor(boolean takeNewSnapshot) { - try (Context ctx = manager.initializeNewContext("Parent")) { - // prepare - ContextAwareCompletableFuture future1 = supplyAsync(stringSupplier("Function 1", "Parent")); - ContextAwareCompletableFuture future2 = supplyAsync(stringSupplier("Function 2", "Parent")); - - // execute - Future result = future1.takeNewSnapshot(takeNewSnapshot) - .runAfterEitherAsync(future2, () -> assertContext("Parent"), contextUnawareThreadpool); - - // verify - assertDoesNotThrow(() -> result.get()); - } - } - - @Test - public void testThenCompose() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }) - .thenCompose(value -> supplyAsync( - () -> value + manager.getActiveContextValue())) - .get(), - is("JohnJohn")); - } - - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }, null, null, true) - .thenCompose(value -> supplyAsync( - () -> value + manager.getActiveContextValue())) - .get(), - is("JohnTravolta")); - } - } - - @Test - public void testThenComposeAsync() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }) - .thenComposeAsync(value -> supplyAsync( - () -> value + manager.getActiveContextValue())) - .get(), - is("JohnJohn")); - } - - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }, null, null, true) - .thenComposeAsync(value -> supplyAsync( - () -> value + manager.getActiveContextValue())) - .get(), - is("JohnTravolta")); - } - } - - @Test - public void testThenComposeAsync_executor() throws ExecutionException, InterruptedException { - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }) - .thenComposeAsync( - value -> completedFuture(value + manager.getActiveContextValue()), - contextUnawareThreadpool) - .get(), - is("JohnJohn")); - } - - try (Context ctx = manager.initializeNewContext("John")) { - assertThat(supplyAsync(() -> { - String current = manager.getActiveContextValue(); - manager.initializeNewContext("Travolta"); - return current; - }, null, null, true) - .thenComposeAsync( - value -> completedFuture(value + manager.getActiveContextValue()), - contextUnawareThreadpool) - .get(), - is("JohnTravolta")); - } - } - - @Test - public void testTimingIssue55() throws ExecutionException, InterruptedException, TimeoutException { - try (Context ctx = manager.initializeNewContext("Vincent Vega")) { - final CountDownLatch latch1 = new CountDownLatch(1), latch2 = new CountDownLatch(1); - ContextAwareCompletableFuture future1 = supplyAsync(() -> { - String result = DummyContextManager.currentValue().orElse("NO VALUE"); - DummyContextManager.setCurrentValue("Jules Winnfield"); - waitFor(latch1); - return result; - }, null, null, true); - ContextAwareCompletableFuture future2 = future1.thenApplyAsync(value -> { - String result = value + ", " + DummyContextManager.currentValue().orElse("NO VALUE"); - DummyContextManager.setCurrentValue("Marcellus Wallace"); - waitFor(latch2); - return result; - }); - Future future3 = future2.thenApplyAsync(value -> - value + ", " + DummyContextManager.currentValue().orElse("NO VALUE")); - - assertThat("Future creation may not block on previous stages", future1.isDone(), is(false)); - assertThat("Future creation may not block on previous stages", future2.isDone(), is(false)); - assertThat("Future creation may not block on previous stages", future3.isDone(), is(false)); - - latch1.countDown(); - future1.get(500, TimeUnit.MILLISECONDS); - assertThat("Future creation may not block on previous stages", future1.isDone(), is(true)); - assertThat("Future creation may not block on previous stages", future2.isDone(), is(false)); - assertThat("Future creation may not block on previous stages", future3.isDone(), is(false)); - - latch2.countDown(); - future2.get(500, TimeUnit.MILLISECONDS); - assertThat("Future creation may not block on previous stages", future2.isDone(), is(true)); - assertThat(future3.get(500, TimeUnit.MILLISECONDS), is("Vincent Vega, Jules Winnfield, Marcellus Wallace")); - assertThat(DummyContextManager.currentValue(), is(Optional.of("Vincent Vega"))); - } - } - - @Test - public void testAllOf() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); - CompletableFuture cf1 = new CompletableFuture<>(); - CompletableFuture cf2 = new ContextAwareCompletableFuture() - .takeNewSnapshot() - .thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored - return s; - }); - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); - - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); - assertThat(result.isDone(), is(false)); - cf1.complete("Value 1"); - assertThat(result.isDone(), is(false)); - cf2.complete("Value 2"); - assertThat(result.get(), is("Vincent Vega")); - } - - @Test - public void testAllOfWithSpecificSnapshot() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); - final ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Marcellus Wallace"); - CompletableFuture cf1 = new CompletableFuture<>(); - CompletableFuture cf2 = new ContextAwareCompletableFuture() - .takeNewSnapshot() - .thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored - return s; - }); - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.allOf(snapshot, cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); - - ContextAwareCompletableFuture result = future.thenApplyAsync(aVoid -> manager.getActiveContextValue()); - assertThat(result.isDone(), is(false)); - cf1.complete("Value 1"); - assertThat(result.isDone(), is(false)); - cf2.complete("Value 2"); - assertThat(result.get(), is("Vincent Vega")); - } - - @Test - public void testAnyOf() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); - CompletableFuture cf1 = new CompletableFuture<>(); - CompletableFuture cf2 = new ContextAwareCompletableFuture() - .takeNewSnapshot() - .thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored - return s; - }); - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); - - ContextAwareCompletableFuture result = future - .thenApplyAsync(s -> manager.getActiveContextValue()); - assertThat(result.isDone(), is(false)); - cf2.complete("Value 2"); - assertThat(result.get(), is("Vincent Vega")); - assertThat(future.get(), is("Value 2")); - } - - @Test - public void testAnyOfWithSpecificSnapshot() throws ExecutionException, InterruptedException { - manager.initializeNewContext("Vincent Vega"); - final ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - manager.initializeNewContext("Marcellus Wallace"); - CompletableFuture cf1 = new CompletableFuture<>(); - CompletableFuture cf2 = new ContextAwareCompletableFuture() - .takeNewSnapshot() - .thenApply(s -> { - manager.initializeNewContext("-" + s); // This context should be ignored - return s; - }); - ContextAwareCompletableFuture future = ContextAwareCompletableFuture.anyOf(snapshot, cf1, cf2); - manager.initializeNewContext("Jules Winnfield"); - - ContextAwareCompletableFuture result = future - .thenApplyAsync(s -> manager.getActiveContextValue()); - assertThat(result.isDone(), is(false)); - cf1.complete("Value 1"); - assertThat(result.get(), is("Vincent Vega")); - assertThat(future.get(), is("Value 1")); - } - - private static void waitFor(CountDownLatch latch) { - try { - latch.await(5, TimeUnit.SECONDS); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - throw new AssertionError("Interrupted waiting for latch.", ie); - } - } -} diff --git a/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager index c4a9ba40..6f9a5447 100644 --- a/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ b/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -1 +1,3 @@ nl.talsmasoftware.context.dummy.DummyContextManager +nl.talsmasoftware.context.dummy.ThrowingContextManager +nl.talsmasoftware.context.clearable.ClearableDummyContextManager diff --git a/context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer similarity index 100% rename from context-propagation-api/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer rename to context-propagation-core/src/test/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer diff --git a/context-propagation-metrics/pom.xml b/context-propagation-metrics/pom.xml index f25ac492..2679246f 100644 --- a/context-propagation-metrics/pom.xml +++ b/context-propagation-metrics/pom.xml @@ -49,5 +49,12 @@ metrics-core ${metrics.version} + + + ${project.groupId} + context-propagation-core + ${project.version} + test + diff --git a/context-propagation-micrometer/pom.xml b/context-propagation-micrometer/pom.xml index 0e90a38f..4fbd2dcf 100644 --- a/context-propagation-micrometer/pom.xml +++ b/context-propagation-micrometer/pom.xml @@ -51,6 +51,13 @@ micrometer-core ${micrometer.version} + + + ${project.groupId} + context-propagation-core + ${project.version} + test + diff --git a/locale-context/pom.xml b/locale-context/pom.xml index 39bd342a..df246592 100644 --- a/locale-context/pom.xml +++ b/locale-context/pom.xml @@ -16,7 +16,8 @@ limitations under the License. --> - + 4.0.0 @@ -39,7 +40,7 @@ ${project.groupId} - context-propagation-api + context-propagation-core ${project.version} diff --git a/log4j2-propagation/pom.xml b/log4j2-propagation/pom.xml index fd0e4422..8ecfa438 100644 --- a/log4j2-propagation/pom.xml +++ b/log4j2-propagation/pom.xml @@ -41,17 +41,23 @@ context-propagation-api ${project.version} - org.apache.logging.log4j log4j-api ${log4j2.version} + org.apache.logging.log4j log4j-core ${log4j2.version} test + + ${project.groupId} + context-propagation-core + ${project.version} + test + diff --git a/opentracing-span-propagation/pom.xml b/opentracing-span-propagation/pom.xml index bd48a94f..fe95ffe6 100644 --- a/opentracing-span-propagation/pom.xml +++ b/opentracing-span-propagation/pom.xml @@ -41,7 +41,7 @@ ${project.groupId} - context-propagation-api + context-propagation-core ${project.version} @@ -49,6 +49,7 @@ opentracing-util ${opentracing-api.version} + io.opentracing opentracing-mock diff --git a/servletrequest-propagation/pom.xml b/servletrequest-propagation/pom.xml index 6f5bc09a..a3a8634d 100644 --- a/servletrequest-propagation/pom.xml +++ b/servletrequest-propagation/pom.xml @@ -44,6 +44,7 @@ context-propagation-api ${project.version} + javax.servlet javax.servlet-api @@ -51,5 +52,12 @@ provided true + + + ${project.groupId} + context-propagation-core + ${project.version} + test + diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java index 0a5e1cb9..e954865e 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java +++ b/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java @@ -15,26 +15,49 @@ */ package nl.talsmasoftware.context.servletrequest; -import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.api.Context; import javax.servlet.ServletRequest; +import java.util.concurrent.atomic.AtomicBoolean; /** - * Simple (unstacked) context using a ThreadLocal containing the current {@link ServletRequest}. + * Simple context using a ThreadLocal containing the current {@link ServletRequest}. * * @author Sjoerd Talsma */ -final class ServletRequestContext extends AbstractThreadLocalContext { - private static final ThreadLocal CONTEXT = - AbstractThreadLocalContext.threadLocalInstanceOf(ServletRequestContext.class); +final class ServletRequestContext implements Context { + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + final ServletRequestContext previous; + final ServletRequest value; + final AtomicBoolean closed; ServletRequestContext(ServletRequest servletRequest) { - super(servletRequest); + previous = CONTEXT.get(); + value = servletRequest; + closed = new AtomicBoolean(false); + CONTEXT.set(this); + } + + @Override + public ServletRequest getValue() { + return closed.get() ? null : value; + } + + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + CONTEXT.set(previous); + } + } + + @Override + public String toString() { + return getClass().getSimpleName() + (closed.get() ? "{closed}" : "{value=" + value + '}'); } static ServletRequest currentValue() { ServletRequestContext current = CONTEXT.get(); - return current != null ? current.getValue() : null; + return current != null ? current.value : null; } static void clear() { @@ -46,4 +69,5 @@ static void clear() { CONTEXT.remove(); } } + } diff --git a/slf4j-propagation/pom.xml b/slf4j-propagation/pom.xml index 0af97147..72ad421b 100644 --- a/slf4j-propagation/pom.xml +++ b/slf4j-propagation/pom.xml @@ -16,7 +16,8 @@ limitations under the License. --> - + 4.0.0 @@ -42,13 +43,18 @@ context-propagation-api ${project.version} - org.slf4j slf4j-api ${slf4j.version} + + ${project.groupId} + context-propagation-core + ${project.version} + test + ch.qos.logback logback-classic diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java index 0afa1565..950c716b 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java +++ b/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java @@ -17,7 +17,6 @@ import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; -import nl.talsmasoftware.context.core.ContextManagers; import org.slf4j.MDC; import java.util.Map; @@ -39,7 +38,7 @@ * *

    * This manager does not implement the optional {@link #clear()} method. - * {@link ContextManagers#clearActiveContexts()} will therefore not clear the {@linkplain MDC}. + * {@code ContextManagers.clearActiveContexts()} will therefore not clear the {@linkplain MDC}. * Please use {@linkplain MDC#clear()} explicitly to do that. * * @author Sjoerd Talsma diff --git a/spring-security-context/pom.xml b/spring-security-context/pom.xml index 96d23f03..b721c253 100644 --- a/spring-security-context/pom.xml +++ b/spring-security-context/pom.xml @@ -16,7 +16,8 @@ limitations under the License. --> - + 4.0.0 @@ -48,5 +49,12 @@ spring-security-core ${spring-security.version} + + + ${project.groupId} + context-propagation-core + ${project.version} + test + From fe24f46837b2ae9eb6af76770e82d72c2cd25cd5 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 14:27:17 +0100 Subject: [PATCH 22/41] Remove core dependency from locale-context module. Signed-off-by: Sjoerd Talsma --- locale-context/pom.xml | 7 ++ .../context/locale/LocaleContext.java | 108 +++++++++++++----- .../context/locale/LocaleContextManager.java | 18 +-- .../locale/LocaleContextManagerTest.java | 24 ++-- readme.md | 1 + 5 files changed, 105 insertions(+), 53 deletions(-) diff --git a/locale-context/pom.xml b/locale-context/pom.xml index df246592..c8c52f34 100644 --- a/locale-context/pom.xml +++ b/locale-context/pom.xml @@ -38,10 +38,17 @@ + + ${project.groupId} + context-propagation-api + ${project.version} + + ${project.groupId} context-propagation-core ${project.version} + test diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java index 6c031e56..c0a75982 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java +++ b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java @@ -15,52 +15,108 @@ */ package nl.talsmasoftware.context.locale; -import nl.talsmasoftware.context.core.threadlocal.AbstractThreadLocalContext; +import nl.talsmasoftware.context.api.Context; import java.util.Locale; +import java.util.concurrent.atomic.AtomicBoolean; /** - * Package protected context implementation based on {@link AbstractThreadLocalContext}. - *

    - * This context works subtly different from the abstract implementation: - *

      - *
    1. It exposes the {@link #isClosed()} method, because
    2. - *
    3. The {@link #getValue()} method keeps returning the contained {@linkplain Locale}, - * even after the context is already closed.
    4. - *
    + * Implementation for a current {@linkplain Locale} context. * * @author Sjoerd Talsma */ -final class LocaleContext extends AbstractThreadLocalContext { - private static final ThreadLocal LOCALE = - AbstractThreadLocalContext.threadLocalInstanceOf(LocaleContext.class); +public final class LocaleContext implements Context { + private static final ThreadLocal LOCALE = new ThreadLocal<>(); + + private final LocaleContext parent; + private final Locale locale; + private final AtomicBoolean closed; - /** - * Instantiates a new context with the specified value. - * The new context will be made the active context for the current thread. - * - * @param newValue The new value to become active in this new context - * (or null to register a new context with 'no value'). - */ LocaleContext(Locale newValue) { - super(newValue); + this.parent = unwindClosed(); + this.locale = newValue; + this.closed = new AtomicBoolean(false); + LOCALE.set(this); } @Override public Locale getValue() { - return value; + return locale; + } + + private LocaleContext closeAndUnwind() { + closed.set(true); + return unwindClosed(); + } + + public void close() { + closeAndUnwind(); } - static Locale currentValue() { - LocaleContext current = LOCALE.get(); - return current != null ? current.value : null; + public String toString() { + return closed.get() ? "LocaleContext{closed}" : "LocaleContext{" + locale + "}"; + } + + /** + * Current locale or {@code null} if none was set or its context was already closed. + * + * @return The current locale or {@code null} + * @see #getOrDefault() + * @see #set(Locale) + */ + public static Locale get() { + final LocaleContext current = unwindClosed(); + return current != null ? current.locale : null; + } + + /** + * Current locale or {@linkplain Locale#getDefault()} if none was set or its context was already closed. + * + * @return The current locale or {@code Locale.getDefault()}. + * @see #get() + * @see #set(Locale) + */ + public static Locale getOrDefault() { + Locale current = get(); + return current != null ? current : Locale.getDefault(); + } + + /** + * Sets the current locale on the current thread until {@linkplain Context#close()} is called. + * + * @param locale The locale to become the current locale. + * @return The context to restore the previous locale with upon {@code close()}. + */ + public static Context set(Locale locale) { + return new LocaleContext(locale); } /** * Unconditionally clears the entire {@link LocaleContext}. * This can be useful when returning threads to a thread pool. */ - static void clearAll() { - LOCALE.remove(); + static void clear() { + LocaleContext current = unwindClosed(); + while (current != null) { + current = current.closeAndUnwind(); + } + } + + /** + * Unwind closed contexts from the threadlocal until the first unclosed context is found. + * + * @return The current (unclosed) context or {@code null} if all contexts were closed. + */ + private static LocaleContext unwindClosed() { + // Find the first unclosed context. + LocaleContext context = LOCALE.get(); + while (context != null && context.closed.get()) { + context = context.parent; + } + + // Set the found unclosed context and return it. + if (context == null) LOCALE.remove(); + else LOCALE.set(context); + return context; } } diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java index bc860f49..af4ccd90 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java +++ b/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java @@ -26,18 +26,6 @@ * @author Sjoerd Talsma */ public final class LocaleContextManager implements ContextManager { - /** - * @return The {@code Locale} for the current thread, or {@code Locale.getDefault()} if no context was initialized. - * @see Locale#getDefault() - */ - public static Locale getCurrentLocaleOrDefault() { - final Locale current = LocaleContext.currentValue(); - return current != null ? current : Locale.getDefault(); - } - - public static Context setCurrentLocale(Locale locale) { - return new LocaleContext(locale); - } /** * Registers the given {@linkplain Locale} value as the current Locale for the active thread @@ -47,14 +35,14 @@ public static Context setCurrentLocale(Locale locale) { * @return The context to be closed again by the caller to remove this locale as current locale. */ public Context initializeNewContext(Locale value) { - return setCurrentLocale(value); + return new LocaleContext(value); } /** * @return The active {@code Locale} context or {@code null} if no such context is active in the current thread. */ public Locale getActiveContextValue() { - return LocaleContext.currentValue(); + return LocaleContext.get(); } /** @@ -63,7 +51,7 @@ public Locale getActiveContextValue() { * This is useful for boundary filters, whose Threads may be returned to some thread pool. */ public void clear() { - LocaleContext.clearAll(); + LocaleContext.clear(); } /** diff --git a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java index 48f3a13f..02224eee 100644 --- a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java +++ b/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java @@ -64,17 +64,17 @@ public void cleanup() { @Test public void testLocalePropagation() throws ExecutionException, InterruptedException { - try (Context ctx1 = LocaleContextManager.setCurrentLocale(DUTCH)) { + try (Context ctx1 = LocaleContext.set(DUTCH)) { assertThat(ctx1.getValue(), is(DUTCH)); assertThat(MANAGER.getActiveContextValue(), is(DUTCH)); - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DUTCH)); + assertThat(LocaleContext.getOrDefault(), is(DUTCH)); final CountDownLatch blocker = new CountDownLatch(1); Future slowCall; try (Context ctx2 = MANAGER.initializeNewContext(GERMAN)) { assertThat(ctx2.getValue(), is(GERMAN)); assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); + assertThat(LocaleContext.getOrDefault(), is(GERMAN)); slowCall = threadpool.submit(() -> { blocker.await(5, TimeUnit.SECONDS); @@ -88,25 +88,25 @@ public void testLocalePropagation() throws ExecutionException, InterruptedExcept assertThat("Context in slow thread", slowCall.get(), is(GERMAN)); } assertThat("Current context", MANAGER.getActiveContextValue(), is(nullValue())); - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); } @Test public void testGetCurrentLocaleOrDefault() { - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); - try (Context ctx1 = LocaleContextManager.setCurrentLocale(GERMAN)) { - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); + try (Context ctx1 = LocaleContext.set(GERMAN)) { + assertThat(LocaleContext.getOrDefault(), is(GERMAN)); assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); try (Context ctx2 = MANAGER.initializeNewContext(null)) { - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); assertThat(MANAGER.getActiveContextValue(), nullValue()); } finally { - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(GERMAN)); + assertThat(LocaleContext.getOrDefault(), is(GERMAN)); assertThat(MANAGER.getActiveContextValue(), is(GERMAN)); } } finally { - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); } } @@ -117,7 +117,7 @@ public void testClear() { MANAGER.clear(); assertThat(MANAGER.getActiveContextValue(), is(nullValue())); - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); assertThat(englishCtx.getValue(), equalTo(ENGLISH)); assertThat(dutchCtx.getValue(), equalTo(DUTCH)); @@ -130,7 +130,7 @@ public void testClearActiveContexts() { ContextManagers.clearActiveContexts(); assertThat(MANAGER.getActiveContextValue(), is(nullValue())); - assertThat(LocaleContextManager.getCurrentLocaleOrDefault(), is(DEFAULT_LOCALE)); + assertThat(LocaleContext.getOrDefault(), is(DEFAULT_LOCALE)); assertThat(englishCtx.getValue(), equalTo(ENGLISH)); assertThat(dutchCtx.getValue(), equalTo(DUTCH)); diff --git a/readme.md b/readme.md index 395ebb2b..c35cf7b7 100644 --- a/readme.md +++ b/readme.md @@ -15,6 +15,7 @@ > - `ContextManager.getActiveContext()` replaced by `getActiveContextValue()`. > - `ContextManager.clear()` will require an implementation. > - All `@Deprecated(forRemoval=true)` is to be removed. +> - Add caveat about use vs. Scoped values and Structured Concurrency. # Context propagation library From aeb9f1c10bab1c543780f3f9a6108140f13c7cbb Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 16:22:12 +0100 Subject: [PATCH 23/41] Organization: Move all Context Timers in 'timers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 49 +++++++++--- ...nl.talsmasoftware.context.api.ContextTimer | 1 - ...nl.talsmasoftware.context.api.ContextTimer | 1 - .../opentracing/OpentracingSpanManager.java | 23 ------ ...nl.talsmasoftware.context.api.ContextTimer | 1 - .../context/opentracing/SpanManagerTest.java | 21 ------ ...asoftware.context.observer.ContextObserver | 1 - pom.xml | 6 +- .../context-timer-metrics}/README.md | 0 .../context-timer-metrics}/pom.xml | 10 ++- .../timers}/metrics/MetricsContextTimer.java | 2 +- ...nl.talsmasoftware.context.api.ContextTimer | 1 + .../metrics/MetricsContextTimerTest.java | 2 +- .../src/test/resources/logging.properties | 0 .../context-timer-micrometer}/pom.xml | 10 ++- .../context-timer-micrometer}/readme.md | 0 .../micrometer/MicrometerContextTimer.java | 2 +- ...nl.talsmasoftware.context.api.ContextTimer | 1 + .../MicrometerContextTimerTest.java | 2 +- .../src/test/resources/logging.properties | 0 timers/context-timer-opentracing/pom.xml | 75 +++++++++++++++++++ .../opentracing/OpentracingContextTimer.java | 18 ++--- ...nl.talsmasoftware.context.api.ContextTimer | 1 + .../timers}/opentracing/MockSpanMatcher.java | 4 +- .../OpentracingContextTimerTest.java | 4 +- 25 files changed, 145 insertions(+), 90 deletions(-) delete mode 100644 context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer delete mode 100644 context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer delete mode 100644 opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingSpanManager.java delete mode 100644 opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer delete mode 100644 opentracing-span-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver rename {context-propagation-metrics => timers/context-timer-metrics}/README.md (100%) rename {context-propagation-metrics => timers/context-timer-metrics}/pom.xml (86%) rename {context-propagation-metrics/src/main/java/nl/talsmasoftware/context => timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers}/metrics/MetricsContextTimer.java (99%) create mode 100644 timers/context-timer-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer rename {context-propagation-metrics/src/test/java/nl/talsmasoftware/context => timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers}/metrics/MetricsContextTimerTest.java (99%) rename {context-propagation-metrics => timers/context-timer-metrics}/src/test/resources/logging.properties (100%) rename {context-propagation-micrometer => timers/context-timer-micrometer}/pom.xml (86%) rename {context-propagation-micrometer => timers/context-timer-micrometer}/readme.md (100%) rename {context-propagation-micrometer/src/main/java/nl/talsmasoftware/context => timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers}/micrometer/MicrometerContextTimer.java (96%) create mode 100644 timers/context-timer-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer rename {context-propagation-micrometer/src/test/java/nl/talsmasoftware/context => timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers}/micrometer/MicrometerContextTimerTest.java (97%) rename {context-propagation-micrometer => timers/context-timer-micrometer}/src/test/resources/logging.properties (100%) create mode 100644 timers/context-timer-opentracing/pom.xml rename {opentracing-span-propagation/src/main/java/nl/talsmasoftware/context => timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers}/opentracing/OpentracingContextTimer.java (83%) create mode 100644 timers/context-timer-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer rename {opentracing-span-propagation/src/test/java/nl/talsmasoftware/context => timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers}/opentracing/MockSpanMatcher.java (97%) rename {opentracing-span-propagation/src/test/java/nl/talsmasoftware/context => timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers}/opentracing/OpentracingContextTimerTest.java (95%) diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index a7103650..5f74a668 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -42,6 +42,9 @@ + + + ${project.groupId} context-propagation-api @@ -78,42 +81,64 @@ sources + + - ${project.groupId} - context-propagation-metrics + ${project.groupId}.timers + context-timer-metrics ${project.version} - ${project.groupId} - context-propagation-metrics + ${project.groupId}.timers + context-timer-metrics ${project.version} javadoc - ${project.groupId} - context-propagation-metrics + ${project.groupId}.timers + context-timer-metrics ${project.version} sources - ${project.groupId} - context-propagation-micrometer + ${project.groupId}.timers + context-timer-micrometer ${project.version} - ${project.groupId} - context-propagation-micrometer + ${project.groupId}.timers + context-timer-micrometer ${project.version} javadoc - ${project.groupId} - context-propagation-micrometer + ${project.groupId}.timers + context-timer-micrometer + ${project.version} + sources + + + + ${project.groupId}.timers + context-timer-opentracing + ${project.version} + + + ${project.groupId}.timers + context-timer-opentracing + ${project.version} + javadoc + + + ${project.groupId}.timers + context-timer-opentracing ${project.version} sources + + ${project.groupId} slf4j-propagation diff --git a/context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer deleted file mode 100644 index 12c699a3..00000000 --- a/context-propagation-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.metrics.MetricsContextTimer diff --git a/context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer deleted file mode 100644 index 4259c5db..00000000 --- a/context-propagation-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.micrometer.MicrometerContextTimer diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingSpanManager.java b/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingSpanManager.java deleted file mode 100644 index 8d2bafe6..00000000 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingSpanManager.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2016-2022 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.opentracing; - -/** - * @author Sjoerd Talsma - * @deprecated Renamed to {@code SpanManager} - */ -public class OpentracingSpanManager extends SpanManager { -} diff --git a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer deleted file mode 100644 index e8d3eddb..00000000 --- a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.opentracing.OpentracingContextTimer diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java index 2ba87197..ec430f31 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java +++ b/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java @@ -23,8 +23,6 @@ import io.opentracing.util.GlobalTracer; import io.opentracing.util.GlobalTracerTestUtil; import io.opentracing.util.ThreadLocalScopeManager; -import nl.talsmasoftware.context.api.Context; -import nl.talsmasoftware.context.api.ContextManager; import nl.talsmasoftware.context.core.ContextManagers; import nl.talsmasoftware.context.core.concurrent.ContextAwareExecutorService; import org.junit.jupiter.api.AfterEach; @@ -208,25 +206,6 @@ public String call() throws Exception { assertThat("child span finished?", mockTracer.finishedSpans(), hasItem((MockSpan) childSpanRef.get())); } - @Test - @Deprecated - public void testDeprecatedClassStillWorks() { - ContextManager deprecatedManager = new OpentracingSpanManager(); - - Span parentSpan = mockTracer.buildSpan("first-op").start(); - Scope parent = mockTracer.activateSpan(parentSpan); - Span newSpan = mockTracer.buildSpan("second-span").start(); - assertThat(deprecatedManager.getActiveContextValue(), is(equalTo(parentSpan))); - - Context newContext = deprecatedManager.initializeNewContext(newSpan); - assertThat(SCOPE_MANAGER.activeSpan(), is(equalTo(newSpan))); - newContext.close(); - assertThat(SCOPE_MANAGER.activeSpan(), not(equalTo(newSpan))); - - newContext.close(); - newContext.close(); - } - @Test public void testClearingAllContexts() { Span span = mockTracer.buildSpan("test-span").start(); diff --git a/opentracing-span-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver b/opentracing-span-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver deleted file mode 100644 index bf52192a..00000000 --- a/opentracing-span-propagation/src/test/resources/META-INF/services/nl.talsmasoftware.context.observer.ContextObserver +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.opentracing.ContextScopeManagerObserver diff --git a/pom.xml b/pom.xml index a6b71ca4..b05871cc 100644 --- a/pom.xml +++ b/pom.xml @@ -38,8 +38,10 @@ context-propagation-bom context-propagation-api context-propagation-core - context-propagation-metrics - context-propagation-micrometer + timers/context-timer-metrics + timers/context-timer-micrometer + timers/context-timer-opentracing + locale-context log4j2-propagation servletrequest-propagation diff --git a/context-propagation-metrics/README.md b/timers/context-timer-metrics/README.md similarity index 100% rename from context-propagation-metrics/README.md rename to timers/context-timer-metrics/README.md diff --git a/context-propagation-metrics/pom.xml b/timers/context-timer-metrics/pom.xml similarity index 86% rename from context-propagation-metrics/pom.xml rename to timers/context-timer-metrics/pom.xml index 2679246f..7b509d4c 100644 --- a/context-propagation-metrics/pom.xml +++ b/timers/context-timer-metrics/pom.xml @@ -25,11 +25,13 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml
    - context-propagation-metrics - Context propagation (metrics) + nl.talsmasoftware.context.timers + context-timer-metrics + Context timer (metrics) jar @@ -39,7 +41,7 @@ - ${project.groupId} + ${parent.groupId} context-propagation-api ${project.version} @@ -51,7 +53,7 @@ - ${project.groupId} + ${parent.groupId} context-propagation-core ${project.version} test diff --git a/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java b/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java similarity index 99% rename from context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java rename to timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java index 99292872..c420bdc2 100644 --- a/context-propagation-metrics/src/main/java/nl/talsmasoftware/context/metrics/MetricsContextTimer.java +++ b/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.metrics; +package nl.talsmasoftware.context.timers.metrics; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; diff --git a/timers/context-timer-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/timers/context-timer-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer new file mode 100644 index 00000000..3219b43b --- /dev/null +++ b/timers/context-timer-metrics/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer @@ -0,0 +1 @@ +nl.talsmasoftware.context.timers.metrics.MetricsContextTimer diff --git a/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java similarity index 99% rename from context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java rename to timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java index a51ecb59..e322cd8a 100644 --- a/context-propagation-metrics/src/test/java/nl/talsmasoftware/context/metrics/MetricsContextTimerTest.java +++ b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.metrics; +package nl.talsmasoftware.context.timers.metrics; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; diff --git a/context-propagation-metrics/src/test/resources/logging.properties b/timers/context-timer-metrics/src/test/resources/logging.properties similarity index 100% rename from context-propagation-metrics/src/test/resources/logging.properties rename to timers/context-timer-metrics/src/test/resources/logging.properties diff --git a/context-propagation-micrometer/pom.xml b/timers/context-timer-micrometer/pom.xml similarity index 86% rename from context-propagation-micrometer/pom.xml rename to timers/context-timer-micrometer/pom.xml index 4fbd2dcf..0b0db9a5 100644 --- a/context-propagation-micrometer/pom.xml +++ b/timers/context-timer-micrometer/pom.xml @@ -25,11 +25,13 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - context-propagation-micrometer - Context propagation (micrometer) + nl.talsmasoftware.context.timers + context-timer-micrometer + Context timer (micrometer) jar @@ -41,7 +43,7 @@ - ${project.groupId} + ${parent.groupId} context-propagation-api ${project.version} @@ -53,7 +55,7 @@ - ${project.groupId} + ${parent.groupId} context-propagation-core ${project.version} test diff --git a/context-propagation-micrometer/readme.md b/timers/context-timer-micrometer/readme.md similarity index 100% rename from context-propagation-micrometer/readme.md rename to timers/context-timer-micrometer/readme.md diff --git a/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java b/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java similarity index 96% rename from context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java rename to timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java index 3b623bc9..f5afca87 100644 --- a/context-propagation-micrometer/src/main/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimer.java +++ b/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.micrometer; +package nl.talsmasoftware.context.timers.micrometer; import io.micrometer.core.instrument.Metrics; import nl.talsmasoftware.context.api.ContextTimer; diff --git a/timers/context-timer-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/timers/context-timer-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer new file mode 100644 index 00000000..d8c25330 --- /dev/null +++ b/timers/context-timer-micrometer/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer @@ -0,0 +1 @@ +nl.talsmasoftware.context.timers.micrometer.MicrometerContextTimer diff --git a/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java similarity index 97% rename from context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java rename to timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java index 5979bb09..50aa5cba 100644 --- a/context-propagation-micrometer/src/test/java/nl/talsmasoftware/context/micrometer/MicrometerContextTimerTest.java +++ b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.micrometer; +package nl.talsmasoftware.context.timers.micrometer; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Timer; diff --git a/context-propagation-micrometer/src/test/resources/logging.properties b/timers/context-timer-micrometer/src/test/resources/logging.properties similarity index 100% rename from context-propagation-micrometer/src/test/resources/logging.properties rename to timers/context-timer-micrometer/src/test/resources/logging.properties diff --git a/timers/context-timer-opentracing/pom.xml b/timers/context-timer-opentracing/pom.xml new file mode 100644 index 00000000..680b5cfa --- /dev/null +++ b/timers/context-timer-opentracing/pom.xml @@ -0,0 +1,75 @@ + + + + + 4.0.0 + + nl.talsmasoftware.context + context-propagation + 2.0.0-SNAPSHOT + ../../pom.xml + + + + nl.talsmasoftware.context.timers + context-timer-opentracing + Context timer (opentracing) + jar + + + ${project.groupId}.metrics + ${project.parent.basedir} + + + + + ${parent.groupId} + context-propagation-api + ${project.version} + + + io.opentracing + opentracing-util + ${opentracing-api.version} + + + + ${parent.groupId} + context-propagation-core + ${project.version} + test + + + io.opentracing + opentracing-mock + ${opentracing-api.version} + test + + + io.opentracing + opentracing-util + ${opentracing-api.version} + test-jar + test + + + + diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java b/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java similarity index 83% rename from opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java rename to timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java index 36d45b10..be2468b8 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimer.java +++ b/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java @@ -13,24 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.timers.opentracing; import io.opentracing.Span; import io.opentracing.util.GlobalTracer; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextTimer; -import nl.talsmasoftware.context.core.ContextManagers; import java.util.concurrent.TimeUnit; import static java.util.Collections.singletonMap; /** - * This {@link ContextTimer} uses the {@code Opentracing API} to report the timing statistics of the context switches - * that occurred. - *

    - * This class does not really support Opentracing as that it uses opentracing to report - * the timing metrics of this library. + * This {@link ContextTimer} uses the {@code Opentracing API} to report timing statistics of context switches. * * @author Sjoerd Talsma */ @@ -62,11 +57,10 @@ public void update(Class type, String method, long duration, TimeUnit unit) { private static boolean reportContextSwitchesFor(Class type) { boolean enableTracing = false; - // Only report spans for entire snapshots, not individual context managers - // Could be made configurable if somebody ever asks for it.. - if (ContextManagers.class.isAssignableFrom(type) - || nl.talsmasoftware.context.core.ContextManagers.class.isAssignableFrom(type) - || ContextSnapshot.class.isAssignableFrom(type)) { + // Only report spans for entire snapshots, not individual context managers. + // Could be made configurable if somebody ever asks for it. + if (ContextSnapshot.class.isAssignableFrom(type) + || "nl.talsmasoftware.context.core.ContextManagers".equals(type.getName())) { final String prop = System.getProperty(SYS_ENABLED, ENV_ENABLED); enableTracing = "1".equals(prop) || "true".equalsIgnoreCase(prop) || "enabled".equalsIgnoreCase(prop); } diff --git a/timers/context-timer-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer b/timers/context-timer-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer new file mode 100644 index 00000000..bdf9623c --- /dev/null +++ b/timers/context-timer-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextTimer @@ -0,0 +1 @@ +nl.talsmasoftware.context.timers.opentracing.OpentracingContextTimer diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/MockSpanMatcher.java b/timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/MockSpanMatcher.java similarity index 97% rename from opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/MockSpanMatcher.java rename to timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/MockSpanMatcher.java index cd703a12..e62bebe1 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/MockSpanMatcher.java +++ b/timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/MockSpanMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.timers.opentracing; import io.opentracing.mock.MockSpan; import org.hamcrest.BaseMatcher; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java b/timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimerTest.java similarity index 95% rename from opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java rename to timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimerTest.java index 9299a666..d1d22b45 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/OpentracingContextTimerTest.java +++ b/timers/context-timer-opentracing/src/test/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.timers.opentracing; import io.opentracing.mock.MockTracer; import io.opentracing.util.GlobalTracer; @@ -25,7 +25,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static nl.talsmasoftware.context.opentracing.MockSpanMatcher.withOperationName; +import static nl.talsmasoftware.context.timers.opentracing.MockSpanMatcher.withOperationName; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItem; From 9c44cad75f6056f937e364fdf65f51b439f887ba Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 16:38:39 +0100 Subject: [PATCH 24/41] Organization: Move Locale Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 29 ++++++++++--------- ....talsmasoftware.context.api.ContextManager | 1 - .../context-manager-locale}/README.md | 0 .../context-manager-locale}/pom.xml | 10 ++++--- .../managers}/locale/LocaleContext.java | 2 +- .../locale/LocaleContextManager.java | 2 +- .../managers}/locale/package-info.java | 7 ++--- ....talsmasoftware.context.api.ContextManager | 1 + .../locale/LocaleContextManagerTest.java | 2 +- .../src/test/resources/logging.properties | 0 pom.xml | 3 +- timers/context-timer-metrics/pom.xml | 4 +-- timers/context-timer-micrometer/pom.xml | 4 +-- timers/context-timer-opentracing/pom.xml | 4 +-- .../src/test/resources/logging.properties | 2 ++ 15 files changed, 39 insertions(+), 32 deletions(-) delete mode 100644 locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {locale-context => managers/context-manager-locale}/README.md (100%) rename {locale-context => managers/context-manager-locale}/pom.xml (84%) rename {locale-context/src/main/java/nl/talsmasoftware/context => managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers}/locale/LocaleContext.java (98%) rename {locale-context/src/main/java/nl/talsmasoftware/context => managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers}/locale/LocaleContextManager.java (97%) rename {locale-context/src/main/java/nl/talsmasoftware/context => managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers}/locale/package-info.java (89%) create mode 100644 managers/context-manager-locale/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {locale-context/src/test/java/nl/talsmasoftware/context => managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers}/locale/LocaleContextManagerTest.java (99%) rename {locale-context => managers/context-manager-locale}/src/test/resources/logging.properties (100%) create mode 100644 timers/context-timer-opentracing/src/test/resources/logging.properties diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 5f74a668..5a15e9d9 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -137,58 +137,61 @@ sources - + - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-locale ${project.version} - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-locale ${project.version} javadoc - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-locale ${project.version} sources + + + ${project.groupId} - log4j2-propagation + slf4j-propagation ${project.version} ${project.groupId} - log4j2-propagation + slf4j-propagation ${project.version} javadoc ${project.groupId} - log4j2-propagation + slf4j-propagation ${project.version} sources ${project.groupId} - locale-context + log4j2-propagation ${project.version} ${project.groupId} - locale-context + log4j2-propagation ${project.version} javadoc ${project.groupId} - locale-context + log4j2-propagation ${project.version} sources diff --git a/locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index cb5c1aaa..00000000 --- a/locale-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.locale.LocaleContextManager diff --git a/locale-context/README.md b/managers/context-manager-locale/README.md similarity index 100% rename from locale-context/README.md rename to managers/context-manager-locale/README.md diff --git a/locale-context/pom.xml b/managers/context-manager-locale/pom.xml similarity index 84% rename from locale-context/pom.xml rename to managers/context-manager-locale/pom.xml index c8c52f34..36026a5d 100644 --- a/locale-context/pom.xml +++ b/managers/context-manager-locale/pom.xml @@ -24,11 +24,13 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - locale-context - Propagation of current Locale + nl.talsmasoftware.context.managers + context-manager-locale + Propagation of Locale jar @@ -39,13 +41,13 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} - ${project.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContext.java similarity index 98% rename from locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java rename to managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContext.java index c0a75982..a6e3053d 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContext.java +++ b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContext.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.locale; +package nl.talsmasoftware.context.managers.locale; import nl.talsmasoftware.context.api.Context; diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java similarity index 97% rename from locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java rename to managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java index af4ccd90..9c1a0ba2 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/LocaleContextManager.java +++ b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.locale; +package nl.talsmasoftware.context.managers.locale; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; diff --git a/locale-context/src/main/java/nl/talsmasoftware/context/locale/package-info.java b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/package-info.java similarity index 89% rename from locale-context/src/main/java/nl/talsmasoftware/context/locale/package-info.java rename to managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/package-info.java index 0973baa1..64dde45f 100644 --- a/locale-context/src/main/java/nl/talsmasoftware/context/locale/package-info.java +++ b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** * Maintain a current {@linkplain java.util.Locale Locale} context. * *

    - * Setting a current locale can be done using the {@linkplain nl.talsmasoftware.context.locale.LocaleContextManager}: + * Setting a current locale can be done using the {@linkplain nl.talsmasoftware.context.managers.locale.LocaleContextManager}: *

    {@code
      * private static LocaleContextManager localeContextManager = new LocaleContextManager();
      *
    @@ -38,4 +37,4 @@
      * }
      * }
    */ -package nl.talsmasoftware.context.locale; \ No newline at end of file +package nl.talsmasoftware.context.managers.locale; diff --git a/managers/context-manager-locale/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-locale/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..08d77054 --- /dev/null +++ b/managers/context-manager-locale/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.managers.locale.LocaleContextManager diff --git a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java b/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java similarity index 99% rename from locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java rename to managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java index 02224eee..961b838c 100644 --- a/locale-context/src/test/java/nl/talsmasoftware/context/locale/LocaleContextManagerTest.java +++ b/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.locale; +package nl.talsmasoftware.context.managers.locale; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.core.ContextManagers; diff --git a/locale-context/src/test/resources/logging.properties b/managers/context-manager-locale/src/test/resources/logging.properties similarity index 100% rename from locale-context/src/test/resources/logging.properties rename to managers/context-manager-locale/src/test/resources/logging.properties diff --git a/pom.xml b/pom.xml index b05871cc..27963fd9 100644 --- a/pom.xml +++ b/pom.xml @@ -38,11 +38,12 @@ context-propagation-bom context-propagation-api context-propagation-core + timers/context-timer-metrics timers/context-timer-micrometer timers/context-timer-opentracing - locale-context + managers/context-manager-locale log4j2-propagation servletrequest-propagation slf4j-propagation diff --git a/timers/context-timer-metrics/pom.xml b/timers/context-timer-metrics/pom.xml index 7b509d4c..e6675441 100644 --- a/timers/context-timer-metrics/pom.xml +++ b/timers/context-timer-metrics/pom.xml @@ -41,7 +41,7 @@ - ${parent.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -53,7 +53,7 @@
    - ${parent.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/timers/context-timer-micrometer/pom.xml b/timers/context-timer-micrometer/pom.xml index 0b0db9a5..a15929ee 100644 --- a/timers/context-timer-micrometer/pom.xml +++ b/timers/context-timer-micrometer/pom.xml @@ -43,7 +43,7 @@ - ${parent.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -55,7 +55,7 @@ - ${parent.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/timers/context-timer-opentracing/pom.xml b/timers/context-timer-opentracing/pom.xml index 680b5cfa..2b401270 100644 --- a/timers/context-timer-opentracing/pom.xml +++ b/timers/context-timer-opentracing/pom.xml @@ -41,7 +41,7 @@ - ${parent.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -52,7 +52,7 @@ - ${parent.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/timers/context-timer-opentracing/src/test/resources/logging.properties b/timers/context-timer-opentracing/src/test/resources/logging.properties new file mode 100644 index 00000000..4786544f --- /dev/null +++ b/timers/context-timer-opentracing/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +# Use no logging by default during tests to keep the output as clean as possible. +.level=OFF From c86124c718ed11ee52267b044180bbb594c3da05 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 18:23:35 +0100 Subject: [PATCH 25/41] Organization: Move Slf4j Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 19 ++++++++++--------- .../context-manager-slf4j}/README.md | 0 .../context-manager-slf4j}/pom.xml | 12 +++++++----- .../managers}/slf4j/mdc/Slf4jMdcManager.java | 2 +- .../managers}/slf4j/mdc/package-info.java | 2 +- ....talsmasoftware.context.api.ContextManager | 1 + .../slf4j/mdc/Slf4jMdcManagerTest.java | 2 +- .../src/test/resources/logging.properties | 0 pom.xml | 2 +- ....talsmasoftware.context.api.ContextManager | 1 - 10 files changed, 22 insertions(+), 19 deletions(-) rename {slf4j-propagation => managers/context-manager-slf4j}/README.md (100%) rename {slf4j-propagation => managers/context-manager-slf4j}/pom.xml (86%) rename {slf4j-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers}/slf4j/mdc/Slf4jMdcManager.java (98%) rename {slf4j-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers}/slf4j/mdc/package-info.java (95%) create mode 100644 managers/context-manager-slf4j/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {slf4j-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers}/slf4j/mdc/Slf4jMdcManagerTest.java (98%) rename {slf4j-propagation => managers/context-manager-slf4j}/src/test/resources/logging.properties (100%) delete mode 100644 slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 5a15e9d9..65719392 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -157,27 +157,28 @@ sources - - - - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} javadoc - ${project.groupId} - slf4j-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} sources + + + + ${project.groupId} log4j2-propagation diff --git a/slf4j-propagation/README.md b/managers/context-manager-slf4j/README.md similarity index 100% rename from slf4j-propagation/README.md rename to managers/context-manager-slf4j/README.md diff --git a/slf4j-propagation/pom.xml b/managers/context-manager-slf4j/pom.xml similarity index 86% rename from slf4j-propagation/pom.xml rename to managers/context-manager-slf4j/pom.xml index 72ad421b..3ac4c600 100644 --- a/slf4j-propagation/pom.xml +++ b/managers/context-manager-slf4j/pom.xml @@ -24,22 +24,24 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - slf4j-propagation - Propagation of SLF4J MDC + nl.talsmasoftware.context.managers + context-manager-slf4j + Propagation of Slf4j MDC jar - ${project.groupId}.mdc + ${project.groupId}.slf4j ${project.parent.basedir} 8 - ${project.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -50,7 +52,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java similarity index 98% rename from slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java rename to managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java index 950c716b..3f2e2511 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManager.java +++ b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.slf4j.mdc; +package nl.talsmasoftware.context.managers.slf4j.mdc; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; diff --git a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/package-info.java similarity index 95% rename from slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java rename to managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/package-info.java index 636638f5..9cb511e4 100644 --- a/slf4j-propagation/src/main/java/nl/talsmasoftware/context/slf4j/mdc/package-info.java +++ b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/package-info.java @@ -25,4 +25,4 @@ * is {@linkplain nl.talsmasoftware.context.api.ContextSnapshot#reactivate() reactivated} * in another thread. */ -package nl.talsmasoftware.context.slf4j.mdc; +package nl.talsmasoftware.context.managers.slf4j.mdc; diff --git a/managers/context-manager-slf4j/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-slf4j/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..555c677c --- /dev/null +++ b/managers/context-manager-slf4j/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.managers.slf4j.mdc.Slf4jMdcManager diff --git a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java b/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java similarity index 98% rename from slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java rename to managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java index ae6811ca..4acc184d 100644 --- a/slf4j-propagation/src/test/java/nl/talsmasoftware/context/slf4j/mdc/Slf4jMdcManagerTest.java +++ b/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.slf4j.mdc; +package nl.talsmasoftware.context.managers.slf4j.mdc; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; diff --git a/slf4j-propagation/src/test/resources/logging.properties b/managers/context-manager-slf4j/src/test/resources/logging.properties similarity index 100% rename from slf4j-propagation/src/test/resources/logging.properties rename to managers/context-manager-slf4j/src/test/resources/logging.properties diff --git a/pom.xml b/pom.xml index 27963fd9..610b2a70 100644 --- a/pom.xml +++ b/pom.xml @@ -44,9 +44,9 @@ timers/context-timer-opentracing managers/context-manager-locale + managers/context-manager-slf4j log4j2-propagation servletrequest-propagation - slf4j-propagation spring-security-context opentracing-span-propagation diff --git a/slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index feb52ec1..00000000 --- a/slf4j-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.slf4j.mdc.Slf4jMdcManager From dd319c2b3038c627aef1553368ccec590b7a3fd9 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Thu, 7 Nov 2024 18:32:39 +0100 Subject: [PATCH 26/41] Organization: Move ServletRequest Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 36 +++++++++---------- .../context-manager-servletrequest}/README.md | 0 .../context-manager-servletrequest}/pom.xml | 10 +++--- .../servletrequest/ServletRequestContext.java | 2 +- .../ServletRequestContextAsyncListener.java | 2 +- .../ServletRequestContextFilter.java | 2 +- .../ServletRequestContextManager.java | 2 +- ....talsmasoftware.context.api.ContextManager | 1 + ...ervletRequestContextAsyncListenerTest.java | 2 +- .../ServletRequestContextFilterTest.java | 4 +-- .../ServletRequestContextManagerTest.java | 2 +- .../src/test/resources/logging.properties | 0 pom.xml | 3 +- ....talsmasoftware.context.api.ContextManager | 1 - 14 files changed, 35 insertions(+), 32 deletions(-) rename {servletrequest-propagation => managers/context-manager-servletrequest}/README.md (100%) rename {servletrequest-propagation => managers/context-manager-servletrequest}/pom.xml (86%) rename {servletrequest-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContext.java (97%) rename {servletrequest-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextAsyncListener.java (95%) rename {servletrequest-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextFilter.java (97%) rename {servletrequest-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextManager.java (96%) create mode 100644 managers/context-manager-servletrequest/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {servletrequest-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextAsyncListenerTest.java (98%) rename {servletrequest-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextFilterTest.java (97%) rename {servletrequest-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager}/servletrequest/ServletRequestContextManagerTest.java (99%) rename {servletrequest-propagation => managers/context-manager-servletrequest}/src/test/resources/logging.properties (100%) delete mode 100644 servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 65719392..7c9162e5 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -157,6 +157,24 @@ sources + + ${project.groupId}.managers + context-manager-servletrequest + ${project.version} + + + ${project.groupId}.managers + context-manager-servletrequest + ${project.version} + javadoc + + + ${project.groupId}.managers + context-manager-servletrequest + ${project.version} + sources + + ${project.groupId}.managers context-manager-slf4j @@ -215,24 +233,6 @@ sources - - ${project.groupId} - servletrequest-propagation - ${project.version} - - - ${project.groupId} - servletrequest-propagation - ${project.version} - javadoc - - - ${project.groupId} - servletrequest-propagation - ${project.version} - sources - - ${project.groupId} spring-security-context diff --git a/servletrequest-propagation/README.md b/managers/context-manager-servletrequest/README.md similarity index 100% rename from servletrequest-propagation/README.md rename to managers/context-manager-servletrequest/README.md diff --git a/servletrequest-propagation/pom.xml b/managers/context-manager-servletrequest/pom.xml similarity index 86% rename from servletrequest-propagation/pom.xml rename to managers/context-manager-servletrequest/pom.xml index a3a8634d..eb56f02d 100644 --- a/servletrequest-propagation/pom.xml +++ b/managers/context-manager-servletrequest/pom.xml @@ -25,11 +25,13 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - servletrequest-propagation - Propagation of ServletRequests + nl.talsmasoftware.context.managers + context-manager-servletrequest + Propagation of ServletRequest jar @@ -40,7 +42,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -54,7 +56,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContext.java similarity index 97% rename from servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java rename to managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContext.java index e954865e..c792760a 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContext.java +++ b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContext.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import nl.talsmasoftware.context.api.Context; diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListener.java similarity index 95% rename from servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java rename to managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListener.java index 614f2284..d6f67766 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListener.java +++ b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListener.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilter.java similarity index 97% rename from servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java rename to managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilter.java index 84eee257..2044d9c5 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilter.java +++ b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilter.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import nl.talsmasoftware.context.api.Context; diff --git a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java similarity index 96% rename from servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java rename to managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java index c24f4ade..1db2f600 100644 --- a/servletrequest-propagation/src/main/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManager.java +++ b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; diff --git a/managers/context-manager-servletrequest/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-servletrequest/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..dfc79776 --- /dev/null +++ b/managers/context-manager-servletrequest/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.manager.servletrequest.ServletRequestContextManager diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListenerTest.java similarity index 98% rename from servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java rename to managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListenerTest.java index 0a56fa44..925f1237 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextAsyncListenerTest.java +++ b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextAsyncListenerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilterTest.java b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilterTest.java similarity index 97% rename from servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilterTest.java rename to managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilterTest.java index 0958a1f4..25591c0a 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextFilterTest.java +++ b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java similarity index 99% rename from servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java rename to managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java index 3aee9e1d..24855128 100644 --- a/servletrequest-propagation/src/test/java/nl/talsmasoftware/context/servletrequest/ServletRequestContextManagerTest.java +++ b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.servletrequest; +package nl.talsmasoftware.context.manager.servletrequest; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.core.ContextManagers; diff --git a/servletrequest-propagation/src/test/resources/logging.properties b/managers/context-manager-servletrequest/src/test/resources/logging.properties similarity index 100% rename from servletrequest-propagation/src/test/resources/logging.properties rename to managers/context-manager-servletrequest/src/test/resources/logging.properties diff --git a/pom.xml b/pom.xml index 610b2a70..32c9ae93 100644 --- a/pom.xml +++ b/pom.xml @@ -44,9 +44,10 @@ timers/context-timer-opentracing managers/context-manager-locale + managers/context-manager-servletrequest managers/context-manager-slf4j + log4j2-propagation - servletrequest-propagation spring-security-context opentracing-span-propagation diff --git a/servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index a41e39c7..00000000 --- a/servletrequest-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.servletrequest.ServletRequestContextManager From 8c06b950c00dba52b297a309ff90836eefd31700 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 09:48:12 +0100 Subject: [PATCH 27/41] Organization: Move Log4j2 Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 33 ++++++++++--------- ....talsmasoftware.context.api.ContextManager | 1 - .../context-manager-log4j2}/README.md | 0 .../context-manager-log4j2}/pom.xml | 18 +++++----- .../Log4j2ThreadContextManager.java | 2 +- .../Log4j2ThreadContextSnapshot.java | 4 +-- .../log4j2/threadcontext/package-info.java | 5 ++- ....talsmasoftware.context.api.ContextManager | 1 + .../Log4J2ThreadContextSnapshotTest.java | 4 +-- .../Log4j2ThreadContextManagerTest.java | 2 +- .../src/test/resources/logging.properties | 0 pom.xml | 2 +- 12 files changed, 37 insertions(+), 35 deletions(-) delete mode 100644 log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {log4j2-propagation => managers/context-manager-log4j2}/README.md (100%) rename {log4j2-propagation => managers/context-manager-log4j2}/pom.xml (88%) rename {log4j2-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers}/log4j2/threadcontext/Log4j2ThreadContextManager.java (99%) rename {log4j2-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers}/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java (96%) rename {log4j2-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers}/log4j2/threadcontext/package-info.java (87%) create mode 100644 managers/context-manager-log4j2/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {log4j2-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers}/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java (98%) rename {log4j2-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers}/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java (99%) rename {log4j2-propagation => managers/context-manager-log4j2}/src/test/resources/logging.properties (100%) diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 7c9162e5..26d18882 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -159,62 +159,63 @@ ${project.groupId}.managers - context-manager-servletrequest + context-manager-log4j2 ${project.version} ${project.groupId}.managers - context-manager-servletrequest + context-manager-log4j2 ${project.version} javadoc ${project.groupId}.managers - context-manager-servletrequest + context-manager-log4j2 ${project.version} sources ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} javadoc ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} sources - - - - - ${project.groupId} - log4j2-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} - ${project.groupId} - log4j2-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} javadoc - ${project.groupId} - log4j2-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} sources + + + + + ${project.groupId} opentracing-span-propagation diff --git a/log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index bbe4a144..00000000 --- a/log4j2-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.log4j2.threadcontext.Log4j2ThreadContextManager diff --git a/log4j2-propagation/README.md b/managers/context-manager-log4j2/README.md similarity index 100% rename from log4j2-propagation/README.md rename to managers/context-manager-log4j2/README.md diff --git a/log4j2-propagation/pom.xml b/managers/context-manager-log4j2/pom.xml similarity index 88% rename from log4j2-propagation/pom.xml rename to managers/context-manager-log4j2/pom.xml index 8ecfa438..4e867a68 100644 --- a/log4j2-propagation/pom.xml +++ b/managers/context-manager-log4j2/pom.xml @@ -23,10 +23,12 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - log4j2-propagation + nl.talsmasoftware.context.managers + context-manager-log4j2 Propagation of Log4j 2 ThreadContext jar @@ -37,7 +39,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -48,15 +50,15 @@ - org.apache.logging.log4j - log4j-core - ${log4j2.version} + ${project.parent.groupId} + context-propagation-core + ${project.version} test - ${project.groupId} - context-propagation-core - ${project.version} + org.apache.logging.log4j + log4j-core + ${log4j2.version} test
    diff --git a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManager.java similarity index 99% rename from log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java rename to managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManager.java index 3a587fc6..e8995a07 100644 --- a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManager.java +++ b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.log4j2.threadcontext; +package nl.talsmasoftware.context.managers.log4j2.threadcontext; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; diff --git a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java similarity index 96% rename from log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java rename to managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java index dbdd7d82..17db624b 100644 --- a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java +++ b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextSnapshot.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.log4j2.threadcontext; +package nl.talsmasoftware.context.managers.log4j2.threadcontext; import org.apache.logging.log4j.ThreadContext; diff --git a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/package-info.java b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/package-info.java similarity index 87% rename from log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/package-info.java rename to managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/package-info.java index 1830331f..6c84b3e6 100644 --- a/log4j2-propagation/src/main/java/nl/talsmasoftware/context/log4j2/threadcontext/package-info.java +++ b/managers/context-manager-log4j2/src/main/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** * Propagate the {@linkplain org.apache.logging.log4j.ThreadContext Log4j 2 ThreadContext} * data from one thread to another. */ -package nl.talsmasoftware.context.log4j2.threadcontext; +package nl.talsmasoftware.context.managers.log4j2.threadcontext; diff --git a/managers/context-manager-log4j2/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-log4j2/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..28e612a6 --- /dev/null +++ b/managers/context-manager-log4j2/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.managers.log4j2.threadcontext.Log4j2ThreadContextManager diff --git a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java similarity index 98% rename from log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java rename to managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java index 3f5e1233..2ac2f486 100644 --- a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java +++ b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4J2ThreadContextSnapshotTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.log4j2.threadcontext; +package nl.talsmasoftware.context.managers.log4j2.threadcontext; import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.AfterEach; diff --git a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java similarity index 99% rename from log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java rename to managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java index 71fd36eb..73556c3f 100644 --- a/log4j2-propagation/src/test/java/nl/talsmasoftware/context/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java +++ b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.log4j2.threadcontext; +package nl.talsmasoftware.context.managers.log4j2.threadcontext; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextSnapshot; diff --git a/log4j2-propagation/src/test/resources/logging.properties b/managers/context-manager-log4j2/src/test/resources/logging.properties similarity index 100% rename from log4j2-propagation/src/test/resources/logging.properties rename to managers/context-manager-log4j2/src/test/resources/logging.properties diff --git a/pom.xml b/pom.xml index 32c9ae93..f186de43 100644 --- a/pom.xml +++ b/pom.xml @@ -44,10 +44,10 @@ timers/context-timer-opentracing managers/context-manager-locale + managers/context-manager-log4j2 managers/context-manager-servletrequest managers/context-manager-slf4j - log4j2-propagation spring-security-context opentracing-span-propagation From c18c9cf2c4347e1d669406a11c24cb44938d7243 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 09:59:40 +0100 Subject: [PATCH 28/41] Organization: Move OpenTracing Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 35 ++++++++++--------- .../context-manager-opentracing}/README.md | 0 .../context-manager-opentracing}/pom.xml | 6 ++-- .../opentracing/ContextScopeManager.java | 2 +- .../managers}/opentracing/SpanManager.java | 2 +- ....talsmasoftware.context.api.ContextManager | 1 + .../opentracing/ContextScopeManagerTest.java | 2 +- .../managers}/opentracing/Issue30Test.java | 2 +- .../opentracing/SpanManagerTest.java | 2 +- .../src/test/resources/logging.properties | 0 ....talsmasoftware.context.api.ContextManager | 1 - pom.xml | 2 +- 12 files changed, 29 insertions(+), 26 deletions(-) rename {opentracing-span-propagation => managers/context-manager-opentracing}/README.md (100%) rename {opentracing-span-propagation => managers/context-manager-opentracing}/pom.xml (91%) rename {opentracing-span-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers}/opentracing/ContextScopeManager.java (98%) rename {opentracing-span-propagation/src/main/java/nl/talsmasoftware/context => managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers}/opentracing/SpanManager.java (98%) create mode 100644 managers/context-manager-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {opentracing-span-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers}/opentracing/ContextScopeManagerTest.java (99%) rename {opentracing-span-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers}/opentracing/Issue30Test.java (98%) rename {opentracing-span-propagation/src/test/java/nl/talsmasoftware/context => managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers}/opentracing/SpanManagerTest.java (99%) rename {opentracing-span-propagation => managers/context-manager-opentracing}/src/test/resources/logging.properties (100%) delete mode 100644 opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 26d18882..1e943c42 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -177,63 +177,64 @@ ${project.groupId}.managers - context-manager-servletrequest + context-manager-opentracing ${project.version} ${project.groupId}.managers - context-manager-servletrequest + context-manager-opentracing ${project.version} javadoc ${project.groupId}.managers - context-manager-servletrequest + context-manager-opentracing ${project.version} sources ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} javadoc ${project.groupId}.managers - context-manager-slf4j + context-manager-servletrequest ${project.version} sources - - - - - - ${project.groupId} - opentracing-span-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} - ${project.groupId} - opentracing-span-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} javadoc - ${project.groupId} - opentracing-span-propagation + ${project.groupId}.managers + context-manager-slf4j ${project.version} sources + + + + + + ${project.groupId} spring-security-context diff --git a/opentracing-span-propagation/README.md b/managers/context-manager-opentracing/README.md similarity index 100% rename from opentracing-span-propagation/README.md rename to managers/context-manager-opentracing/README.md diff --git a/opentracing-span-propagation/pom.xml b/managers/context-manager-opentracing/pom.xml similarity index 91% rename from opentracing-span-propagation/pom.xml rename to managers/context-manager-opentracing/pom.xml index fe95ffe6..3be2350a 100644 --- a/opentracing-span-propagation/pom.xml +++ b/managers/context-manager-opentracing/pom.xml @@ -25,10 +25,12 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - opentracing-span-propagation + nl.talsmasoftware.context.managers + context-manager-opentracing Propagation of OpenTracing Spans jar @@ -40,7 +42,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java similarity index 98% rename from opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java rename to managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java index cba515be..d8a8e1a1 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/ContextScopeManager.java +++ b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.managers.opentracing; import io.opentracing.Scope; import io.opentracing.ScopeManager; diff --git a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java similarity index 98% rename from opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java rename to managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java index 59ee3d9e..2a62ec5d 100644 --- a/opentracing-span-propagation/src/main/java/nl/talsmasoftware/context/opentracing/SpanManager.java +++ b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.managers.opentracing; import io.opentracing.Scope; import io.opentracing.Span; diff --git a/managers/context-manager-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..8360d58c --- /dev/null +++ b/managers/context-manager-opentracing/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.managers.opentracing.SpanManager diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java similarity index 99% rename from opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java rename to managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java index b311ab72..e6b81dae 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/ContextScopeManagerTest.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.managers.opentracing; import io.opentracing.Scope; import io.opentracing.Span; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java similarity index 98% rename from opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java rename to managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java index c80ad31d..623e8981 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/Issue30Test.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.managers.opentracing; import io.opentracing.ScopeManager; import io.opentracing.mock.MockTracer; diff --git a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java similarity index 99% rename from opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java rename to managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java index ec430f31..78328cea 100644 --- a/opentracing-span-propagation/src/test/java/nl/talsmasoftware/context/opentracing/SpanManagerTest.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.opentracing; +package nl.talsmasoftware.context.managers.opentracing; import io.opentracing.Scope; import io.opentracing.ScopeManager; diff --git a/opentracing-span-propagation/src/test/resources/logging.properties b/managers/context-manager-opentracing/src/test/resources/logging.properties similarity index 100% rename from opentracing-span-propagation/src/test/resources/logging.properties rename to managers/context-manager-opentracing/src/test/resources/logging.properties diff --git a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index e4cb8132..00000000 --- a/opentracing-span-propagation/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.opentracing.SpanManager diff --git a/pom.xml b/pom.xml index f186de43..d72a43ce 100644 --- a/pom.xml +++ b/pom.xml @@ -45,11 +45,11 @@ managers/context-manager-locale managers/context-manager-log4j2 + managers/context-manager-opentracing managers/context-manager-servletrequest managers/context-manager-slf4j spring-security-context - opentracing-span-propagation From 2878a2d2f2633eb7445e20ce122862a34ff3f45f Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 10:10:15 +0100 Subject: [PATCH 29/41] Organization: Move Spring Security Context Manager in 'managers' group. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 24 +++++-------------- .../README.md | 0 .../context-manager-spring-security}/pom.xml | 8 ++++--- .../SpringSecurityContextManager.java | 2 +- ....talsmasoftware.context.api.ContextManager | 1 + .../SpringSecurityContextManagerTest.java | 2 +- .../springsecurity/TestAuthentication.java | 4 ++-- .../src/test/resources/logging.properties | 0 pom.xml | 3 +-- ....talsmasoftware.context.api.ContextManager | 1 - 10 files changed, 17 insertions(+), 28 deletions(-) rename {spring-security-context => managers/context-manager-spring-security}/README.md (100%) rename {spring-security-context => managers/context-manager-spring-security}/pom.xml (88%) rename {spring-security-context/src/main/java/nl/talsmasoftware/context => managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers}/springsecurity/SpringSecurityContextManager.java (98%) create mode 100644 managers/context-manager-spring-security/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager rename {spring-security-context/src/test/java/nl/talsmasoftware/context => managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers}/springsecurity/SpringSecurityContextManagerTest.java (98%) rename {spring-security-context/src/test/java/nl/talsmasoftware/context => managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers}/springsecurity/TestAuthentication.java (95%) rename {spring-security-context => managers/context-manager-spring-security}/src/test/resources/logging.properties (100%) delete mode 100644 spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 1e943c42..02a52f49 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -229,35 +229,23 @@ sources - - - - - - - ${project.groupId} - spring-security-context + ${project.groupId}.managers + context-manager-spring-security ${project.version} - ${project.groupId} - spring-security-context + ${project.groupId}.managers + context-manager-spring-security ${project.version} javadoc - ${project.groupId} - spring-security-context + ${project.groupId}.managers + context-manager-spring-security ${project.version} sources - - - nl.talsmasoftware - concurrency - 0.1.3 - diff --git a/spring-security-context/README.md b/managers/context-manager-spring-security/README.md similarity index 100% rename from spring-security-context/README.md rename to managers/context-manager-spring-security/README.md diff --git a/spring-security-context/pom.xml b/managers/context-manager-spring-security/pom.xml similarity index 88% rename from spring-security-context/pom.xml rename to managers/context-manager-spring-security/pom.xml index b721c253..bce6e07f 100644 --- a/spring-security-context/pom.xml +++ b/managers/context-manager-spring-security/pom.xml @@ -24,10 +24,12 @@ nl.talsmasoftware.context context-propagation 2.0.0-SNAPSHOT + ../../pom.xml - spring-security-context + nl.talsmasoftware.context.managers + context-manager-spring-security Propagation of Spring Security Context jar @@ -40,7 +42,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-api ${project.version} @@ -51,7 +53,7 @@ - ${project.groupId} + ${project.parent.groupId} context-propagation-core ${project.version} test diff --git a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java b/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java similarity index 98% rename from spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java rename to managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java index f77ffa11..e0f7cb27 100644 --- a/spring-security-context/src/main/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManager.java +++ b/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.springsecurity; +package nl.talsmasoftware.context.managers.springsecurity; import nl.talsmasoftware.context.api.Context; import nl.talsmasoftware.context.api.ContextManager; diff --git a/managers/context-manager-spring-security/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/managers/context-manager-spring-security/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager new file mode 100644 index 00000000..967d28d5 --- /dev/null +++ b/managers/context-manager-spring-security/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager @@ -0,0 +1 @@ +nl.talsmasoftware.context.managers.springsecurity.SpringSecurityContextManager diff --git a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java similarity index 98% rename from spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java rename to managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java index 0a70d762..460e03af 100644 --- a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/SpringSecurityContextManagerTest.java +++ b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.springsecurity; +package nl.talsmasoftware.context.managers.springsecurity; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; diff --git a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/TestAuthentication.java b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/TestAuthentication.java similarity index 95% rename from spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/TestAuthentication.java rename to managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/TestAuthentication.java index aba71742..be98dd46 100644 --- a/spring-security-context/src/test/java/nl/talsmasoftware/context/springsecurity/TestAuthentication.java +++ b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/TestAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 Talsma ICT + * Copyright 2016-2024 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package nl.talsmasoftware.context.springsecurity; +package nl.talsmasoftware.context.managers.springsecurity; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; diff --git a/spring-security-context/src/test/resources/logging.properties b/managers/context-manager-spring-security/src/test/resources/logging.properties similarity index 100% rename from spring-security-context/src/test/resources/logging.properties rename to managers/context-manager-spring-security/src/test/resources/logging.properties diff --git a/pom.xml b/pom.xml index d72a43ce..2e1ae908 100644 --- a/pom.xml +++ b/pom.xml @@ -48,8 +48,7 @@ managers/context-manager-opentracing managers/context-manager-servletrequest managers/context-manager-slf4j - - spring-security-context + managers/context-manager-spring-security diff --git a/spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager b/spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager deleted file mode 100644 index 7d0d7ffb..00000000 --- a/spring-security-context/src/main/resources/META-INF/services/nl.talsmasoftware.context.api.ContextManager +++ /dev/null @@ -1 +0,0 @@ -nl.talsmasoftware.context.springsecurity.SpringSecurityContextManager From ce395b14335a1e74a3d4e7528491d99ec43e99b1 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 10:24:42 +0100 Subject: [PATCH 30/41] Remove obsolete test. Signed-off-by: Sjoerd Talsma --- .../WrapperWithContextAndConsumerTest.java | 63 ------------------- 1 file changed, 63 deletions(-) delete mode 100644 context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java deleted file mode 100644 index acbe44dd..00000000 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumerTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2016-2024 Talsma ICT - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package nl.talsmasoftware.context.core.function; - -import nl.talsmasoftware.context.api.ContextSnapshot; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.function.Consumer; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * @author Sjoerd Talsma - */ -public class WrapperWithContextAndConsumerTest { - - private ContextSnapshot snapshot; - - @BeforeEach - public void setUp() { - snapshot = mock(ContextSnapshot.class); - } - - @AfterEach - public void verifyMocks() { - verifyNoMoreInteractions(snapshot); - } - - @Test - @Deprecated - public void testDeprecatedConsumerMethod() { - assertThat(new WrapperWithContextAndConsumer(snapshot, "string", null) { - }.contextSnapshotConsumer, is(nullValue())); - - final Consumer contextSnapshotConsumer = snapshot -> { - }; - - assertThat(new WrapperWithContextAndConsumer(snapshot, "string", contextSnapshotConsumer) { - }.contextSnapshotConsumer, - is(sameInstance(contextSnapshotConsumer))); - } - -} From 9ee148e92be82bb0fa914aa303b662429fafc2c9 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 10:44:02 +0100 Subject: [PATCH 31/41] Deprecate ContextManager constructors in favour of singleton provider() Signed-off-by: Sjoerd Talsma --- .../managers/locale/LocaleContextManager.java | 28 +++++++++++++++++++ .../locale/LocaleContextManagerTest.java | 2 +- .../opentracing/ContextScopeManager.java | 28 +++++++++++++++++++ .../managers/opentracing/SpanManager.java | 27 ++++++++++++++++++ .../opentracing/ContextScopeManagerTest.java | 2 +- .../managers/opentracing/SpanManagerTest.java | 12 ++++---- .../ServletRequestContextManager.java | 27 ++++++++++++++++++ .../ServletRequestContextManagerTest.java | 26 ++++++++--------- .../managers/slf4j/mdc/Slf4jMdcManager.java | 26 +++++++++++++++++ .../slf4j/mdc/Slf4jMdcManagerTest.java | 4 +-- .../SpringSecurityContextManager.java | 26 +++++++++++++++++ .../SpringSecurityContextManagerTest.java | 6 ++-- 12 files changed, 188 insertions(+), 26 deletions(-) diff --git a/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java index 9c1a0ba2..9c45d1db 100644 --- a/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java +++ b/managers/context-manager-locale/src/main/java/nl/talsmasoftware/context/managers/locale/LocaleContextManager.java @@ -26,6 +26,34 @@ * @author Sjoerd Talsma */ public final class LocaleContextManager implements ContextManager { + /** + * Singleton instance of this class. + */ + private static final LocaleContextManager INSTANCE = new LocaleContextManager(); + + /** + * Returns the singleton instance of the {@code LocaleContextManager}. + * + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The LocaleContext manager. + * @see LocaleContext + */ + public static LocaleContextManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public LocaleContextManager() { + } /** * Registers the given {@linkplain Locale} value as the current Locale for the active thread diff --git a/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java b/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java index 961b838c..63a2e848 100644 --- a/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java +++ b/managers/context-manager-locale/src/test/java/nl/talsmasoftware/context/managers/locale/LocaleContextManagerTest.java @@ -46,7 +46,7 @@ public class LocaleContextManagerTest { private static final Locale GERMAN = Locale.GERMANY; private static final Locale DEFAULT_LOCALE = Locale.getDefault(); - private static final LocaleContextManager MANAGER = new LocaleContextManager(); + private static final LocaleContextManager MANAGER = LocaleContextManager.provider(); private ExecutorService threadpool; diff --git a/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java index d8a8e1a1..25920aa3 100644 --- a/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java +++ b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManager.java @@ -54,6 +54,34 @@ * @since 1.0.6 */ public class ContextScopeManager implements ScopeManager, ContextManager { + /** + * Singleton instance of this class. + */ + private static final ContextScopeManager INSTANCE = new ContextScopeManager(); + + /** + * Returns the singleton instance of the {@code ContextScopeManager}. + * + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The OpenTracing scope manager. + */ + public static ContextScopeManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public ContextScopeManager() { + } + @Override public Scope activate(Span span) { return new ThreadLocalSpanContext(span); diff --git a/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java index 2a62ec5d..e669c0d2 100644 --- a/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java +++ b/managers/context-manager-opentracing/src/main/java/nl/talsmasoftware/context/managers/opentracing/SpanManager.java @@ -32,6 +32,33 @@ * @author Sjoerd Talsma */ public class SpanManager implements ContextManager { + /** + * Singleton instance of this class. + */ + private static final SpanManager INSTANCE = new SpanManager(); + + /** + * Returns the singleton instance of the {@code SpanManager}. + * + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The OpenTracing Span context manager. + */ + public static SpanManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public SpanManager() { + } /** * Return the {@link GlobalTracer#activeSpan() active span}. diff --git a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java index e6b81dae..587d1ecb 100644 --- a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/ContextScopeManagerTest.java @@ -51,7 +51,7 @@ public class ContextScopeManagerTest { public void registerMockGlobalTracer() { GlobalTracerTestUtil.resetGlobalTracer(); assertThat("Pre-existing GlobalTracer", GlobalTracer.isRegistered(), is(false)); - scopeManager = new ContextScopeManager(); + scopeManager = ContextScopeManager.provider(); GlobalTracer.register(mockTracer = new MockTracer(scopeManager)); threadpool = new ContextAwareExecutorService(Executors.newCachedThreadPool()); } diff --git a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java index 78328cea..e64ea9ee 100644 --- a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/SpanManagerTest.java @@ -210,27 +210,27 @@ public String call() throws Exception { public void testClearingAllContexts() { Span span = mockTracer.buildSpan("test-span").start(); Scope scope = mockTracer.scopeManager().activate(span); - assertThat(new SpanManager().getActiveContextValue(), is(sameInstance(span))); + assertThat(SpanManager.provider().getActiveContextValue(), is(sameInstance(span))); ContextManagers.clearActiveContexts(); // TODO Test after this is merged: https://github.com/opentracing/opentracing-java/pull/313 -// assertThat(new SpanManager().getActiveContext(), is(nullValue())); + // assertThat(SpanManager.provider().getActiveContextValue(), is(nullValue())); } @Test public void testSpanManagerToString() { - assertThat(new SpanManager(), hasToString("SpanManager")); + assertThat(SpanManager.provider(), hasToString("SpanManager")); } @Test public void testSpanContextToString() { Span span = mockTracer.buildSpan("test-span").start(); - assertThat(new SpanManager().getActiveContextValue(), nullValue()); + assertThat(SpanManager.provider().getActiveContextValue(), nullValue()); Scope scope = mockTracer.scopeManager().activate(span); - assertThat(new SpanManager().getActiveContextValue(), is(span)); + assertThat(SpanManager.provider().getActiveContextValue(), is(span)); scope.close(); - assertThat(new SpanManager().getActiveContextValue(), nullValue()); + assertThat(SpanManager.provider().getActiveContextValue(), nullValue()); } } diff --git a/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java index 1db2f600..63b793dd 100644 --- a/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java +++ b/managers/context-manager-servletrequest/src/main/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManager.java @@ -26,6 +26,33 @@ * @author Sjoerd Talsma */ public final class ServletRequestContextManager implements ContextManager { + /** + * Singleton instance of this class. + */ + private static final ServletRequestContextManager INSTANCE = new ServletRequestContextManager(); + + /** + * Returns the singleton instance of the {@code ServletRequestContextManager}. + * + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The context manager for ServletRequests. + */ + public static ServletRequestContextManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public ServletRequestContextManager() { + } /** * Static utility method to obtain the current {@link ServletRequest} (if available). diff --git a/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java index 24855128..caa64b46 100644 --- a/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java +++ b/managers/context-manager-servletrequest/src/test/java/nl/talsmasoftware/context/manager/servletrequest/ServletRequestContextManagerTest.java @@ -45,31 +45,31 @@ public class ServletRequestContextManagerTest { @BeforeEach public void init() { - new ServletRequestContextManager().clear(); + ServletRequestContextManager.provider().clear(); threadpool = new ContextAwareExecutorService(Executors.newCachedThreadPool()); } @AfterEach public void cleanup() { threadpool.shutdown(); - new ServletRequestContextManager().clear(); + ServletRequestContextManager.provider().clear(); } @Test public void testContextManagerToStringValue() { - assertThat(new ServletRequestContextManager(), hasToString(ServletRequestContextManager.class.getSimpleName())); + assertThat(ServletRequestContextManager.provider(), hasToString(ServletRequestContextManager.class.getSimpleName())); } @Test public void testGetActiveContext() { - assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); + assertThat(ServletRequestContextManager.provider().getActiveContextValue(), is(nullValue())); final ServletRequest request = mock(ServletRequest.class); - Context ctx = new ServletRequestContextManager().initializeNewContext(request); + Context ctx = ServletRequestContextManager.provider().initializeNewContext(request); - assertThat(new ServletRequestContextManager().getActiveContextValue(), is(sameInstance(request))); + assertThat(ServletRequestContextManager.provider().getActiveContextValue(), is(sameInstance(request))); ctx.close(); - assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); + assertThat(ServletRequestContextManager.provider().getActiveContextValue(), is(nullValue())); } @Test @@ -77,7 +77,7 @@ public void testCurrentServletRequest() { assertThat(ServletRequestContextManager.currentServletRequest(), is(nullValue())); final ServletRequest request = mock(ServletRequest.class); - Context ctx = new ServletRequestContextManager().initializeNewContext(request); + Context ctx = ServletRequestContextManager.provider().initializeNewContext(request); assertThat(ServletRequestContextManager.currentServletRequest(), is(sameInstance(request))); ctx.close(); @@ -87,18 +87,18 @@ public void testCurrentServletRequest() { @Test public void testClearableImplementation() { final ServletRequest request = mock(ServletRequest.class); - Context ctx = new ServletRequestContextManager().initializeNewContext(request); + Context ctx = ServletRequestContextManager.provider().initializeNewContext(request); assertThat(ctx.getValue(), is(sameInstance(request))); - assertThat(new ServletRequestContextManager().getActiveContextValue(), is(sameInstance(request))); + assertThat(ServletRequestContextManager.provider().getActiveContextValue(), is(sameInstance(request))); ContextManagers.clearActiveContexts(); assertThat(ctx.getValue(), is(nullValue())); // must have been closed - assertThat(new ServletRequestContextManager().getActiveContextValue(), is(nullValue())); + assertThat(ServletRequestContextManager.provider().getActiveContextValue(), is(nullValue())); } @Test public void testPropagationInOtherThreads() throws ExecutionException, InterruptedException { - ServletRequestContextManager manager = new ServletRequestContextManager(); + ServletRequestContextManager manager = ServletRequestContextManager.provider(); ServletRequest request1 = mock(ServletRequest.class); ServletRequest request2 = mock(ServletRequest.class); @@ -128,7 +128,7 @@ public ServletRequest call() throws InterruptedException { @Test public void testServletRequestContextToString() { - ServletRequestContextManager manager = new ServletRequestContextManager(); + ServletRequestContextManager manager = ServletRequestContextManager.provider(); assertThat(manager.getActiveContextValue(), nullValue()); ServletRequest request = mock(ServletRequest.class); diff --git a/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java index 3f2e2511..e45c1973 100644 --- a/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java +++ b/managers/context-manager-slf4j/src/main/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManager.java @@ -44,6 +44,32 @@ * @author Sjoerd Talsma */ public class Slf4jMdcManager implements ContextManager> { + /** + * Singleton instance of this class. + */ + private static final Slf4jMdcManager INSTANCE = new Slf4jMdcManager(); + + /** + * Returns the singleton instance of the {@code Slf4jMdcManager}. + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The Slf4j {@code MDC} manager. + */ + public static Slf4jMdcManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public Slf4jMdcManager() { + } /** * Initializes a new MDC context populated by the specified values. diff --git a/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java b/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java index 4acc184d..55481537 100644 --- a/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java +++ b/managers/context-manager-slf4j/src/test/java/nl/talsmasoftware/context/managers/slf4j/mdc/Slf4jMdcManagerTest.java @@ -94,12 +94,12 @@ public void testMdcItemRestoration() throws Exception { @Test public void testSlf4jMdcManagerToString() { - assertThat(new Slf4jMdcManager(), hasToString("Slf4jMdcManager")); + assertThat(Slf4jMdcManager.provider(), hasToString("Slf4jMdcManager")); } @Test public void testSlf4jMdcContextToString() { - Slf4jMdcManager mgr = new Slf4jMdcManager(); + Slf4jMdcManager mgr = Slf4jMdcManager.provider(); MDC.put("dummy", "value"); Map mdc = MDC.getCopyOfContextMap(); assertThat(mgr.getActiveContextValue(), equalTo(mdc)); diff --git a/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java b/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java index e0f7cb27..6162ba9e 100644 --- a/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java +++ b/managers/context-manager-spring-security/src/main/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManager.java @@ -33,6 +33,32 @@ * @author Sjoerd Talsma */ public class SpringSecurityContextManager implements ContextManager { + /** + * Singleton instance of this class. + */ + private static final SpringSecurityContextManager INSTANCE = new SpringSecurityContextManager(); + + /** + * Returns the singleton instance of the {@code SpringSecurityContextManager}. + *

    + * The ServiceLoader supports a static {@code provider()} method to resolve services since Java 9. + * + * @return The Spring Security context manager. + */ + public static SpringSecurityContextManager provider() { + return INSTANCE; + } + + /** + * Creates a new context manager. + * + * @see #provider() + * @deprecated This constructor only exists for usage by Java 8 {@code ServiceLoader}. The singleton instance + * obtained from {@link #provider()} should be used to avoid unnecessary instantiations. + */ + @Deprecated + public SpringSecurityContextManager() { + } /** * Creates a new Spring {@linkplain SecurityContext} and sets the {@linkplain Authentication value} in it. diff --git a/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java index 460e03af..bb92a808 100644 --- a/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java +++ b/managers/context-manager-spring-security/src/test/java/nl/talsmasoftware/context/managers/springsecurity/SpringSecurityContextManagerTest.java @@ -79,7 +79,7 @@ private static void setAuthentication(String name) { @Test public void testWithoutAnyAuthentication() { - assertThat(new SpringSecurityContextManager().getActiveContextValue(), is(nullValue())); + assertThat(SpringSecurityContextManager.provider().getActiveContextValue(), is(nullValue())); } @Test @@ -115,10 +115,10 @@ public void testAuthenticationReactivation() throws Exception { @Test public void testClearableImplementation() { setAuthentication("Vincent Vega"); - assertThat(new SpringSecurityContextManager().getActiveContextValue().getName(), is("Vincent Vega")); + assertThat(SpringSecurityContextManager.provider().getActiveContextValue().getName(), is("Vincent Vega")); ContextManagers.clearActiveContexts(); - assertThat(new SpringSecurityContextManager().getActiveContextValue(), is(nullValue())); + assertThat(SpringSecurityContextManager.provider().getActiveContextValue(), is(nullValue())); } } From b93214f8f02a5a51d2b951a7e687346c02abfc55 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 10:57:58 +0100 Subject: [PATCH 32/41] Minor documentation improvements. Signed-off-by: Sjoerd Talsma --- .../java/nl/talsmasoftware/context/api/ContextManager.java | 3 +++ .../java/nl/talsmasoftware/context/api/ContextSnapshot.java | 2 ++ readme.md | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java index cf7803d7..0d5b58b8 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java @@ -44,6 +44,7 @@ public interface ContextManager { * * @return The value of the active context, or {@code null} if no context is active. * @see Context#getValue() + * @since 2.0.0 */ T getActiveContextValue(); @@ -61,6 +62,8 @@ public interface ContextManager { * *

    * This method normally should only get called by {@code ContextManagers.clearActiveContexts()}. + * + * @since 2.0.0 */ void clear(); diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java index 191ceea4..9fdc1b52 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java @@ -66,6 +66,8 @@ public interface ContextSnapshot { * *

    * It is strongly advised to only use reactivation with try-with-resources code blocks. + * + * @since 2.0.0 */ interface Reactivation extends Closeable { /** diff --git a/readme.md b/readme.md index c35cf7b7..89ea2692 100644 --- a/readme.md +++ b/readme.md @@ -147,7 +147,7 @@ context snapshots along with time spent in each individual `ContextManager`. ### Logging performance On a development machine, you can get timing for each snapshot by turning on logging -for `nl.talsmasoftware.context.Timing` at `FINEST` or `TRACE` level +for `nl.talsmasoftware.context.core.Timers` at `FINEST` or `TRACE` level (depending on your logger of choice). Please **do not** turn this on in production as the logging overhead will most likely have a noticable impact on your application. From 9ede75b5a22a56935370e3d3a24de6c797dca339 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 11:08:23 +0100 Subject: [PATCH 33/41] Simplification of bom; remove explicit sources and javadoc classifier dependencies. Signed-off-by: Sjoerd Talsma --- context-propagation-bom/pom.xml | 142 +------------------------------- 1 file changed, 1 insertion(+), 141 deletions(-) diff --git a/context-propagation-bom/pom.xml b/context-propagation-bom/pom.xml index 02a52f49..99fa7c94 100644 --- a/context-propagation-bom/pom.xml +++ b/context-propagation-bom/pom.xml @@ -50,35 +50,10 @@ context-propagation-api ${project.version} - - ${project.groupId} - context-propagation-api - ${project.version} - javadoc - - - ${project.groupId} - context-propagation-api - ${project.version} - sources - - - - ${project.groupId} - context-propagation-core - ${project.version} - - - ${project.groupId} - context-propagation-core - ${project.version} - javadoc - ${project.groupId} context-propagation-core ${project.version} - sources @@ -88,163 +63,48 @@ context-timer-metrics ${project.version} - - ${project.groupId}.timers - context-timer-metrics - ${project.version} - javadoc - - - ${project.groupId}.timers - context-timer-metrics - ${project.version} - sources - - - - ${project.groupId}.timers - context-timer-micrometer - ${project.version} - ${project.groupId}.timers context-timer-micrometer ${project.version} - javadoc - - ${project.groupId}.timers - context-timer-micrometer - ${project.version} - sources - - ${project.groupId}.timers context-timer-opentracing ${project.version} - - ${project.groupId}.timers - context-timer-opentracing - ${project.version} - javadoc - - - ${project.groupId}.timers - context-timer-opentracing - ${project.version} - sources - - + ${project.groupId}.managers context-manager-locale ${project.version} - - ${project.groupId}.managers - context-manager-locale - ${project.version} - javadoc - - - ${project.groupId}.managers - context-manager-locale - ${project.version} - sources - - - - ${project.groupId}.managers - context-manager-log4j2 - ${project.version} - - - ${project.groupId}.managers - context-manager-log4j2 - ${project.version} - javadoc - ${project.groupId}.managers context-manager-log4j2 ${project.version} - sources - - - - ${project.groupId}.managers - context-manager-opentracing - ${project.version} ${project.groupId}.managers context-manager-opentracing ${project.version} - javadoc - - ${project.groupId}.managers - context-manager-opentracing - ${project.version} - sources - - ${project.groupId}.managers context-manager-servletrequest ${project.version} - - ${project.groupId}.managers - context-manager-servletrequest - ${project.version} - javadoc - - - ${project.groupId}.managers - context-manager-servletrequest - ${project.version} - sources - - ${project.groupId}.managers context-manager-slf4j ${project.version} - - ${project.groupId}.managers - context-manager-slf4j - ${project.version} - javadoc - - - ${project.groupId}.managers - context-manager-slf4j - ${project.version} - sources - - - - ${project.groupId}.managers - context-manager-spring-security - ${project.version} - - - ${project.groupId}.managers - context-manager-spring-security - ${project.version} - javadoc - ${project.groupId}.managers context-manager-spring-security ${project.version} - sources From 1142c57a45034a3936fe49b68823cd7959cde00f Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 11:20:18 +0100 Subject: [PATCH 34/41] Simplify logging when no ContextManagers are found. Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 99c6d87d..fed5219d 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -96,11 +96,12 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext.exception"); } } - if (managerStart == null) { - NoContextManagersFound noContextManagersFound = new NoContextManagersFound(); - LOGGER.log(Level.INFO, noContextManagersFound.getMessage(), noContextManagersFound); + final ContextSnapshotImpl result = new ContextSnapshotImpl(managers, values); + if (managerStart == null && LOGGER.isLoggable(Level.FINER)) { + LOGGER.finer(result + " was created but no ContextManagers were found! " + + " Thead=" + Thread.currentThread() + + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); } - ContextSnapshotImpl result = new ContextSnapshotImpl(managers, values); Timers.timed(System.nanoTime() - start, ContextManagers.class, "createContextSnapshot"); return result; } @@ -139,9 +140,10 @@ public static void clearActiveContexts() { Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear.exception"); } } - if (managerStart == null) { - NoContextManagersFound noContextManagersFound = new NoContextManagersFound(); - LOGGER.log(Level.INFO, noContextManagersFound.getMessage(), noContextManagersFound); + if (managerStart == null && LOGGER.isLoggable(Level.FINER)) { + LOGGER.finer("No ContextManagers were cleared because none were found! " + + " Thead=" + Thread.currentThread() + + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); } Timers.timed(System.nanoTime() - start, ContextManagers.class, "clearActiveContexts"); } @@ -300,18 +302,7 @@ public void close() { @Override public String toString() { - return "ReactivatedContext{size=" + reactivated.size() + '}'; - } - } - - /** - * Exception that we don't actually throw, but it helps track the issue if we log it including the stacktrace. - */ - private static class NoContextManagersFound extends RuntimeException { - private NoContextManagersFound() { - super("Context snapshot was created but no ContextManagers were found!" - + " Thread=" + Thread.currentThread() - + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); + return "ContextSnapshot.Reactivation{size=" + reactivated.size() + '}'; } } } From 8a1842550e064b296f3c17cbe58393084bed33e0 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 13:06:09 +0100 Subject: [PATCH 35/41] Simplifying ContextManagers and avoid new Lists when creating or reactivating snapshots. This should be a significant performance improvement. Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 138 ++++++------------ .../context/core/ServiceCache.java | 91 ++++++++++++ .../talsmasoftware/context/core/Timers.java | 2 +- .../context/core/ContextSnapshotTest.java | 9 +- 4 files changed, 140 insertions(+), 100 deletions(-) create mode 100644 context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ServiceCache.java diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index fed5219d..e47e56b6 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -19,13 +19,9 @@ import nl.talsmasoftware.context.api.ContextManager; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; -import nl.talsmasoftware.context.api.ContextTimer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; import java.util.List; -import java.util.ServiceLoader; +import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; @@ -43,15 +39,6 @@ public final class ContextManagers { private static final Logger LOGGER = Logger.getLogger(ContextManagers.class.getName()); - /** - * Sometimes a single, fixed classloader may be necessary (e.g. #97) - */ - private static volatile ClassLoader classLoaderOverride = null; - - private static volatile List> contextManagers = null; - - private static volatile List contextTimers = null; - /** * Private constructor to avoid instantiation of this class. */ @@ -72,32 +59,26 @@ private ContextManagers() { * @return A new snapshot that can be reactivated elsewhere (e.g. a background thread) * within a try-with-resources construct. */ + @SuppressWarnings("rawtypes") public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapshot() { final long start = System.nanoTime(); - final List> managers = new LinkedList<>(); - final List values = new LinkedList<>(); - Long managerStart = null; - for (ContextManager manager : getContextManagers()) { - managerStart = System.nanoTime(); + final List managers = ServiceCache.cached(ContextManager.class); + final Object[] values = new Object[managers.size()]; + + for (ListIterator it = managers.listIterator(); it.hasNext(); ) { + final ContextManager manager = it.next(); + long managerStart = System.nanoTime(); try { - final Object activeContextValue = manager.getActiveContextValue(); - if (activeContextValue != null) { - values.add(activeContextValue); - managers.add(manager); - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Active context value of " + manager + " added to new snapshot: " + activeContextValue); - } - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext"); - } else if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.log(Level.FINEST, "There is no active context for " + manager + " in this snapshot."); - } + values[it.previousIndex()] = getActiveContextValue(manager); + Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext"); } catch (RuntimeException rte) { - LOGGER.log(Level.WARNING, "Exception obtaining active context from " + manager + " for snapshot.", rte); + LOGGER.log(Level.WARNING, "Error obtaining active context from " + manager + " (in thread " + Thread.currentThread().getName() + ").", rte); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext.exception"); } } + final ContextSnapshotImpl result = new ContextSnapshotImpl(managers, values); - if (managerStart == null && LOGGER.isLoggable(Level.FINER)) { + if (managers.isEmpty() && LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(result + " was created but no ContextManagers were found! " + " Thead=" + Thread.currentThread() + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); @@ -126,17 +107,14 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho public static void clearActiveContexts() { final long start = System.nanoTime(); Long managerStart = null; - for (ContextManager manager : getContextManagers()) { + for (ContextManager manager : ServiceCache.cached(ContextManager.class)) { managerStart = System.nanoTime(); try { - manager.clear(); - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Active context of " + manager + " was cleared."); - } + clear(manager); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear"); } catch (RuntimeException rte) { - LOGGER.log(Level.WARNING, "Exception clearing active context from " + manager + ".", rte); - contextManagers = null; + LOGGER.log(Level.WARNING, "Error clearing active context from " + manager + ".", rte); + ServiceCache.clear(); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear.exception"); } } @@ -170,48 +148,20 @@ public static void clearActiveContexts() { * @since 1.0.5 */ public static synchronized void useClassLoader(ClassLoader classLoader) { - if (classLoaderOverride == classLoader) { - LOGGER.finest(() -> "Maintaining classloader override as " + classLoader + " (unchanged)"); - return; - } - LOGGER.fine(() -> "Updating classloader override to " + classLoader + " (was: " + classLoaderOverride + ")"); - classLoaderOverride = classLoader; - contextManagers = null; - contextTimers = null; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static List> getContextManagers() { - if (contextManagers == null) { - synchronized (ContextManagers.class) { - if (contextManagers == null) { - contextManagers = (List) load(ContextManager.class); - } - } - } - return contextManagers; + ServiceCache.useClassLoader(classLoader); } - static List getContextTimers() { - if (contextTimers == null) { - synchronized (ContextManagers.class) { - if (contextTimers == null) { - contextTimers = load(ContextTimer.class); - } - } - } - return contextTimers; + private static Object getActiveContextValue(ContextManager manager) { + final Object activeContextValue = manager.getActiveContextValue(); + LOGGER.finest(() -> activeContextValue == null + ? "There is no active context value for " + manager + " (in thread " + Thread.currentThread().getName() + ")." + : "Active context value of " + manager + " in " + Thread.currentThread().getName() + ": " + activeContextValue); + return activeContextValue; } - private static List load(Class type) { - ArrayList list = new ArrayList<>(); - if (classLoaderOverride == null) { - ServiceLoader.load(type).forEach(list::add); - } else { - ServiceLoader.load(type, classLoaderOverride).forEach(list::add); - } - list.trimToSize(); - return Collections.unmodifiableList(list); + private static void clear(ContextManager manager) { + manager.clear(); + LOGGER.finest(() -> "Active context of " + manager + " was cleared."); } /** @@ -219,22 +169,23 @@ private static List load(Class type) { * snapshot in each corresponding {@link ContextManager}. */ @SuppressWarnings("rawtypes") - private static final class ContextSnapshotImpl implements nl.talsmasoftware.context.api.ContextSnapshot { - private static final ContextManager[] MANAGER_ARRAY = new ContextManager[0]; - private final ContextManager[] managers; + private static final class ContextSnapshotImpl implements ContextSnapshot { + private final List managers; private final Object[] values; - private ContextSnapshotImpl(List> managers, List values) { - this.managers = managers.toArray(MANAGER_ARRAY); - this.values = values.toArray(); + private ContextSnapshotImpl(List managers, Object[] values) { + this.managers = managers; + this.values = values; } public Reactivation reactivate() { final long start = System.nanoTime(); - final List> reactivatedContexts = new ArrayList>(managers.length); + final Context[] reactivatedContexts = new Context[managers.size()]; try { - for (int i = 0; i < managers.length && i < values.length; i++) { - reactivatedContexts.add(reactivate(managers[i], values[i])); + for (ListIterator it = managers.listIterator(); it.hasNext(); ) { + final ContextManager manager = it.next(); + final Object value = values[it.previousIndex()]; + reactivatedContexts[it.previousIndex()] = value != null ? reactivate(manager, value) : null; } ReactivationImpl reactivation = new ReactivationImpl(reactivatedContexts); Timers.timed(System.nanoTime() - start, nl.talsmasoftware.context.api.ContextSnapshot.class, "reactivate"); @@ -251,7 +202,7 @@ public Reactivation reactivate() { reactivationException.addSuppressed(rte); } } - contextManagers = null; + ServiceCache.clear(); throw reactivationException; } } @@ -269,7 +220,7 @@ private Context reactivate(ContextManager contextManager, Object snapshotValue) @Override public String toString() { - return "ContextSnapshot{size=" + managers.length + '}'; + return "ContextSnapshot{size=" + managers.size() + '}'; } } @@ -278,18 +229,19 @@ public String toString() { * when it is closed itself.
    * This context contains no meaningful value in itself and purely exists to close the reactivated contexts. */ + @SuppressWarnings("rawtypes") private static final class ReactivationImpl implements Reactivation { - private final List> reactivated; + private final Context[] reactivated; - private ReactivationImpl(List> reactivated) { + private ReactivationImpl(Context[] reactivated) { this.reactivated = reactivated; } public void close() { RuntimeException closeException = null; // close in reverse order of reactivation - for (int i = this.reactivated.size() - 1; i >= 0; i--) { - Context reactivated = this.reactivated.get(i); + for (int i = this.reactivated.length - 1; i >= 0; i--) { + Context reactivated = this.reactivated[i]; if (reactivated != null) try { reactivated.close(); } catch (RuntimeException rte) { @@ -302,7 +254,7 @@ public void close() { @Override public String toString() { - return "ContextSnapshot.Reactivation{size=" + reactivated.size() + '}'; + return "ContextSnapshot.Reactivation{size=" + reactivated.length + '}'; } } } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ServiceCache.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ServiceCache.java new file mode 100644 index 00000000..18d8122d --- /dev/null +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ServiceCache.java @@ -0,0 +1,91 @@ +/* + * Copyright 2016-2024 Talsma ICT + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package nl.talsmasoftware.context.core; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.ServiceLoader; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.logging.Logger; + +/** + * Cache for resolved services. + * + *

    + * This is required because the ServiceLoader itself is not thread-safe due to its internal lazy iterator. + */ +class ServiceCache { + private static final Logger LOGGER = Logger.getLogger(ServiceCache.class.getName()); + + /** + * Internal concurrent map as cache. + */ + @SuppressWarnings("rawtypes") + private static final ConcurrentMap CACHE = new ConcurrentHashMap<>(); + + /** + * Sometimes a single, fixed classloader may be necessary (e.g. #97) + */ + private static volatile ClassLoader classLoaderOverride = null; + + static synchronized void useClassLoader(ClassLoader classLoader) { + if (classLoaderOverride == classLoader) { + LOGGER.finest(() -> "Maintaining classloader override as " + classLoader + " (unchanged)"); + return; + } + LOGGER.fine(() -> "Updating classloader override to " + classLoader + " (was: " + classLoaderOverride + ")"); + classLoaderOverride = classLoader; + CACHE.clear(); + } + + @SuppressWarnings("unchecked") + static List cached(Class serviceClass) { + return (List) CACHE.computeIfAbsent(serviceClass, ServiceCache::load); + } + + static void clear() { + CACHE.clear(); + } + + /** + * Loads the service implementations of the requested type. + * + *

    + * This method is synchronized because ServiceLoader is not thread-safe. + * Fortunately this only gets called after a cache miss, so should not affect performance. + * + *

    + * The returned {@code List} will be {@linkplain Collections#unmodifiableList(List) unmodifiable}. + * + * @param serviceType The service type to load. + * @param The service type to load. + * @return Unmodifiable list of service implementations. + */ + private synchronized static List load(Class serviceType) { + final ArrayList services = new ArrayList<>(); + final ServiceLoader loader = classLoaderOverride == null + ? ServiceLoader.load(serviceType) + : ServiceLoader.load(serviceType, classLoaderOverride); + for (T service : loader) { + services.add(service); + } + services.trimToSize(); + // TODO debug logging + return Collections.unmodifiableList(services); + } +} diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java index 4b4da233..32c58760 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java @@ -25,7 +25,7 @@ final class Timers { private static final Logger TIMING_LOGGER = Logger.getLogger(Timers.class.getName()); static void timed(long durationNanos, Class type, String method) { - for (ContextTimer delegate : ContextManagers.getContextTimers()) { + for (ContextTimer delegate : ServiceCache.cached(ContextTimer.class)) { delegate.update(type, method, durationNanos, TimeUnit.NANOSECONDS); } if (TIMING_LOGGER.isLoggable(Level.FINEST)) { diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java index 865ca7d6..637c522f 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java @@ -20,7 +20,6 @@ import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.Test; -import java.io.Closeable; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; @@ -36,9 +35,7 @@ public class ContextSnapshotTest { @Test public void testSnapshotToString() { - try (Context ctx = MGR.initializeNewContext("Dummy value")) { - assertThat(ContextManagers.createContextSnapshot(), hasToString(startsWith("ContextSnapshot{size="))); - } + assertThat(ContextManagers.createContextSnapshot(), hasToString(startsWith("ContextSnapshot{size="))); } @Test @@ -48,9 +45,9 @@ public void testSnapshotReactivate() throws IOException { try (Context ctx2 = MGR.initializeNewContext("New value")) { assertThat(MGR.getActiveContextValue(), is("New value")); - try (Closeable reactivation = snapshot.reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshot.reactivate()) { assertThat(MGR.getActiveContextValue(), is("Old value")); - assertThat(reactivation, hasToString(startsWith("ReactivatedContext{size="))); + assertThat(reactivation, hasToString(startsWith("ContextSnapshot.Reactivation{size="))); } assertThat(MGR.getActiveContextValue(), is("New value")); From b4dcb843641dd7caeaee65c029ed42d8713cd2d5 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 13:12:33 +0100 Subject: [PATCH 36/41] Simplifying ContextManagers and avoid new Lists when creating or reactivating snapshots. This should be a significant performance improvement. Signed-off-by: Sjoerd Talsma --- .../java/nl/talsmasoftware/context/core/ContextManagers.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index e47e56b6..56f38456 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -62,7 +62,7 @@ private ContextManagers() { @SuppressWarnings("rawtypes") public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapshot() { final long start = System.nanoTime(); - final List managers = ServiceCache.cached(ContextManager.class); + final List managers = ServiceCache.cached(ContextManager.class); // Cached list is immutable final Object[] values = new Object[managers.size()]; for (ListIterator it = managers.listIterator(); it.hasNext(); ) { From ffc4b9b4d0a97f0997e4c2467cba7403a5c68117 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 13:27:56 +0100 Subject: [PATCH 37/41] Simplification; replace ListIterator by index for-loop. Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 56f38456..1b79cbe5 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -21,7 +21,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot.Reactivation; import java.util.List; -import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; @@ -65,11 +64,11 @@ public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapsho final List managers = ServiceCache.cached(ContextManager.class); // Cached list is immutable final Object[] values = new Object[managers.size()]; - for (ListIterator it = managers.listIterator(); it.hasNext(); ) { - final ContextManager manager = it.next(); + for (int i = 0; i < values.length; i++) { + final ContextManager manager = managers.get(i); long managerStart = System.nanoTime(); try { - values[it.previousIndex()] = getActiveContextValue(manager); + values[i] = getActiveContextValue(manager); Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext"); } catch (RuntimeException rte) { LOGGER.log(Level.WARNING, "Error obtaining active context from " + manager + " (in thread " + Thread.currentThread().getName() + ").", rte); @@ -170,6 +169,7 @@ private static void clear(ContextManager manager) { */ @SuppressWarnings("rawtypes") private static final class ContextSnapshotImpl implements ContextSnapshot { + // TODO extract this inner class? private final List managers; private final Object[] values; @@ -181,16 +181,17 @@ private ContextSnapshotImpl(List managers, Object[] values) { public Reactivation reactivate() { final long start = System.nanoTime(); final Context[] reactivatedContexts = new Context[managers.size()]; + try { - for (ListIterator it = managers.listIterator(); it.hasNext(); ) { - final ContextManager manager = it.next(); - final Object value = values[it.previousIndex()]; - reactivatedContexts[it.previousIndex()] = value != null ? reactivate(manager, value) : null; + for (int i = 0; i < values.length; i++) { + reactivatedContexts[i] = reactivate(managers.get(i), values[i]); } + ReactivationImpl reactivation = new ReactivationImpl(reactivatedContexts); Timers.timed(System.nanoTime() - start, nl.talsmasoftware.context.api.ContextSnapshot.class, "reactivate"); return reactivation; } catch (RuntimeException reactivationException) { + // TODO think about simplifying by catching & handling in reactivate(manager, value) method for (Context alreadyReactivated : reactivatedContexts) { if (alreadyReactivated != null) try { if (LOGGER.isLoggable(Level.FINEST)) { @@ -210,6 +211,7 @@ public Reactivation reactivate() { @SuppressWarnings("unchecked") // As we got the values from the managers themselves, they must also accept them! private Context reactivate(ContextManager contextManager, Object snapshotValue) { long start = System.nanoTime(); + if (snapshotValue == null) return null; Context reactivated = contextManager.initializeNewContext(snapshotValue); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Context reactivated from snapshot by " + contextManager + ": " + reactivated + "."); @@ -231,6 +233,7 @@ public String toString() { */ @SuppressWarnings("rawtypes") private static final class ReactivationImpl implements Reactivation { + // TODO extract this inner class? private final Context[] reactivated; private ReactivationImpl(Context[] reactivated) { From f7e3502e0f1a4a46cbc60a39b93b40d91d84ca45 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 14:18:52 +0100 Subject: [PATCH 38/41] Clean up: remove Closeable / IOException from test that were introduced temporarily. Signed-off-by: Sjoerd Talsma --- .../context/core/ContextManagers.java | 4 ++-- .../core/function/BiConsumerWithContext.java | 10 ++-------- .../core/function/BiFunctionWithContext.java | 10 ++-------- .../core/function/BiPredicateWithContext.java | 14 +++----------- .../core/function/BooleanSupplierWithContext.java | 6 +----- .../context/core/function/ConsumerWithContext.java | 10 ++-------- .../context/core/function/FunctionWithContext.java | 14 +++----------- .../core/function/PredicateWithContext.java | 14 +++----------- .../context/core/function/RunnableWithContext.java | 6 +----- .../context/core/function/SupplierWithContext.java | 6 +----- .../context/core/ContextManagersTest.java | 10 ++++------ .../context/core/ContextSnapshotTest.java | 4 +--- .../context/core/NoContextManagersTest.java | 10 ++++------ .../core/function/BiFunctionWithContextTest.java | 6 ++---- .../core/function/BiPredicateWithContextTest.java | 6 ++---- .../function/BinaryOperatorWithContextTest.java | 6 ++---- .../function/BooleanSupplierWithContextTest.java | 6 ++---- .../core/function/ConsumerWithContextTest.java | 10 +++------- .../core/function/FunctionWithContextTest.java | 6 ++---- .../core/function/PredicateWithContextTest.java | 6 ++---- .../core/function/RunnableWithContextTest.java | 6 ++---- .../core/function/SupplierWithContextTest.java | 6 ++---- .../function/UnaryOperatorWithContextTest.java | 6 ++---- .../Log4j2ThreadContextManagerTest.java | 6 ++---- .../context/managers/opentracing/Issue30Test.java | 7 ++----- 25 files changed, 54 insertions(+), 141 deletions(-) diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 1b79cbe5..8ae4cdae 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -59,7 +59,7 @@ private ContextManagers() { * within a try-with-resources construct. */ @SuppressWarnings("rawtypes") - public static nl.talsmasoftware.context.api.ContextSnapshot createContextSnapshot() { + public static ContextSnapshot createContextSnapshot() { final long start = System.nanoTime(); final List managers = ServiceCache.cached(ContextManager.class); // Cached list is immutable final Object[] values = new Object[managers.size()]; @@ -188,7 +188,7 @@ public Reactivation reactivate() { } ReactivationImpl reactivation = new ReactivationImpl(reactivatedContexts); - Timers.timed(System.nanoTime() - start, nl.talsmasoftware.context.api.ContextSnapshot.class, "reactivate"); + Timers.timed(System.nanoTime() - start, ContextSnapshot.class, "reactivate"); return reactivation; } catch (RuntimeException reactivationException) { // TODO think about simplifying by catching & handling in reactivate(manager, value) method diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java index f446c85e..790b3d8f 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiConsumerWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; @@ -51,7 +49,7 @@ protected BiConsumerWithContext(Supplier supplier, BiConsumer andThen(BiConsumer after) { requireNonNull(after, "Cannot post-process with after bi-consumer ."); return (l, r) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(l, r); @@ -83,8 +79,6 @@ public BiConsumer andThen(BiConsumer after) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java index b5e8cc78..66384f94 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiFunctionWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; @@ -52,7 +50,7 @@ protected BiFunctionWithContext(Supplier supplier, BiFunction BiFunction andThen(Function after) { requireNonNull(after, "Cannot post-process bi-function with after function ."); return (IN1 in1, IN2 in2) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); return after.apply(delegate().apply(in1, in2)); @@ -83,8 +79,6 @@ public BiFunction andThen(Function af contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java index 508c0858..050e61c9 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BiPredicateWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Supplier; @@ -51,7 +49,7 @@ protected BiPredicateWithContext(Supplier supplier, BiPredicate @Override public boolean test(IN1 in1, IN2 in2) { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating test method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2); @@ -62,8 +60,6 @@ public boolean test(IN1 in1, IN2 in2) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } } @@ -71,7 +67,7 @@ public boolean test(IN1 in1, IN2 in2) { public BiPredicate and(BiPredicate other) { requireNonNull(other, "Cannot combine bi-predicate with 'and' ."); return (IN1 in1, IN2 in2) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'and' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2) && other.test(in1, in2); @@ -82,8 +78,6 @@ public BiPredicate and(BiPredicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } @@ -92,7 +86,7 @@ public BiPredicate and(BiPredicate other) { public BiPredicate or(BiPredicate other) { requireNonNull(other, "Cannot combine bi-predicate with 'or' ."); return (IN1 in1, IN2 in2) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'or' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(in1, in2) || other.test(in1, in2); @@ -103,8 +97,6 @@ public BiPredicate or(BiPredicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java index 88bedf5f..a6e405aa 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Supplier; @@ -49,7 +47,7 @@ protected BooleanSupplierWithContext(Supplier supplier, Boolean @Override public boolean getAsBoolean() { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating getAsBoolean method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().getAsBoolean(); @@ -60,8 +58,6 @@ public boolean getAsBoolean() { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java index c9ca7392..fc483b2c 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/ConsumerWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -50,7 +48,7 @@ protected ConsumerWithContext(Supplier supplier, Consumer de @Override public void accept(T t) { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating accept method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(t); @@ -61,8 +59,6 @@ public void accept(T t) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new IllegalStateException("Error closing snapshot reactivation: " + e.getMessage(), e); } } @@ -70,7 +66,7 @@ public void accept(T t) { public Consumer andThen(Consumer after) { requireNonNull(after, "Cannot follow ConsumerWithContext with after consumer ."); return (T t) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); delegate().accept(t); @@ -82,8 +78,6 @@ public Consumer andThen(Consumer after) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java index b4d250c8..6b9d4bf8 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/FunctionWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -50,7 +48,7 @@ protected FunctionWithContext(Supplier supplier, Function Function compose(Function before) { requireNonNull(before, "Cannot compose with before function ."); return (V v) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating compose method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().apply(before.apply(v)); @@ -80,8 +76,6 @@ public Function compose(Function before) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } @@ -89,7 +83,7 @@ public Function compose(Function before) { public Function andThen(Function after) { requireNonNull(after, "Cannot transform with after function ."); return (IN in) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating andThen method with {0} to {1}.", new Object[]{context, delegate()}); return after.apply(delegate().apply(in)); @@ -100,8 +94,6 @@ public Function andThen(Function after) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java index 285fb320..4aea7403 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/PredicateWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -51,7 +49,7 @@ protected PredicateWithContext(Supplier supplier, Predicate @Override public boolean test(T t) { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating test method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t); @@ -62,8 +60,6 @@ public boolean test(T t) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } } @@ -71,7 +67,7 @@ public boolean test(T t) { public Predicate and(Predicate other) { requireNonNull(other, "Cannot combine predicate with 'and' ."); return (t) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'and' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t) && other.test(t); @@ -82,8 +78,6 @@ public Predicate and(Predicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } @@ -92,7 +86,7 @@ public Predicate and(Predicate other) { public Predicate or(Predicate other) { requireNonNull(other, "Cannot combine predicate with 'or' ."); return (t) -> { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating 'or' method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().test(t) || other.test(t); @@ -103,8 +97,6 @@ public Predicate or(Predicate other) { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }; } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java index ac552c7e..497fe570 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/RunnableWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -72,7 +70,7 @@ protected RunnableWithContext(Supplier supplier, Runnable deleg @Override public void run() { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating run method with {0} to {1}.", new Object[]{context, delegate()}); delegate().run(); @@ -83,8 +81,6 @@ public void run() { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java index 9a2bcfab..86d0034f 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/SupplierWithContext.java @@ -18,8 +18,6 @@ import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.core.ContextManagers; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; @@ -48,7 +46,7 @@ protected SupplierWithContext(Supplier snapshotSupplier, Suppli @Override public T get() { - try (Closeable context = snapshot().reactivate()) { + try (ContextSnapshot.Reactivation context = snapshot().reactivate()) { try { // inner 'try' is needed: https://github.com/talsma-ict/context-propagation/pull/56#discussion_r201590623 LOGGER.log(Level.FINEST, "Delegating get method with {0} to {1}.", new Object[]{context, delegate()}); return delegate().get(); @@ -59,8 +57,6 @@ public T get() { contextSnapshotConsumer.accept(resultSnapshot); } } - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); } } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index 9380df80..fb3d5295 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -26,8 +26,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -82,7 +80,7 @@ public void testUnsupportedConstructor() { } @Test - public void testSnapshot_inSameThread() throws IOException { + public void testSnapshot_inSameThread() { dummyManager.clear(); MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); @@ -99,7 +97,7 @@ public void testSnapshot_inSameThread() throws IOException { MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // Reactivate snapshot: ctx1 -> ctx2 -> ctx3 -> ctx2' - Closeable reactivation = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); reactivation.close(); @@ -173,14 +171,14 @@ public ContextSnapshot call() throws Exception { } @Test - public void testCreateSnapshot_ExceptionHandling() throws IOException { + public void testCreateSnapshot_ExceptionHandling() { ThrowingContextManager.onGet = new IllegalStateException("No active context!"); Context ctx = new DummyContext("blah"); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx.close(); MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); - Closeable reactivation = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); MatcherAssert.assertThat(DummyContext.currentValue(), is("blah")); reactivation.close(); MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java index 637c522f..002948aa 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextSnapshotTest.java @@ -20,8 +20,6 @@ import nl.talsmasoftware.context.dummy.DummyContextManager; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; @@ -39,7 +37,7 @@ public void testSnapshotToString() { } @Test - public void testSnapshotReactivate() throws IOException { + public void testSnapshotReactivate() { try (Context ctx = MGR.initializeNewContext("Old value")) { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); try (Context ctx2 = MGR.initializeNewContext("New value")) { diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java index 6ae54665..c7ede91b 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/NoContextManagersTest.java @@ -23,9 +23,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; import java.io.File; -import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -50,21 +48,21 @@ public void resetDefaultClassLoader() { } @Test - public void testReactivate_withoutContextManagers() throws IOException { + public void testReactivate_withoutContextManagers() { Context ctx1 = new DummyContext("foo"); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx1.close(); - Closeable reactivated = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivated = snapshot.reactivate(); reactivated.close(); } @Test - public void testCreateSnapshot_withoutContextManagers() throws IOException { + public void testCreateSnapshot_withoutContextManagers() { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); assertThat(snapshot, is(notNullValue())); - Closeable reactivated = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivated = snapshot.reactivate(); assertThat(reactivated, is(notNullValue())); reactivated.close(); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java index 6705f3b0..a29bab46 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiFunctionWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Function; @@ -96,7 +94,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { + public void testApplyWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -110,7 +108,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java index 2c403b22..378e2889 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BiPredicateWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiPredicate; import java.util.function.Supplier; @@ -95,7 +93,7 @@ public void testTestWithoutSnapshotSupplier() { } @Test - public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { + public void testTestWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -109,7 +107,7 @@ public void testTestWithSnapshotConsumer() throws InterruptedException, IOExcept t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java index 4da0d8e7..82a0f8bc 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BinaryOperatorWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.BinaryOperator; @@ -98,7 +96,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { + public void testApplyWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -111,7 +109,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep t.start(); t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java index 9b3b150b..b6310428 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/BooleanSupplierWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -85,7 +83,7 @@ public void testConstructWithoutSnapshotSupplier() { } @Test - public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { + public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException { DummyContext.setCurrentValue("true"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -101,7 +99,7 @@ public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, In assertThat(future.get(), is(true)); assertThat(DummyContext.currentValue(), is("true")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("false")); } assertThat(DummyContext.currentValue(), is("true")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java index 46874bfd..fac9a614 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/ConsumerWithContextTest.java @@ -24,8 +24,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -103,10 +101,8 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { assertThat("Snapshot consumer must be called", snapshotHolder[0], is(notNullValue())); t = new Thread(() -> { - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat("Thread context must propagate", currentValue(), is("New value")); - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); } }); t.start(); @@ -114,7 +110,7 @@ public void testAcceptWithSnapshotConsumer() throws InterruptedException { } @Test - public void testAndThen() throws InterruptedException, IOException { + public void testAndThen() throws InterruptedException { setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -129,7 +125,7 @@ public void testAndThen() throws InterruptedException, IOException { t.join(); assertThat(currentValue(), is("Old value")); - try (Closeable reactivated = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivated = snapshotHolder[0].reactivate()) { assertThat(currentValue(), is("NEW VALUE, New value, Old value")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java index a18848f5..53c34239 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/FunctionWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Supplier; @@ -95,7 +93,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { + public void testApplyWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -109,7 +107,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java index 4c761bc3..3420fc4a 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/PredicateWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; @@ -96,7 +94,7 @@ public void testTestWithoutSnapshotSupplier() { } @Test - public void testTestWithSnapshotConsumer() throws InterruptedException, IOException { + public void testTestWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -110,7 +108,7 @@ public void testTestWithSnapshotConsumer() throws InterruptedException, IOExcept t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java index f2adff7d..016f93b0 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/RunnableWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Supplier; import static org.hamcrest.MatcherAssert.assertThat; @@ -94,7 +92,7 @@ public void testRunWithoutSnapshotSupplier() { } @Test - public void testRunWithSnapshotConsumer() throws InterruptedException, IOException { + public void testRunWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -105,7 +103,7 @@ public void testRunWithSnapshotConsumer() throws InterruptedException, IOExcepti t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java index 9b1fb443..ac4d71cf 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/SupplierWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -76,7 +74,7 @@ public void testGetNull() { } @Test - public void testGetWithSnapshotConsumer() throws ExecutionException, InterruptedException, IOException { + public void testGetWithSnapshotConsumer() throws ExecutionException, InterruptedException { DummyContext.setCurrentValue("Old value"); final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; @@ -93,7 +91,7 @@ public void testGetWithSnapshotConsumer() throws ExecutionException, Interrupted verify(snapshot).reactivate(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } } diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java index 48005a91..ecb6ad14 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/function/UnaryOperatorWithContextTest.java @@ -23,8 +23,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -93,7 +91,7 @@ public void testApplyWithoutSnapshotSupplier() { } @Test - public void testApplyWithSnapshotConsumer() throws InterruptedException, IOException { + public void testApplyWithSnapshotConsumer() throws InterruptedException { final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1]; DummyContext.setCurrentValue("Old value"); @@ -107,7 +105,7 @@ public void testApplyWithSnapshotConsumer() throws InterruptedException, IOExcep t.join(); assertThat(DummyContext.currentValue(), is("Old value")); - try (Closeable reactivation = snapshotHolder[0].reactivate()) { + try (ContextSnapshot.Reactivation reactivation = snapshotHolder[0].reactivate()) { assertThat(DummyContext.currentValue(), is("New value")); } assertThat(DummyContext.currentValue(), is("Old value")); diff --git a/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java index 73556c3f..d5962b00 100644 --- a/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java +++ b/managers/context-manager-log4j2/src/test/java/nl/talsmasoftware/context/managers/log4j2/threadcontext/Log4j2ThreadContextManagerTest.java @@ -24,8 +24,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; @@ -173,7 +171,7 @@ public Integer call() { } @Test - void testSnapshotRestorationAfterClosingReactivatedSnapshot() throws IOException { + void testSnapshotRestorationAfterClosingReactivatedSnapshot() { String mapKey1 = "map1"; ThreadContext.put(mapKey1, "value1"); ThreadContext.push("stack1"); @@ -192,7 +190,7 @@ void testSnapshotRestorationAfterClosingReactivatedSnapshot() throws IOException String mapKey2 = "map2"; ThreadContext.put(mapKey2, "value2"); - Closeable reactivation = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); assertThat("ThreadContext changed by reactivation", ThreadContext.get(mapKey1), equalTo("value1")); assertThat("Existing ThreadContext data should not have been cleared", ThreadContext.get(mapKey2), equalTo("value2")); assertThat(ThreadContext.getContext().size(), is(2)); diff --git a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java index 623e8981..982ef344 100644 --- a/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java +++ b/managers/context-manager-opentracing/src/test/java/nl/talsmasoftware/context/managers/opentracing/Issue30Test.java @@ -26,9 +26,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.io.IOException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -71,9 +68,9 @@ public void cleanup() { } @Test - public void testIssue30NullPointerException() throws IOException { + public void testIssue30NullPointerException() { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - Closeable reactivation = snapshot.reactivate(); + ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); reactivation.close(); // This throws NPE in issue 30 } From 185178cccd61a987f0729daf64d95761c3c22e51 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 14:38:40 +0100 Subject: [PATCH 39/41] Minor touchups. Signed-off-by: Sjoerd Talsma --- .../WrapperWithContextAndConsumer.java | 10 ++-- .../context/core/ContextManagersTest.java | 49 +++++++++---------- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java index 2d089509..a0b20407 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/function/WrapperWithContextAndConsumer.java @@ -23,17 +23,21 @@ /** * A {@linkplain WrapperWithContext} that takes an additional {@link Consumer} accepting a result snapshot, - * captured after the function end. + * to be captured at the end of the function. * *

    - * This consumer is optional. All clients should avoid taking unnecessary snapshots if the consumer is {@code null}. + * This consumer is optional.
    + * All subclasses must avoid capturing unnecessary snapshots if the consumer is {@code null}. * * @param The type of the wrapped delegate object. */ abstract class WrapperWithContextAndConsumer extends WrapperWithContext { /** - * The context snapshot consumer to provide a new snapshot to after the function is completed, may be {@code null}. + * The context snapshot consumer to provide a new snapshot to after the function is complete. + * + *

    + * This consumer may be {@code null} in which case no new snapshot must be captured. */ protected final Consumer contextSnapshotConsumer; diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java index fb3d5295..f83d882a 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/ContextManagersTest.java @@ -21,7 +21,6 @@ import nl.talsmasoftware.context.dummy.DummyContext; import nl.talsmasoftware.context.dummy.DummyContextManager; import nl.talsmasoftware.context.dummy.ThrowingContextManager; -import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -82,37 +81,37 @@ public void testUnsupportedConstructor() { @Test public void testSnapshot_inSameThread() { dummyManager.clear(); - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); DummyContext ctx1 = new DummyContext("initial value"); - MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); + assertThat(DummyContext.currentValue(), is("initial value")); DummyContext ctx2 = new DummyContext("second value"); - MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); + assertThat(DummyContext.currentValue(), is("second value")); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); // No context change because of snapshot. + assertThat(DummyContext.currentValue(), is("second value")); // No context change because of snapshot. DummyContext ctx3 = new DummyContext("third value"); - MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); + assertThat(DummyContext.currentValue(), is("third value")); // Reactivate snapshot: ctx1 -> ctx2 -> ctx3 -> ctx2' ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); + assertThat(DummyContext.currentValue(), is("second value")); reactivation.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! + assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! // out-of-order closing! ctx2.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! + assertThat(DummyContext.currentValue(), is("third value")); // back to ctx3, NOT ctx1 !! ctx3.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); // back to ctx1 because ctx2 is closed + assertThat(DummyContext.currentValue(), is("initial value")); // back to ctx1 because ctx2 is closed - MatcherAssert.assertThat(ctx1.isClosed(), is(false)); - MatcherAssert.assertThat(ctx2.isClosed(), is(true)); - MatcherAssert.assertThat(ctx3.isClosed(), is(true)); + assertThat(ctx1.isClosed(), is(false)); + assertThat(ctx2.isClosed(), is(true)); + assertThat(ctx3.isClosed(), is(true)); ctx1.close(); } @@ -120,10 +119,10 @@ public void testSnapshot_inSameThread() { public void testSnapshotThreadPropagation() throws ExecutionException, InterruptedException { DummyContext.reset(); ExecutorService threadpool = new ContextAwareExecutorService(Executors.newCachedThreadPool()); - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); DummyContext ctx1 = new DummyContext("initial value"); - MatcherAssert.assertThat(DummyContext.currentValue(), is("initial value")); + assertThat(DummyContext.currentValue(), is("initial value")); Future threadResult = threadpool.submit(new Callable() { public String call() throws Exception { return DummyContext.currentValue(); @@ -141,7 +140,7 @@ public String call() throws Exception { return res + ", " + DummyContext.currentValue(); } }); - MatcherAssert.assertThat(DummyContext.currentValue(), is("second value")); + assertThat(DummyContext.currentValue(), is("second value")); assertThat(threadResult.get(), is("second value, in-thread value, second value")); ctx2.close(); @@ -177,11 +176,11 @@ public void testCreateSnapshot_ExceptionHandling() { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ctx.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); ContextSnapshot.Reactivation reactivation = snapshot.reactivate(); - MatcherAssert.assertThat(DummyContext.currentValue(), is("blah")); + assertThat(DummyContext.currentValue(), is("blah")); reactivation.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); } @Test @@ -193,18 +192,18 @@ public void testReactivateSnapshot_ExceptionHandling() { ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); ThrowingContextManager.onInitialize = reactivationException; - MatcherAssert.assertThat(DummyContext.currentValue(), is("foo")); - MatcherAssert.assertThat(mgr.getActiveContextValue(), is("bar")); + assertThat(DummyContext.currentValue(), is("foo")); + assertThat(mgr.getActiveContextValue(), is("bar")); ctx1.close(); ctx2.close(); - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); - MatcherAssert.assertThat(mgr.getActiveContextValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(mgr.getActiveContextValue(), is(nullValue())); RuntimeException expected = assertThrows(RuntimeException.class, snapshot::reactivate); // foo + bar mustn't be set after exception! - MatcherAssert.assertThat(DummyContext.currentValue(), is(nullValue())); - MatcherAssert.assertThat(mgr.getActiveContextValue(), is(nullValue())); + assertThat(DummyContext.currentValue(), is(nullValue())); + assertThat(mgr.getActiveContextValue(), is(nullValue())); } @Test From 567774f89725beb581040d66678f5c8f965baaa0 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 14:56:00 +0100 Subject: [PATCH 40/41] Replace several fully qualified names by simple names + import. Signed-off-by: Sjoerd Talsma --- .../context/core/delegation/DelegatingFutureTest.java | 2 +- .../context/timers/metrics/MetricsContextTimerTest.java | 8 ++++---- .../timers/micrometer/MicrometerContextTimerTest.java | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java index 95e9b469..63671670 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/delegation/DelegatingFutureTest.java @@ -49,7 +49,7 @@ */ public class DelegatingFutureTest { - private static class TestDelegatingFuture extends nl.talsmasoftware.context.core.delegation.DelegatingFuture { + private static class TestDelegatingFuture extends DelegatingFuture { private TestDelegatingFuture(Future delegate) { super(delegate); } diff --git a/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java index e322cd8a..0b4a2e54 100644 --- a/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java +++ b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java @@ -68,7 +68,7 @@ public void resetCacheAndRegistry() { public void testCreateSnapshotInFreshApplication() { assertThat(SharedMetricRegistries.names(), is(empty())); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - String name = MetricRegistry.name(nl.talsmasoftware.context.core.ContextManagers.class, "createContextSnapshot"); + String name = MetricRegistry.name(ContextManagers.class, "createContextSnapshot"); assertThat(snapshot, is(notNullValue())); assertThat(SharedMetricRegistries.names(), contains("ContextPropagationMetrics")); @@ -83,7 +83,7 @@ public void testCreateSnapshotInApplicationWithDefaultRegistry() { assertThat(SharedMetricRegistries.names(), contains("DefaultRegistry")); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - String name = MetricRegistry.name(nl.talsmasoftware.context.core.ContextManagers.class, "createContextSnapshot"); + String name = MetricRegistry.name(ContextManagers.class, "createContextSnapshot"); assertThat(snapshot, is(notNullValue())); assertThat(SharedMetricRegistries.names(), contains("DefaultRegistry")); // No new registries! @@ -99,7 +99,7 @@ public void testCreateSnapshotInApplicationWithSingleNonDefaultRegistry() { assertThat(SharedMetricRegistries.names(), contains("NonDefaultRegistry")); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); - String name = MetricRegistry.name(nl.talsmasoftware.context.core.ContextManagers.class, "createContextSnapshot"); + String name = MetricRegistry.name(ContextManagers.class, "createContextSnapshot"); assertThat(snapshot, is(notNullValue())); assertThat(SharedMetricRegistries.names(), contains("NonDefaultRegistry")); // No new registries! @@ -117,7 +117,7 @@ public void testCreate3SnapshotsInApplicationWithMultipleNonDefaultRegistries() for (int i = 1; i <= 3; i++) { assertThat(ContextManagers.createContextSnapshot(), is(notNullValue())); } - String name = MetricRegistry.name(nl.talsmasoftware.context.core.ContextManagers.class, "createContextSnapshot"); + String name = MetricRegistry.name(ContextManagers.class, "createContextSnapshot"); assertThat(registry1.getTimers().containsKey(name), is(true)); assertThat(registry1.timer(name).getCount(), is(3L)); diff --git a/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java index 50aa5cba..1d11f032 100644 --- a/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java +++ b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java @@ -49,7 +49,7 @@ public void shutdownRegistry() { @Test public void testCreateSnapshotInFreshApplication() { - Timer timer = Metrics.timer(nl.talsmasoftware.context.core.ContextManagers.class.getName() + ".createContextSnapshot"); + Timer timer = Metrics.timer(ContextManagers.class.getName() + ".createContextSnapshot"); assertThat(timer.count(), is(0L)); ContextSnapshot snapshot = ContextManagers.createContextSnapshot(); From 74c436ac6991ef3f5a8e6f4c039e97af09d663a0 Mon Sep 17 00:00:00 2001 From: Sjoerd Talsma Date: Fri, 8 Nov 2024 20:42:24 +0100 Subject: [PATCH 41/41] Extend ContextTimer api with thrown errors. Signed-off-by: Sjoerd Talsma --- .../talsmasoftware/context/api/Context.java | 2 +- .../context/api/ContextManager.java | 1 + .../context/api/ContextSnapshot.java | 2 +- .../context/api/ContextTimer.java | 21 +-- .../context/core/ContextManagers.java | 150 ++++++++++-------- .../talsmasoftware/context/core/Timers.java | 4 +- .../context/core/TimersTest.java | 4 +- .../timers/metrics/MetricsContextTimer.java | 50 +++--- .../metrics/MetricsContextTimerTest.java | 15 +- .../micrometer/MicrometerContextTimer.java | 3 +- .../MicrometerContextTimerTest.java | 2 +- .../opentracing/OpentracingContextTimer.java | 23 ++- 12 files changed, 165 insertions(+), 112 deletions(-) diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java index 3c201145..7b333a5b 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/Context.java @@ -42,7 +42,7 @@ * * @param Type of the context value. * @author Sjoerd Talsma - * @since 1.1.0 + * @since 2.0.0 */ public interface Context extends Closeable { diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java index 0d5b58b8..5f27b477 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextManager.java @@ -24,6 +24,7 @@ * * @param type of the context value * @author Sjoerd Talsma + * @since 2.0.0 */ public interface ContextManager { diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java index 9fdc1b52..0c6da1a8 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextSnapshot.java @@ -38,7 +38,7 @@ * {@link Reactivation#close()}. * * @author Sjoerd Talsma - * @since 1.1.0 + * @since 2.0.0 */ public interface ContextSnapshot { diff --git a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java index 6fbc2d2b..7f106309 100644 --- a/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java +++ b/context-propagation-api/src/main/java/nl/talsmasoftware/context/api/ContextTimer.java @@ -20,29 +20,30 @@ /** * Minimal Service Provider Interface for services that wish to get informed of context switching metrics. *

    - * Currently the following timed operations are updated: + * Currently, the following timed operations are updated: *

      *
    • {@code ContextManagers.createContextSnapshot}
    • - *
    • {@code ContextSnapshot.reactivate}
    • - *
    • {@code ContextManager.initializeNewContext}(*)
    • - *
    • {@code ContextManager.getActiveContext}(*)
    • + *
    • {@linkplain ContextSnapshot#reactivate()}
    • + *
    • {@linkplain ContextManager#getActiveContextValue()} (*)
    • + *
    • {@linkplain ContextManager#initializeNewContext(Object)} (*)
    • *
    *

    * (*) Timing is updated for each concrete {@code ContextManager} implementation class * * @author Sjoerd Talsma - * @since 1.1.0 + * @since 2.0.0 */ public interface ContextTimer { /** * Provides a new update for the context timer. * - * @param type The class being called - * @param method The method being called - * @param duration The duration of the method - * @param unit The unit of the duration + * @param type Class that was called + * @param method Method that was called + * @param duration Duration of the call + * @param unit Unit of the duration + * @param error Error that was thrown in the call (optional, normally {@code null}) */ - void update(Class type, String method, long duration, TimeUnit unit); + void update(Class type, String method, long duration, TimeUnit unit, Throwable error); } diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java index 8ae4cdae..9225bd12 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/ContextManagers.java @@ -65,15 +65,7 @@ public static ContextSnapshot createContextSnapshot() { final Object[] values = new Object[managers.size()]; for (int i = 0; i < values.length; i++) { - final ContextManager manager = managers.get(i); - long managerStart = System.nanoTime(); - try { - values[i] = getActiveContextValue(manager); - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext"); - } catch (RuntimeException rte) { - LOGGER.log(Level.WARNING, "Error obtaining active context from " + manager + " (in thread " + Thread.currentThread().getName() + ").", rte); - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "getActiveContext.exception"); - } + values[i] = getActiveContextValue(managers.get(i)); } final ContextSnapshotImpl result = new ContextSnapshotImpl(managers, values); @@ -82,7 +74,7 @@ public static ContextSnapshot createContextSnapshot() { + " Thead=" + Thread.currentThread() + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); } - Timers.timed(System.nanoTime() - start, ContextManagers.class, "createContextSnapshot"); + Timers.timed(System.nanoTime() - start, ContextManagers.class, "createContextSnapshot", null); return result; } @@ -105,24 +97,10 @@ public static ContextSnapshot createContextSnapshot() { */ public static void clearActiveContexts() { final long start = System.nanoTime(); - Long managerStart = null; for (ContextManager manager : ServiceCache.cached(ContextManager.class)) { - managerStart = System.nanoTime(); - try { - clear(manager); - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear"); - } catch (RuntimeException rte) { - LOGGER.log(Level.WARNING, "Error clearing active context from " + manager + ".", rte); - ServiceCache.clear(); - Timers.timed(System.nanoTime() - managerStart, manager.getClass(), "clear.exception"); - } + clear(manager); } - if (managerStart == null && LOGGER.isLoggable(Level.FINER)) { - LOGGER.finer("No ContextManagers were cleared because none were found! " - + " Thead=" + Thread.currentThread() - + ", ContextClassLoader=" + Thread.currentThread().getContextClassLoader()); - } - Timers.timed(System.nanoTime() - start, ContextManagers.class, "clearActiveContexts"); + Timers.timed(System.nanoTime() - start, ContextManagers.class, "clearActiveContexts", null); } /** @@ -151,16 +129,39 @@ public static synchronized void useClassLoader(ClassLoader classLoader) { } private static Object getActiveContextValue(ContextManager manager) { - final Object activeContextValue = manager.getActiveContextValue(); - LOGGER.finest(() -> activeContextValue == null - ? "There is no active context value for " + manager + " (in thread " + Thread.currentThread().getName() + ")." - : "Active context value of " + manager + " in " + Thread.currentThread().getName() + ": " + activeContextValue); - return activeContextValue; + final long start = System.nanoTime(); + RuntimeException error = null; + try { + + final Object activeContextValue = manager.getActiveContextValue(); + LOGGER.finest(() -> activeContextValue == null + ? "There is no active context value for " + manager + " (in thread " + Thread.currentThread().getName() + ")." + : "Active context value of " + manager + " in " + Thread.currentThread().getName() + ": " + activeContextValue); + return activeContextValue; + + } catch (RuntimeException e) { + LOGGER.log(Level.WARNING, e, () -> "Error obtaining active context from " + manager + " (in thread " + Thread.currentThread().getName() + ")."); + error = e; + return null; + } finally { + Timers.timed(System.nanoTime() - start, manager.getClass(), "getActiveContextValue", error); + } } private static void clear(ContextManager manager) { - manager.clear(); - LOGGER.finest(() -> "Active context of " + manager + " was cleared."); + final long start = System.nanoTime(); + RuntimeException error = null; + try { + + manager.clear(); + LOGGER.finest(() -> "Active context of " + manager + " was cleared."); + + } catch (RuntimeException e) { + LOGGER.log(Level.WARNING, e, () -> "Error clearing active context from " + manager + "(in thread " + Thread.currentThread().getName() + ")."); + error = e; + } finally { + Timers.timed(System.nanoTime() - start, manager.getClass(), "clear", error); + } } /** @@ -169,7 +170,6 @@ private static void clear(ContextManager manager) { */ @SuppressWarnings("rawtypes") private static final class ContextSnapshotImpl implements ContextSnapshot { - // TODO extract this inner class? private final List managers; private final Object[] values; @@ -180,49 +180,74 @@ private ContextSnapshotImpl(List managers, Object[] values) { public Reactivation reactivate() { final long start = System.nanoTime(); + RuntimeException error = null; final Context[] reactivatedContexts = new Context[managers.size()]; - try { + for (int i = 0; i < values.length; i++) { reactivatedContexts[i] = reactivate(managers.get(i), values[i]); } + return new ReactivationImpl(reactivatedContexts); - ReactivationImpl reactivation = new ReactivationImpl(reactivatedContexts); - Timers.timed(System.nanoTime() - start, ContextSnapshot.class, "reactivate"); - return reactivation; } catch (RuntimeException reactivationException) { - // TODO think about simplifying by catching & handling in reactivate(manager, value) method - for (Context alreadyReactivated : reactivatedContexts) { - if (alreadyReactivated != null) try { - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Snapshot reactivation failed! " + - "Closing already reactivated context: " + alreadyReactivated + "."); - } - alreadyReactivated.close(); - } catch (RuntimeException rte) { - reactivationException.addSuppressed(rte); - } - } + tryClose(reactivatedContexts, reactivationException); ServiceCache.clear(); - throw reactivationException; + throw error = reactivationException; + } finally { + Timers.timed(System.nanoTime() - start, ContextSnapshot.class, "reactivate", error); } } - @SuppressWarnings("unchecked") // As we got the values from the managers themselves, they must also accept them! - private Context reactivate(ContextManager contextManager, Object snapshotValue) { - long start = System.nanoTime(); + @Override + public String toString() { + return "ContextSnapshot{size=" + managers.size() + '}'; + } + + /** + * Reactivates a snapshot value for a single context manager. + * + *

    + * This initializes a new context with the context manager + * (normally on another thread the snapshot value was captured from). + * + * @param contextManager The context manager to reactivate the snapshot value for. + * @param snapshotValue The snapshot value to be reactivated. + * @return The context to be included in the reactivation object. + */ + @SuppressWarnings("unchecked") // We got the value from the managers itself. + private static Context reactivate(ContextManager contextManager, Object snapshotValue) { if (snapshotValue == null) return null; - Context reactivated = contextManager.initializeNewContext(snapshotValue); - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.finest("Context reactivated from snapshot by " + contextManager + ": " + reactivated + "."); + long start = System.nanoTime(); + RuntimeException error = null; + try { + + Context reactivated = contextManager.initializeNewContext(snapshotValue); + LOGGER.finest(() -> "Context reactivated from snapshot by " + contextManager + ": " + reactivated + "."); + return reactivated; + + } catch (RuntimeException e) { + throw error = e; + } finally { + Timers.timed(System.nanoTime() - start, contextManager.getClass(), "initializeNewContext", error); } - Timers.timed(System.nanoTime() - start, contextManager.getClass(), "initializeNewContext"); - return reactivated; } - @Override - public String toString() { - return "ContextSnapshot{size=" + managers.size() + '}'; + /** + * Try to close already-reactivated contexts when a later context manager threw an exception. + * + * @param reactivatedContexts The contexts that were already reactivated when the error happened. + * @param reason The error that happened. + */ + private static void tryClose(Context[] reactivatedContexts, Throwable reason) { + for (Context alreadyReactivated : reactivatedContexts) { + if (alreadyReactivated != null) { + try { + alreadyReactivated.close(); + } catch (RuntimeException rte) { + reason.addSuppressed(rte); + } + } + } } } @@ -233,7 +258,6 @@ public String toString() { */ @SuppressWarnings("rawtypes") private static final class ReactivationImpl implements Reactivation { - // TODO extract this inner class? private final Context[] reactivated; private ReactivationImpl(Context[] reactivated) { diff --git a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java index 32c58760..0ec1366e 100644 --- a/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java +++ b/context-propagation-core/src/main/java/nl/talsmasoftware/context/core/Timers.java @@ -24,9 +24,9 @@ final class Timers { private static final Logger TIMING_LOGGER = Logger.getLogger(Timers.class.getName()); - static void timed(long durationNanos, Class type, String method) { + static void timed(long durationNanos, Class type, String method, Throwable error) { for (ContextTimer delegate : ServiceCache.cached(ContextTimer.class)) { - delegate.update(type, method, durationNanos, TimeUnit.NANOSECONDS); + delegate.update(type, method, durationNanos, TimeUnit.NANOSECONDS, error); } if (TIMING_LOGGER.isLoggable(Level.FINEST)) { TIMING_LOGGER.log(Level.FINEST, "{0}.{1}: {2,number}ns", new Object[]{type.getName(), method, durationNanos}); diff --git a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java index 90da0c3f..a5c23ab6 100644 --- a/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java +++ b/context-propagation-core/src/test/java/nl/talsmasoftware/context/core/TimersTest.java @@ -34,7 +34,7 @@ public class TimersTest { @Test public void testTimingDelegation() { - Timers.timed(TimeUnit.MILLISECONDS.toNanos(150), getClass(), "testTimingDelegation"); + Timers.timed(TimeUnit.MILLISECONDS.toNanos(150), getClass(), "testTimingDelegation", null); assertThat(TestContextTimer.getLastTimedMillis(getClass(), "testTimingDelegation"), is(150L)); } @@ -45,7 +45,7 @@ public static Long getLastTimedMillis(Class type, String method) { return LAST_TIMED.get(type.getName() + "." + method); } - public void update(Class type, String method, long duration, TimeUnit unit) { + public void update(Class type, String method, long duration, TimeUnit unit, Throwable error) { LAST_TIMED.put(type.getName() + "." + method, unit.toMillis(duration)); } diff --git a/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java b/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java index c420bdc2..f2af09bf 100644 --- a/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java +++ b/timers/context-timer-metrics/src/main/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimer.java @@ -15,6 +15,7 @@ */ package nl.talsmasoftware.context.timers.metrics; +import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; import com.codahale.metrics.Timer; @@ -68,32 +69,45 @@ public class MetricsContextTimer implements ContextTimer { private static final String SYS_REGISTRY_NAME = "contextpropagation.metrics.registry"; private static final String ENV_REGISTRY_NAME = SYS_REGISTRY_NAME.toUpperCase().replace('.', '_'); - private static final ConcurrentMap TIMERS = new ConcurrentHashMap<>(); + private static final ConcurrentMap CACHED_TIMERS = new ConcurrentHashMap<>(); + private static final ConcurrentMap CACHED_ERRORS = new ConcurrentHashMap<>(); @Override - public void update(Class type, String method, long duration, TimeUnit unit) { - locateTimer(type, method).update(duration, unit); + public void update(Class type, String method, long duration, TimeUnit unit, Throwable error) { + final String name = MetricRegistry.name(type, method); + final String errorsName = MetricRegistry.name(name, "errors"); + CACHED_TIMERS.computeIfAbsent(name, this::registerTimer).update(duration, unit); + CACHED_ERRORS.computeIfAbsent(errorsName, this::registerMeter).mark(error == null ? 0L : 1L); } - private static Timer locateTimer(Class type, String method) { - final String name = MetricRegistry.name(type, method); - Timer timer = TIMERS.get(name); - if (timer == null) { - final Collection sharedRegistries = locateSharedRegistries(); - for (MetricRegistry registry : sharedRegistries) { - timer = registry.getTimers().get(name); - if (timer != null) break; - } - if (timer == null) timer = new Timer(); - TIMERS.putIfAbsent(name, timer); - timer = TIMERS.get(name); // In case of race conditions - for (MetricRegistry registry : sharedRegistries) { - if (!registry.getTimers().containsKey(name)) registry.register(name, timer); + private Timer registerTimer(String name) { + final Collection sharedRegistries = locateSharedRegistries(); + for (MetricRegistry registry : sharedRegistries) { + Timer timer = registry.getTimers().get(name); + if (timer != null) { + return timer; } } + + final Timer timer = new Timer(); + sharedRegistries.forEach(registry -> registry.register(name, timer)); return timer; } + private Meter registerMeter(String name) { + final Collection sharedRegistries = locateSharedRegistries(); + for (MetricRegistry registry : sharedRegistries) { + Meter meter = registry.getMeters().get(name); + if (meter != null) { + return meter; + } + } + + final Meter meter = new Meter(); + sharedRegistries.forEach(registry -> registry.register(name, meter)); + return meter; + } + private static Collection locateSharedRegistries() { String registryName = System.getProperty(SYS_REGISTRY_NAME, System.getenv(ENV_REGISTRY_NAME)); if (registryName == null) { @@ -123,6 +137,6 @@ private static Collection locateSharedRegistries() { @Override public String toString() { - return getClass().getSimpleName() + "{timers=" + TIMERS.keySet() + "}"; + return getClass().getSimpleName() + "{timers=" + CACHED_TIMERS.keySet() + "}"; } } diff --git a/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java index 0b4a2e54..60b10fd2 100644 --- a/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java +++ b/timers/context-timer-metrics/src/test/java/nl/talsmasoftware/context/timers/metrics/MetricsContextTimerTest.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import java.util.Arrays; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -47,12 +48,14 @@ public class MetricsContextTimerTest { @BeforeEach @AfterEach @SuppressWarnings("unchecked") - public void resetCacheAndRegistry() { + public void resetCachesAndRegistry() { try { - // Reflect and clear the cache - Field cache = MetricsContextTimer.class.getDeclaredField("TIMERS"); - cache.setAccessible(true); - ((Map) cache.get(null)).clear(); + // Reflect and clear the caches + for (String name : Arrays.asList("CACHED_TIMERS", "CACHED_ERRORS")) { + Field cache = MetricsContextTimer.class.getDeclaredField(name); + cache.setAccessible(true); + ((Map) cache.get(null)).clear(); + } // Clear all shared registries SharedMetricRegistries.clear(); @@ -131,7 +134,7 @@ public void testMetricsContextTimerToString() { MetricsContextTimer metricsContextTimer = new MetricsContextTimer(); assertThat(metricsContextTimer, hasToString("MetricsContextTimer{timers=[]}")); - metricsContextTimer.update(getClass(), "method", 1, TimeUnit.SECONDS); + metricsContextTimer.update(getClass(), "method", 1, TimeUnit.SECONDS, null); assertThat(metricsContextTimer, hasToString("MetricsContextTimer{timers=[" + getClass().getName() + ".method]}")); } diff --git a/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java b/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java index f5afca87..4d9e1d0b 100644 --- a/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java +++ b/timers/context-timer-micrometer/src/main/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimer.java @@ -34,9 +34,10 @@ public class MicrometerContextTimer implements ContextTimer { * @param method The method being called * @param duration The duration of the method * @param unit The unit of the duration + * @param error Optional error that occurred when calling the method. */ @Override - public void update(Class type, String method, long duration, TimeUnit unit) { + public void update(Class type, String method, long duration, TimeUnit unit, Throwable error) { Metrics.timer(type.getName() + "." + method).record(duration, unit); } diff --git a/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java index 1d11f032..2a0b66dc 100644 --- a/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java +++ b/timers/context-timer-micrometer/src/test/java/nl/talsmasoftware/context/timers/micrometer/MicrometerContextTimerTest.java @@ -61,7 +61,7 @@ public void testCreateSnapshotInFreshApplication() { @Test public void testTiming() { Timer timer = Metrics.timer(MicrometerContextTimerTest.class.getName() + ".testTiming"); - new MicrometerContextTimer().update(MicrometerContextTimerTest.class, "testTiming", 43, TimeUnit.MILLISECONDS); + new MicrometerContextTimer().update(MicrometerContextTimerTest.class, "testTiming", 43, TimeUnit.MILLISECONDS, null); assertThat(timer.count(), is(1L)); assertThat(timer.mean(TimeUnit.NANOSECONDS), closeTo(43000000.0d, 0.001d)); } diff --git a/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java b/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java index be2468b8..cb5ebd71 100644 --- a/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java +++ b/timers/context-timer-opentracing/src/main/java/nl/talsmasoftware/context/timers/opentracing/OpentracingContextTimer.java @@ -16,14 +16,16 @@ package nl.talsmasoftware.context.timers.opentracing; import io.opentracing.Span; +import io.opentracing.log.Fields; +import io.opentracing.tag.Tags; import io.opentracing.util.GlobalTracer; import nl.talsmasoftware.context.api.ContextSnapshot; import nl.talsmasoftware.context.api.ContextTimer; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.TimeUnit; -import static java.util.Collections.singletonMap; - /** * This {@link ContextTimer} uses the {@code Opentracing API} to report timing statistics of context switches. * @@ -35,20 +37,27 @@ public class OpentracingContextTimer implements ContextTimer { private static final String LOG_FIELD_THREAD = "context.thread"; @Override - public void update(Class type, String method, long duration, TimeUnit unit) { + public void update(Class type, String method, long duration, TimeUnit unit, Throwable error) { if (GlobalTracer.isRegistered() && reportContextSwitchesFor(type)) { String operationName = type.getSimpleName() + "." + method; long finishedMicros = System.currentTimeMillis() * 1000; long startTimestampMicros = finishedMicros - unit.toMicros(duration); Span span = GlobalTracer.get().buildSpan(operationName).withStartTimestamp(startTimestampMicros).start(); try { + Map log = new LinkedHashMap<>(); if ("createContextSnapshot".equals(method)) { - span.log("New context snapshot created"); - span.log(singletonMap(LOG_FIELD_THREAD, Thread.currentThread().getName())); + log.put(Fields.EVENT, "New context snapshot created"); } else if ("reactivate".equals(method)) { - span.log("Context snapshot reactivated"); - span.log(singletonMap(LOG_FIELD_THREAD, Thread.currentThread().getName())); + log.put(Fields.EVENT, "Context snapshot reactivated"); + } + if (error != null) { + Tags.ERROR.set(span, true); + log.put(Fields.EVENT, "error"); + log.put(Fields.MESSAGE, error.getMessage()); + log.put(Fields.ERROR_OBJECT, error); } + log.put(LOG_FIELD_THREAD, Thread.currentThread().getName()); + span.log(log); } finally { span.finish(finishedMicros); }