├── .gitignore
├── .project
├── .settings
└── org.eclipse.m2e.core.prefs
├── .travis.settings.xml
├── .travis.yml
├── LICENSE
├── README.md
├── core
├── .project
├── pom.xml
└── src
│ └── main
│ └── java
│ └── io
│ └── reactiverse
│ └── reactivecontexts
│ └── core
│ ├── CompletableFutureWrapper.java
│ ├── CompletionStageWrapper.java
│ ├── Context.java
│ ├── ContextPropagator.java
│ ├── ContextProvider.java
│ ├── ContextState.java
│ └── package-info.java
├── docs
├── Gemfile
├── README.md
└── _config.yml
├── pom.xml
├── propagators-rxjava1
├── .project
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── io
│ │ └── reactiverse
│ │ └── reactivecontexts
│ │ └── propagators
│ │ └── rxjava1
│ │ ├── ContextPropagatorOnCompleteCreateAction.java
│ │ ├── ContextPropagatorOnObservableCreateAction.java
│ │ ├── ContextPropagatorOnSingleCreateAction.java
│ │ └── RxJava1ContextPropagator.java
│ └── resources
│ └── META-INF
│ └── services
│ └── io.reactiverse.reactivecontexts.core.ContextPropagator
├── propagators-rxjava2
├── .project
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── io
│ │ └── reactiverse
│ │ └── reactivecontexts
│ │ └── propagators
│ │ └── rxjava2
│ │ ├── ContextPropagatorOnCompletableAssemblyAction.java
│ │ ├── ContextPropagatorOnCompletableCreateAction.java
│ │ ├── ContextPropagatorOnFlowableAssemblyAction.java
│ │ ├── ContextPropagatorOnFlowableCreateAction.java
│ │ ├── ContextPropagatorOnMaybeAssemblyAction.java
│ │ ├── ContextPropagatorOnMaybeCreateAction.java
│ │ ├── ContextPropagatorOnObservableAssemblyAction.java
│ │ ├── ContextPropagatorOnObservableCreateAction.java
│ │ ├── ContextPropagatorOnSingleAssemblyAction.java
│ │ ├── ContextPropagatorOnSingleCreateAction.java
│ │ └── RxJava2ContextPropagator.java
│ └── resources
│ └── META-INF
│ └── services
│ └── io.reactiverse.reactivecontexts.core.ContextPropagator
└── tests
├── .project
├── pom.xml
└── src
├── main
├── java
│ └── io
│ │ └── reactiverse
│ │ └── reactivecontexts
│ │ └── test
│ │ ├── MyContext.java
│ │ └── MyContextProvider.java
└── resources
│ └── META-INF
│ └── services
│ └── io.reactiverse.reactivecontexts.core.ContextProvider
└── test
└── java
└── io
└── reactiverse
└── reactivecontexts
└── test
├── BackPressureExceptionTest.java
├── ManualPropagationMultipleRequestTest.java
├── RxJava1MultipleRequestTest.java
├── RxJava1Test.java
└── RxJava2Test.java
/.gitignore:
--------------------------------------------------------------------------------
1 | */target
2 | */.classpath
3 | */.settings
4 | .settings
5 | .classpath
6 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | reactive-contexts-parent
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.m2e.core.maven2Builder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.m2e.core.maven2Nature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/.travis.settings.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 | false
6 |
7 |
8 |
9 | sonatype-repository
10 |
11 |
12 | sonatype-nexus-snapshots
13 | https://oss.sonatype.org/content/repositories/snapshots
14 |
15 | true
16 |
17 | default
18 |
19 | false
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | sonatype-repository
28 |
29 |
30 |
31 |
32 | sonatype-nexus-snapshots
33 | ${env.SONATYPE_NEXUS_USERNAME}
34 | ${env.SONATYPE_NEXUS_PASSWORD}
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | notifications:
3 | email:
4 | recipients:
5 | - stef@epardaud.fr
6 | on_success: always
7 | on_failure: always
8 | deploy:
9 | provider: script
10 | script: "cp .travis.settings.xml $HOME/.m2/settings.xml && mvn -X deploy"
11 | skip_cleanup: true
12 | on:
13 | branch: master
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Reactive Contexts
2 |
3 | [](https://travis-ci.com/reactiverse/reactive-contexts)
4 |
5 | Reactive Contexts is a library that allows you to capture contexts from various providers ([RESTEasy](https://resteasy.github.io),
6 | [Redpipe](http://redpipe.net), [Weld](http://weld.cdi-spec.org))
7 | and propagate them along the reactive flow of various propagators ([RxJava1, RxJava2](https://github.com/ReactiveX/RxJava)).
8 |
9 | # License
10 |
11 | Reactive Contexts is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) terms.
12 |
13 | # The problem with contexts and reactive libraries
14 |
15 | Many libraries (for example: RESTEasy, [CDI](http://cdi-spec.org)) use a thread-local context that holds information required by user-executing
16 | code (in the case of RESTEasy: the current request, response and many other useful information so that the resource
17 | method can look them up when executed).
18 |
19 | This works well in settings where you have one thread per operation, but stops working if the operation spawns other
20 | threads, or gets executed in other threads, or simply later, as is the case in many Reactive libraries, such as RxJava,
21 | where users code is spread between the subscriber, operations such as filter/map, and producers, all of which can be
22 | executed in different thread schedulers.
23 |
24 | For example, the following RESTEasy/RxJava code works out of the box with the latest version of RESTEasy:
25 |
26 | @GET
27 | @Path("reactive-nodelay")
28 | public Single reactiveNoDelay(@Context UriInfo uriInfo){
29 | return Single.just("hello")
30 | .map(str -> str + " from: "+uriInfo.getAbsolutePath());
31 | }
32 |
33 | And will display something like `hello from: http://localhost:8081/reactive-nodelay`.
34 |
35 | But if you introduce a delay, which is only one of the many ways to introduce a thread-switch from RxJava:
36 |
37 | @GET
38 | @Path("reactive-delay")
39 | public Single reactiveDelay(@Context UriInfo uriInfo){
40 | return Single.just("hello")
41 | .delay(1, TimeUnit.SECONDS)
42 | .map(str -> str + " from: "+uriInfo.getAbsolutePath());
43 | }
44 |
45 | Then it breaks down with `RESTEASY003880: Unable to find contextual data of type: javax.ws.rs.core.UriInfo`.
46 |
47 | This is due to the fact that RESTEasy doesn't know that RxJava is going to schedule the delayed `map` operation
48 | into a different scheduler, on a thread which doesn't have the RESTEasy context set-up in a thread-local.
49 |
50 | This is not RESTEasy's fault: the exact same error will happen if you try to use CDI at that point, for the exact
51 | same reason. Many existing libraries rely on thread-locals for context propagation, and it does not work in the
52 | async/Reactive world.
53 |
54 | RxJava supports a system of hooks/plugins that we can use to capture and restore context, but there can only be
55 | one such hook/plugin, so if RESTEasy uses it, CDI cannot use it. Also, there would be a lot of code duplication
56 | as propagating contexts with RxJava hooks/plugins is not trivial.
57 |
58 | # The solution
59 |
60 | In order to enable automatic context propagation of any number of contexts, Reactive Context uses a system of plugins
61 | for saving/restoring contexts: `ContextProvider`, and plugins that hook into Reactive libraries/schedulers in
62 | order to use the `Context` API for saving/restoring all contexts: `ContextPropagator`.
63 |
64 | If your context-using framework is supported, and your Reactive library/scheduler is supported too, then all your
65 | contexts will be automatically propagated and your code will look great. If not, add support for your
66 | `ContextProvider` or `ContextPropagator`. If it's not possible, you can still use manual context
67 | propagation by accessing directly the `Context` API.
68 |
69 | To get back to our original problematic code:
70 |
71 | @GET
72 | @Path("reactive-delay")
73 | public Single reactiveDelay(@Context UriInfo uriInfo){
74 | return Single.just("hello")
75 | .delay(1, TimeUnit.SECONDS)
76 | .map(str -> str + " from: "+uriInfo.getAbsolutePath());
77 | }
78 |
79 | Will work fine if you use the RESTEasy `ContextProvider` with the RxJava2 `ContextPropagator`, without any change
80 | in your code. Automatic context propagation FTW!
81 |
82 | # Usage
83 |
84 | Import the following Maven module:
85 |
86 | ```xml
87 |
88 | io.reactiverse
89 | reactive-contexts-core
90 | 1.0.0
91 |
92 | ```
93 |
94 | Then call `io.reactiverse.reactivecontexts.core.Context.load();` and your contexts will be propagated, depending on the
95 | presence of the following optional plugins in your classpath:
96 |
97 | artifactId | Description
98 | --- | ---
99 | `reactive-contexts-core` | Core engine
100 | `reactive-contexts-propagators-rxjava1` | Propagates contexts for RxJava1
101 | `reactive-contexts-propagators-rxjava2` | Propagates contexts for RxJava2
102 |
103 | If you are using RxJava 1 or 2, you don't need anything to propagate your contexts: every RxJava type (`Single`,
104 | `Flowable`…) will have the right contexts automatically propagated. If you are using reactive types that don't
105 | have a `reactive-contexts-propagator` plugin, such as `CompletionStage` in the JDK, see [below for how to manually
106 | propagate contexts](#manual-context-propagation)
107 |
108 | # Building
109 |
110 | Clone this repository, and run:
111 |
112 | ```shell
113 | $ mvn clean install
114 | ```
115 |
116 | # For context providers
117 |
118 | If you have a context that your library provides and requires, which is often stored in thread-local
119 | variables, it's very likely it won't work with reactive applications that register callbacks and
120 | invoke them later in various threads.
121 |
122 | In order for your library to have its context propagated to all supported reactive libraries, you
123 | can implement the `io.reactiverse.reactivecontexts.core.ContextProvider` interface and specify how
124 | you can save and restore your context:
125 |
126 | ```java
127 | package my.library;
128 |
129 | public class MyContextProvider implements ContextProvider {
130 |
131 | @Override
132 | public MyState install(MyState state) {
133 | MyState previousState = MyContext.getState();
134 | MyContext.setState(state);
135 | return previousState;
136 | }
137 |
138 | @Override
139 | public void restore(MyState previousState) {
140 | MyContext.setState(previousState);
141 | }
142 |
143 | @Override
144 | public MyState capture() {
145 | return MyContext.getState();
146 | }
147 | }
148 | ```
149 |
150 | Then you declare a `META-INF/services/io.reactiverse.reactivecontexts.core.ContextProvider` file which
151 | lists your fully-qualified class name implementing the `ContextProvider` interface (in this case
152 | `my.library.MyContextProvider`) and include it in your classpath.
153 |
154 | Upon initialisation, your context provider implementation will automatically be loaded and your
155 | context will be propagated to all supported reactive libraries.
156 |
157 | # For context propagators
158 |
159 | If you have a reactive library that supports scheduling of callbacks on various threads, you will need
160 | to register a `ContextPropagator` implementation that will be called by the `reactive-contexts` library,
161 | where you will register any required plumbing on the reactive library, to make sure it will properly
162 | propagate all contexts during scheduling.
163 |
164 | For example, here is how the RxJava1 propagator is implemented:
165 |
166 | ```java
167 | public class RxJava1ContextPropagator implements ContextPropagator {
168 |
169 | public void setup() {
170 | RxJavaHooks.setOnSingleCreate(new ContextPropagatorOnSingleCreateAction());
171 | // ...
172 | }
173 | }
174 | ```
175 |
176 | Don't forget to list your context propagator's fully-qualified class names in the
177 | `META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator` file, and to include it in
178 | your classpath.
179 |
180 | Your plugin can capture all current contexts with `Context.capture()`, then install captured contexts with
181 | `Context.install(contexts)` and restore them with `Context.restore(contexts)`.
182 |
183 | For example, here is how contexts are propagated for RxJava1 `Single`:
184 |
185 | ```java
186 | public class ContextPropagatorOnSingleCreateAction implements Func1 {
187 |
188 | @Override
189 | public OnSubscribe call(OnSubscribe t) {
190 | return new ContextCapturerSingle(t);
191 | }
192 |
193 | final static class ContextCapturerSingle implements Single.OnSubscribe {
194 |
195 | final Single.OnSubscribe source;
196 |
197 | private ContextState states;
198 |
199 | public ContextCapturerSingle(Single.OnSubscribe source) {
200 | this.source = source;
201 | // capture the context
202 | states = Context.capture();
203 | }
204 |
205 | @Override
206 | public void call(SingleSubscriber super T> t) {
207 | // restore the context for subscription
208 | ContextState previousStates = states.install();
209 | try {
210 | source.call(new OnAssemblySingleSubscriber(t, states));
211 | }finally {
212 | previousStates.restore();
213 | }
214 | }
215 |
216 | static final class OnAssemblySingleSubscriber extends SingleSubscriber {
217 |
218 | final SingleSubscriber super T> actual;
219 | private final ContextState states;
220 |
221 |
222 | public OnAssemblySingleSubscriber(SingleSubscriber super T> actual, ContextState states) {
223 | this.actual = actual;
224 | this.states = states;
225 | actual.add(this);
226 | }
227 |
228 | @Override
229 | public void onError(Throwable e) {
230 | // propagate the context for listeners
231 | ContextState previousStates = states.install();
232 | try {
233 | actual.onError(e);
234 | }finally {
235 | previousStates.restore();
236 | }
237 | }
238 |
239 | @Override
240 | public void onSuccess(T t) {
241 | // propagate the context for listeners
242 | ContextState previousStates = states.install();
243 | try {
244 | actual.onSuccess(t);
245 | }finally {
246 | previousStates.restore();
247 | }
248 | }
249 | }
250 | }
251 |
252 | }
253 | ```
254 |
255 | ## Manual context propagation
256 |
257 | If you have a library that uses reactive types that don't support hooks, such as the JDK's `CompletionStage`,
258 | you will have to manually capture and restore contexts, for example:
259 |
260 | ```java
261 | CompletionStage userResponse = invokeUserAction();
262 | ContextState states = Context.capture();
263 | userResponse.thenAccept(response -> {
264 | ContextState previousStates = states.install();
265 | try {
266 | writeResponse(response);
267 | }finally {
268 | previousStates.restore();
269 | }
270 | });
271 | ```
272 |
273 | Alternately, you can use `Context.wrap` to propagate reactive contexts to many functional interfaces, for example:
274 |
275 | ```java
276 | CompletionStage userResponse = Context.wrap(invokeUserAction());
277 | userResponse.thenAccept(response -> writeResponse(response));
278 | ```
279 |
280 | # Threads, class loaders
281 |
282 | If you are using a flat classpath, this is all you need to know. If you're using a modular class loader,
283 | or need to have several independent `Context` objects, each with their own list of providers and
284 | propagators, then you need to stop using the global `Context` instance and create your own.
285 |
286 | You can create your own Context with `new Context()`, then set it as a thread-local with
287 | `Context.setThreadInstance(Context)`, and when you're done you can clear the thread-local with
288 | `Context.clearThreadInstance()`.
289 |
290 | Note that each captured context state will restore the proper Context thread-local when
291 | calling `ContextState.install()` and `ContextState.restore()`, so as to avoid
292 | interference.
293 |
294 |
--------------------------------------------------------------------------------
/core/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | core
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | io.reactiverse
7 | reactive-contexts-parent
8 | 1.0.2-SNAPSHOT
9 |
10 | reactive-contexts-core
11 | reactive-contexts-core
12 | http://maven.apache.org
13 |
14 | UTF-8
15 |
16 |
17 |
18 | junit
19 | junit
20 | test
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-source-plugin
28 |
29 |
30 | org.apache.maven.plugins
31 | maven-javadoc-plugin
32 |
33 |
34 |
35 |
36 |
37 | release
38 |
39 |
40 |
41 | org.apache.maven.plugins
42 | maven-gpg-plugin
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/core/src/main/java/io/reactiverse/reactivecontexts/core/CompletableFutureWrapper.java:
--------------------------------------------------------------------------------
1 | package io.reactiverse.reactivecontexts.core;
2 |
3 | import java.util.concurrent.CompletableFuture;
4 | import java.util.concurrent.CompletionStage;
5 | import java.util.concurrent.ExecutionException;
6 | import java.util.concurrent.Executor;
7 | import java.util.concurrent.TimeUnit;
8 | import java.util.concurrent.TimeoutException;
9 | import java.util.function.BiConsumer;
10 | import java.util.function.BiFunction;
11 | import java.util.function.Consumer;
12 | import java.util.function.Function;
13 |
14 | final class CompletableFutureWrapper extends CompletableFuture {
15 | private final ContextState state;
16 | private final CompletableFuture f;
17 |
18 | CompletableFutureWrapper(ContextState state, CompletableFuture f) {
19 | this.state = state;
20 | this.f = f;
21 | }
22 |
23 | @Override
24 | public boolean complete(T value) {
25 | return f.complete(value);
26 | }
27 |
28 | @Override
29 | public boolean completeExceptionally(Throwable ex) {
30 | return f.completeExceptionally(ex);
31 | }
32 |
33 | @Override
34 | public boolean cancel(boolean mayInterruptIfRunning) {
35 | return f.cancel(mayInterruptIfRunning);
36 | }
37 |
38 | @Override
39 | public boolean isCancelled() {
40 | return f.isCancelled();
41 | }
42 |
43 | @Override
44 | public boolean isCompletedExceptionally() {
45 | return f.isCompletedExceptionally();
46 | }
47 |
48 | @Override
49 | public void obtrudeValue(T value) {
50 | f.obtrudeValue(value);
51 | }
52 |
53 | @Override
54 | public void obtrudeException(Throwable ex) {
55 | f.obtrudeException(ex);
56 | }
57 |
58 | @Override
59 | public int getNumberOfDependents() {
60 | return f.getNumberOfDependents();
61 | }
62 |
63 | @Override
64 | public boolean isDone() {
65 | return f.isDone();
66 | }
67 |
68 | @Override
69 | public T get() throws InterruptedException, ExecutionException {
70 | return f.get();
71 | }
72 |
73 | @Override
74 | public T get(long timeout, TimeUnit unit)
75 | throws InterruptedException, ExecutionException, TimeoutException {
76 | return f.get(timeout, unit);
77 | }
78 |
79 | @Override
80 | public T join() {
81 | return f.join();
82 | }
83 |
84 | @Override
85 | public T getNow(T valueIfAbsent) {
86 | return f.getNow(valueIfAbsent);
87 | }
88 |
89 | @Override
90 | public CompletableFuture toCompletableFuture() {
91 | return this;
92 | }
93 |
94 | @Override
95 | public CompletableFuture exceptionally(Function fn) {
96 | return Context.wrap(state, f.exceptionally(Context.wrap(state, fn)));
97 | }
98 |
99 | @Override
100 | public CompletableFuture handle(BiFunction super T, Throwable, ? extends U> fn) {
101 | return Context.wrap(state, f.handle(Context.wrap(state, fn)));
102 | }
103 |
104 | @Override
105 | public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U> fn) {
106 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn)));
107 | }
108 |
109 | @Override
110 | public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U> fn,
111 | Executor executor) {
112 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn), executor));
113 | }
114 |
115 | @Override
116 | public CompletableFuture thenApply(Function super T, ? extends U> fn) {
117 | return Context.wrap(state, f.thenApply(Context.wrap(state, fn)));
118 | }
119 |
120 | @Override
121 | public CompletableFuture thenApplyAsync(Function super T, ? extends U> fn) {
122 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn)));
123 | }
124 |
125 | @Override
126 | public CompletableFuture thenApplyAsync(Function super T, ? extends U> fn, Executor executor) {
127 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn), executor));
128 | }
129 |
130 | @Override
131 | public CompletableFuture thenAccept(Consumer super T> action) {
132 | return Context.wrap(state, f.thenAccept(Context.wrap(state, action)));
133 | }
134 |
135 | @Override
136 | public CompletableFuture thenAcceptAsync(Consumer super T> action) {
137 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action)));
138 | }
139 |
140 | @Override
141 | public CompletableFuture thenAcceptAsync(Consumer super T> action, Executor executor) {
142 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action), executor));
143 | }
144 |
145 | @Override
146 | public CompletableFuture thenRun(Runnable action) {
147 | return Context.wrap(state, f.thenRun(Context.wrap(state, action)));
148 | }
149 |
150 | @Override
151 | public CompletableFuture thenRunAsync(Runnable action) {
152 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action)));
153 | }
154 |
155 | @Override
156 | public CompletableFuture thenRunAsync(Runnable action, Executor executor) {
157 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action), executor));
158 | }
159 |
160 | @Override
161 | public CompletableFuture thenCombine(CompletionStage extends U> other,
162 | BiFunction super T, ? super U, ? extends V> fn) {
163 | return Context.wrap(state, f.thenCombine(other, Context.wrap(state, fn)));
164 | }
165 |
166 | @Override
167 | public CompletableFuture thenCombineAsync(CompletionStage extends U> other,
168 | BiFunction super T, ? super U, ? extends V> fn) {
169 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn)));
170 | }
171 |
172 | @Override
173 | public CompletableFuture thenCombineAsync(CompletionStage extends U> other,
174 | BiFunction super T, ? super U, ? extends V> fn, Executor executor) {
175 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn), executor));
176 | }
177 |
178 | @Override
179 | public CompletableFuture thenAcceptBoth(CompletionStage extends U> other,
180 | BiConsumer super T, ? super U> action) {
181 | return Context.wrap(state, f.thenAcceptBoth(other, Context.wrap(state, action)));
182 | }
183 |
184 | @Override
185 | public CompletableFuture thenAcceptBothAsync(CompletionStage extends U> other,
186 | BiConsumer super T, ? super U> action) {
187 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action)));
188 | }
189 |
190 | @Override
191 | public CompletableFuture thenAcceptBothAsync(CompletionStage extends U> other,
192 | BiConsumer super T, ? super U> action, Executor executor) {
193 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action), executor));
194 | }
195 |
196 | @Override
197 | public CompletableFuture runAfterBoth(CompletionStage> other, Runnable action) {
198 | return Context.wrap(state, f.runAfterBoth(other, Context.wrap(state, action)));
199 | }
200 |
201 | @Override
202 | public CompletableFuture runAfterBothAsync(CompletionStage> other, Runnable action) {
203 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action)));
204 | }
205 |
206 | @Override
207 | public CompletableFuture runAfterBothAsync(CompletionStage> other, Runnable action,
208 | Executor executor) {
209 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action), executor));
210 | }
211 |
212 | @Override
213 | public CompletableFuture applyToEither(CompletionStage extends T> other,
214 | Function super T, U> fn) {
215 | return Context.wrap(state, f.applyToEither(other, Context.wrap(state, fn)));
216 | }
217 |
218 | @Override
219 | public CompletableFuture applyToEitherAsync(CompletionStage extends T> other,
220 | Function super T, U> fn) {
221 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn)));
222 | }
223 |
224 | @Override
225 | public CompletableFuture applyToEitherAsync(CompletionStage extends T> other,
226 | Function super T, U> fn, Executor executor) {
227 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn), executor));
228 | }
229 |
230 | @Override
231 | public CompletableFuture acceptEither(CompletionStage extends T> other,
232 | Consumer super T> action) {
233 | return Context.wrap(state, f.acceptEither(other, Context.wrap(state, action)));
234 | }
235 |
236 | @Override
237 | public CompletableFuture acceptEitherAsync(CompletionStage extends T> other,
238 | Consumer super T> action) {
239 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action)));
240 | }
241 |
242 | @Override
243 | public CompletableFuture acceptEitherAsync(CompletionStage extends T> other,
244 | Consumer super T> action, Executor executor) {
245 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action), executor));
246 | }
247 |
248 | @Override
249 | public CompletableFuture runAfterEither(CompletionStage> other, Runnable action) {
250 | return Context.wrap(state, f.runAfterEither(other, Context.wrap(state, action)));
251 | }
252 |
253 | @Override
254 | public CompletableFuture runAfterEitherAsync(CompletionStage> other, Runnable action) {
255 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action)));
256 | }
257 |
258 | @Override
259 | public CompletableFuture runAfterEitherAsync(CompletionStage> other, Runnable action,
260 | Executor executor) {
261 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action), executor));
262 | }
263 |
264 | @Override
265 | public CompletableFuture thenCompose(Function super T, ? extends CompletionStage> fn) {
266 | return Context.wrap(state, f.thenCompose(Context.wrap(state, fn)));
267 | }
268 |
269 | @Override
270 | public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage> fn) {
271 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn)));
272 | }
273 |
274 | @Override
275 | public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage> fn,
276 | Executor executor) {
277 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn), executor));
278 | }
279 |
280 | @Override
281 | public CompletableFuture whenComplete(BiConsumer super T, ? super Throwable> action) {
282 | return Context.wrap(state, f.whenComplete(Context.wrap(state, action)));
283 | }
284 |
285 | @Override
286 | public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable> action) {
287 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action)));
288 | }
289 |
290 | @Override
291 | public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable> action,
292 | Executor executor) {
293 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action), executor));
294 | }
295 |
296 | @Override
297 | public String toString() {
298 | return f.toString();
299 | }
300 |
301 | @Override
302 | public int hashCode() {
303 | return f.hashCode();
304 | }
305 |
306 | @Override
307 | public boolean equals(Object obj) {
308 | return f.equals(obj);
309 | }
310 | }
--------------------------------------------------------------------------------
/core/src/main/java/io/reactiverse/reactivecontexts/core/CompletionStageWrapper.java:
--------------------------------------------------------------------------------
1 | package io.reactiverse.reactivecontexts.core;
2 |
3 | import java.util.concurrent.CompletableFuture;
4 | import java.util.concurrent.CompletionStage;
5 | import java.util.concurrent.Executor;
6 | import java.util.function.BiConsumer;
7 | import java.util.function.BiFunction;
8 | import java.util.function.Consumer;
9 | import java.util.function.Function;
10 |
11 | final class CompletionStageWrapper implements CompletionStage {
12 | private final ContextState state;
13 | private final CompletionStage f;
14 |
15 | CompletionStageWrapper(ContextState state, CompletionStage f) {
16 | this.state = state;
17 | this.f = f;
18 | }
19 |
20 | @Override
21 | public CompletableFuture toCompletableFuture() {
22 | return Context.wrap(f.toCompletableFuture());
23 | }
24 |
25 | @Override
26 | public CompletionStage exceptionally(Function fn) {
27 | return Context.wrap(state, f.exceptionally(Context.wrap(state, fn)));
28 | }
29 |
30 | @Override
31 | public CompletionStage handle(BiFunction super T, Throwable, ? extends U> fn) {
32 | return Context.wrap(state, f.handle(Context.wrap(state, fn)));
33 | }
34 |
35 | @Override
36 | public CompletionStage handleAsync(BiFunction super T, Throwable, ? extends U> fn) {
37 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn)));
38 | }
39 |
40 | @Override
41 | public CompletionStage handleAsync(BiFunction super T, Throwable, ? extends U> fn,
42 | Executor executor) {
43 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn), executor));
44 | }
45 |
46 | @Override
47 | public CompletionStage thenApply(Function super T, ? extends U> fn) {
48 | return Context.wrap(state, f.thenApply(Context.wrap(state, fn)));
49 | }
50 |
51 | @Override
52 | public CompletionStage thenApplyAsync(Function super T, ? extends U> fn) {
53 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn)));
54 | }
55 |
56 | @Override
57 | public CompletionStage thenApplyAsync(Function super T, ? extends U> fn, Executor executor) {
58 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn), executor));
59 | }
60 |
61 | @Override
62 | public CompletionStage thenAccept(Consumer super T> action) {
63 | return Context.wrap(state, f.thenAccept(Context.wrap(state, action)));
64 | }
65 |
66 | @Override
67 | public CompletionStage thenAcceptAsync(Consumer super T> action) {
68 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action)));
69 | }
70 |
71 | @Override
72 | public CompletionStage thenAcceptAsync(Consumer super T> action, Executor executor) {
73 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action), executor));
74 | }
75 |
76 | @Override
77 | public CompletionStage thenRun(Runnable action) {
78 | return Context.wrap(state, f.thenRun(Context.wrap(state, action)));
79 | }
80 |
81 | @Override
82 | public CompletionStage thenRunAsync(Runnable action) {
83 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action)));
84 | }
85 |
86 | @Override
87 | public CompletionStage thenRunAsync(Runnable action, Executor executor) {
88 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action), executor));
89 | }
90 |
91 | @Override
92 | public CompletionStage thenCombine(CompletionStage extends U> other,
93 | BiFunction super T, ? super U, ? extends V> fn) {
94 | return Context.wrap(state, f.thenCombine(other, Context.wrap(state, fn)));
95 | }
96 |
97 | @Override
98 | public CompletionStage thenCombineAsync(CompletionStage extends U> other,
99 | BiFunction super T, ? super U, ? extends V> fn) {
100 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn)));
101 | }
102 |
103 | @Override
104 | public CompletionStage thenCombineAsync(CompletionStage extends U> other,
105 | BiFunction super T, ? super U, ? extends V> fn, Executor executor) {
106 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn), executor));
107 | }
108 |
109 | @Override
110 | public CompletionStage thenAcceptBoth(CompletionStage extends U> other,
111 | BiConsumer super T, ? super U> action) {
112 | return Context.wrap(state, f.thenAcceptBoth(other, Context.wrap(state, action)));
113 | }
114 |
115 | @Override
116 | public CompletionStage thenAcceptBothAsync(CompletionStage extends U> other,
117 | BiConsumer super T, ? super U> action) {
118 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action)));
119 | }
120 |
121 | @Override
122 | public CompletionStage thenAcceptBothAsync(CompletionStage extends U> other,
123 | BiConsumer super T, ? super U> action, Executor executor) {
124 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action), executor));
125 | }
126 |
127 | @Override
128 | public CompletionStage runAfterBoth(CompletionStage> other, Runnable action) {
129 | return Context.wrap(state, f.runAfterBoth(other, Context.wrap(state, action)));
130 | }
131 |
132 | @Override
133 | public CompletionStage runAfterBothAsync(CompletionStage> other, Runnable action) {
134 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action)));
135 | }
136 |
137 | @Override
138 | public CompletionStage runAfterBothAsync(CompletionStage> other, Runnable action,
139 | Executor executor) {
140 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action), executor));
141 | }
142 |
143 | @Override
144 | public CompletionStage applyToEither(CompletionStage extends T> other,
145 | Function super T, U> fn) {
146 | return Context.wrap(state, f.applyToEither(other, Context.wrap(state, fn)));
147 | }
148 |
149 | @Override
150 | public CompletionStage applyToEitherAsync(CompletionStage extends T> other,
151 | Function super T, U> fn) {
152 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn)));
153 | }
154 |
155 | @Override
156 | public CompletionStage applyToEitherAsync(CompletionStage extends T> other,
157 | Function super T, U> fn, Executor executor) {
158 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn), executor));
159 | }
160 |
161 | @Override
162 | public CompletionStage acceptEither(CompletionStage extends T> other,
163 | Consumer super T> action) {
164 | return Context.wrap(state, f.acceptEither(other, Context.wrap(state, action)));
165 | }
166 |
167 | @Override
168 | public CompletionStage acceptEitherAsync(CompletionStage extends T> other,
169 | Consumer super T> action) {
170 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action)));
171 | }
172 |
173 | @Override
174 | public CompletionStage acceptEitherAsync(CompletionStage extends T> other,
175 | Consumer super T> action, Executor executor) {
176 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action), executor));
177 | }
178 |
179 | @Override
180 | public CompletionStage runAfterEither(CompletionStage> other, Runnable action) {
181 | return Context.wrap(state, f.runAfterEither(other, Context.wrap(state, action)));
182 | }
183 |
184 | @Override
185 | public CompletionStage runAfterEitherAsync(CompletionStage> other, Runnable action) {
186 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action)));
187 | }
188 |
189 | @Override
190 | public CompletionStage runAfterEitherAsync(CompletionStage> other, Runnable action,
191 | Executor executor) {
192 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action), executor));
193 | }
194 |
195 | @Override
196 | public CompletionStage thenCompose(Function super T, ? extends CompletionStage> fn) {
197 | return Context.wrap(state, f.thenCompose(Context.wrap(state, fn)));
198 | }
199 |
200 | @Override
201 | public CompletionStage thenComposeAsync(Function super T, ? extends CompletionStage> fn) {
202 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn)));
203 | }
204 |
205 | @Override
206 | public CompletionStage thenComposeAsync(Function super T, ? extends CompletionStage> fn,
207 | Executor executor) {
208 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn), executor));
209 | }
210 |
211 | @Override
212 | public CompletionStage whenComplete(BiConsumer super T, ? super Throwable> action) {
213 | return Context.wrap(state, f.whenComplete(Context.wrap(state, action)));
214 | }
215 |
216 | @Override
217 | public CompletionStage whenCompleteAsync(BiConsumer super T, ? super Throwable> action) {
218 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action)));
219 | }
220 |
221 | @Override
222 | public CompletionStage whenCompleteAsync(BiConsumer super T, ? super Throwable> action,
223 | Executor executor) {
224 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action), executor));
225 | }
226 |
227 | @Override
228 | public String toString() {
229 | return f.toString();
230 | }
231 |
232 | @Override
233 | public int hashCode() {
234 | return f.hashCode();
235 | }
236 |
237 | @Override
238 | public boolean equals(Object obj) {
239 | return f.equals(obj);
240 | }
241 | }
--------------------------------------------------------------------------------
/core/src/main/java/io/reactiverse/reactivecontexts/core/Context.java:
--------------------------------------------------------------------------------
1 | package io.reactiverse.reactivecontexts.core;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.ServiceLoader;
6 | import java.util.concurrent.CompletableFuture;
7 | import java.util.concurrent.CompletionStage;
8 | import java.util.function.BiConsumer;
9 | import java.util.function.BiFunction;
10 | import java.util.function.Consumer;
11 | import java.util.function.Function;
12 |
13 | /**
14 | *
15 | * Main class for initialising the list of {@link ContextPropagator} and {@link ContextProvider}.
16 | *
17 | *
18 | * Upon startup, you should initialise Reactive Contexts by calling {@link #load()}, which
19 | * will initialise all {@link ContextPropagator} and {@link ContextProvider} via the {@link ServiceLoader}
20 | * mechanism.
21 | *
22 | *
23 | * If you don't have an automatic {@link ContextPropagator}, you can then manually capture contexts with
24 | * {@link #capture()}, and then surround your context-requiring code with:
25 | *
47 | * If you are using a flat classpath, this is all you need to know. If you're using a modular class loader,
48 | * or need to have several independent {@link Context} objects, each with their own list of providers and
49 | * propagators, then you need to stop using the global {@link Context} instance and create your own.
50 | *
51 | *
52 | * You can create your own Context with {@link #Context()}, then set it as a thread-local with
53 | * {@link #setThreadInstance(Context)}, and when you're done you can clear the thread-local with
54 | * {@link #clearThreadInstance()}.
55 | *
56 | *
57 | * Note that each captured context state will restore the proper Context thread-local when
58 | * calling {@link #install(ContextState)} and {@link #restore(ContextState)}, so as to avoid
59 | * interference.
60 | *
61 | * @author Stéphane Épardaud
62 | */
63 | public class Context {
64 |
65 | private static Context instance = new Context();
66 | private static ThreadLocal threadInstance = new ThreadLocal();
67 |
68 | /**
69 | * Initialises the list of registered {@link ContextProvider} and {@link ContextPropagator}
70 | * if they are not already initialised. Otherwise, has no effect.
71 | */
72 | public static void load() {
73 | // does not do anything, but triggers the static block load
74 | }
75 |
76 | /**
77 | * Returns a {@link Context} type suitable for handling Reactive Contexts. If there is a
78 | * thread-local {@link Context} as installed by {@link #setThreadInstance(Context)}, the
79 | * thread-local instance is returned. If not, a global shared instance is returned.
80 | * @return a thread-local or global instance of {@link Context}.
81 | * @see #setThreadInstance(Context)
82 | */
83 | public static Context getInstance() {
84 | Context ret = threadInstance.get();
85 | if(ret == null)
86 | ret = instance;
87 | return ret;
88 | }
89 |
90 | /**
91 | * Installs a {@link Context} instance to use in the current thread. It will be returned
92 | * by {@link #getInstance()} within the current thread.
93 | *
94 | * @param instance the {@link Context} instance to install in the current thread
95 | * @return the previous instance of {@link Context} that was associated to the current thread
96 | * @see #clearThreadInstance()
97 | */
98 | public static Context setThreadInstance(Context instance) {
99 | Context oldInstance = threadInstance.get();
100 | threadInstance.set(instance);
101 | return oldInstance;
102 | }
103 |
104 | /**
105 | * Clears the currently-associated {@link Context} instance for the current thread.
106 | * @see #setThreadInstance(Context)
107 | */
108 | public static void clearThreadInstance() {
109 | threadInstance.remove();
110 | }
111 |
112 | private List> providers = new ArrayList<>();
113 | private List propagators = new ArrayList<>();
114 |
115 | /**
116 | * Creates a new Context instance with the associated {@link ContextProvider} and {@link ContextPropagator}
117 | * as looked up by {@link ServiceLoader#load(Class)} for the current classloader.
118 | */
119 | public Context() {
120 | for (ContextProvider> listener : ServiceLoader.load(ContextProvider.class)) {
121 | providers.add(listener);
122 | }
123 | for (ContextPropagator propagator : ServiceLoader.load(ContextPropagator.class)) {
124 | propagators.add(propagator);
125 | propagator.setup();
126 | }
127 | }
128 |
129 | /**
130 | * Captures the current state as given by the current context.
131 | * @return the current context state
132 | * @see #getInstance()
133 | */
134 | public static ContextState capture() {
135 | return getInstance().captureState();
136 | }
137 |
138 | /**
139 | * Captures all contexts currently registered via this {@link Context}'s {@link ContextProvider} plugins.
140 | * @return the storage required for all currently registered contexts.
141 | * @see #install(ContextState)
142 | */
143 | public ContextState captureState() {
144 | Object[] ret = new Object[providers.size()];
145 | for (int i = 0; i < providers.size(); i++) {
146 | ContextProvider> plugin = providers.get(i);
147 | ret[i] = plugin.capture();
148 | }
149 | return new ContextState(this, ret, threadInstance.get());
150 | }
151 |
152 | /**
153 | * Installs a set of contexts previously captured with {@link #captureState()} to all
154 | * currently registered {@link ContextProvider} plugins in this {@link Context}.
155 | * @param state the context state previously captured with {@link #captureState()}
156 | * @return the (current/before installation) storage required for all currently registered contexts.
157 | * @see #captureState()
158 | * @see #restore(ContextState)
159 | * @throws IllegalArgumentException if the state to install has not been captured by this {@link Context} instance.
160 | */
161 | public ContextState install(ContextState state) {
162 | if(this != state.getContext())
163 | throw new IllegalArgumentException("State was captured with different context");
164 | Object[] oldStates = new Object[providers.size()];
165 | Object[] states = state.getState();
166 | for (int i = 0; i < providers.size(); i++) {
167 | @SuppressWarnings("unchecked")
168 | ContextProvider