├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── deploy.sh
├── misc
└── caesar.png
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── github
│ └── vbauer
│ └── caesar
│ ├── annotation
│ ├── Timeout.java
│ └── package-info.java
│ ├── callback
│ ├── AsyncCallback.java
│ ├── AsyncCallbackAdapter.java
│ ├── FutureCallbackAdapter.java
│ └── package-info.java
│ ├── exception
│ ├── AbstractCaesarException.java
│ ├── MissedSyncMethodException.java
│ ├── UnsupportedTimeoutException.java
│ └── package-info.java
│ ├── proxy
│ ├── AsyncInvocationHandler.java
│ ├── AsyncProxyCreator.java
│ └── package-info.java
│ ├── runner
│ ├── AsyncMethodRunner.java
│ ├── AsyncMethodRunnerFactory.java
│ ├── impl
│ │ ├── AsyncCallbackMethodRunner.java
│ │ ├── FutureCallbackMethodRunner.java
│ │ ├── FutureMethodRunner.java
│ │ ├── ListenableFutureMethodRunner.java
│ │ ├── ObservableMethodRunner.java
│ │ ├── SyncMethodRunner.java
│ │ ├── base
│ │ │ ├── AbstractAsyncMethodRunner.java
│ │ │ ├── AbstractCallbackMethodRunner.java
│ │ │ ├── AbstractReturnMethodRunner.java
│ │ │ └── package-info.java
│ │ └── package-info.java
│ ├── package-info.java
│ └── task
│ │ ├── AsyncCallbackTask.java
│ │ ├── FutureCallbackTask.java
│ │ ├── SimpleInvokeTask.java
│ │ └── package-info.java
│ └── util
│ ├── ReflectionUtils.java
│ └── package-info.java
└── test
├── java
└── com
│ └── github
│ └── vbauer
│ └── caesar
│ ├── annotation
│ └── TimeoutAnnotationTest.java
│ ├── basic
│ ├── BasicRunnerTest.java
│ └── BasicTest.java
│ ├── bean
│ ├── CallbackAsync.java
│ ├── FutureAsync.java
│ ├── FutureCallbackAsync.java
│ ├── ListenableFutureAsync.java
│ ├── ObservableAsync.java
│ ├── SimpleAsync.java
│ ├── SimpleSync.java
│ └── Sync.java
│ ├── callback
│ ├── AsyncCallbackAdapterTest.java
│ └── FutureCallbackAdapterTest.java
│ ├── exception
│ └── CaesarExceptionTest.java
│ ├── proxy
│ └── AsyncProxyCreatorTest.java
│ ├── runner
│ ├── AsyncMethodRunnerFactoryTest.java
│ └── impl
│ │ ├── AsyncCallbackMethodRunnerTest.java
│ │ ├── FutureCallbackMethodRunnerTest.java
│ │ ├── FutureMethodRunnerTest.java
│ │ ├── ListenableFutureMethodRunnerTest.java
│ │ └── ObservableMethodRunnerTest.java
│ └── util
│ └── ReflectionUtilsTest.java
└── resources
└── checkstyle.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.gitignore.io
2 |
3 | ### Java ###
4 | *.class
5 |
6 | # Mobile Tools for Java (J2ME)
7 | .mtj.tmp/
8 |
9 | # Package Files #
10 | *.jar
11 | *.war
12 | *.ear
13 |
14 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
15 | hs_err_pid*
16 |
17 |
18 | ### JetBrains ###
19 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
20 |
21 | *.iml
22 |
23 | ## Directory-based project format:
24 | .idea/
25 | # if you remove the above rule, at least ignore the following:
26 |
27 | # User-specific stuff:
28 | # .idea/workspace.xml
29 | # .idea/tasks.xml
30 | # .idea/dictionaries
31 |
32 | # Sensitive or high-churn files:
33 | # .idea/dataSources.ids
34 | # .idea/dataSources.xml
35 | # .idea/sqlDataSources.xml
36 | # .idea/dynamic.xml
37 | # .idea/uiDesigner.xml
38 |
39 | # Gradle:
40 | # .idea/gradle.xml
41 | # .idea/libraries
42 |
43 | # Mongo Explorer plugin:
44 | # .idea/mongoSettings.xml
45 |
46 | ## File-based project format:
47 | *.ipr
48 | *.iws
49 |
50 | ## Plugin-specific files:
51 |
52 | # IntelliJ
53 | out/
54 |
55 | # mpeltonen/sbt-idea plugin
56 | .idea_modules/
57 |
58 | # JIRA plugin
59 | atlassian-ide-plugin.xml
60 |
61 | # Crashlytics plugin (for Android Studio and IntelliJ)
62 | com_crashlytics_export_strings.xml
63 | crashlytics.properties
64 | crashlytics-build.properties
65 |
66 |
67 | ### Maven ###
68 | target/
69 | pom.xml.tag
70 | pom.xml.releaseBackup
71 | pom.xml.versionsBackup
72 | pom.xml.next
73 | release.properties
74 |
75 |
76 | ### Eclipse ###
77 | *.pydevproject
78 | .metadata
79 | .gradle
80 | bin/
81 | tmp/
82 | *.tmp
83 | *.bak
84 | *.swp
85 | *~.nib
86 | local.properties
87 | .settings/
88 | .loadpath
89 |
90 | # Eclipse Core
91 | .project
92 |
93 | # External tool builders
94 | .externalToolBuilders/
95 |
96 | # Locally stored "Eclipse launch configurations"
97 | *.launch
98 |
99 | # CDT-specific
100 | .cproject
101 |
102 | # JDT-specific (Eclipse Java Development Tools)
103 | .classpath
104 |
105 | # PDT-specific
106 | .buildpath
107 |
108 | # sbteclipse plugin
109 | .target
110 |
111 | # TeXlipse plugin
112 | .texlipse
113 |
114 |
115 | ### Windows ###
116 | # Windows image file caches
117 | Thumbs.db
118 | ehthumbs.db
119 |
120 | # Folder config file
121 | Desktop.ini
122 |
123 | # Recycle Bin used on file shares
124 | $RECYCLE.BIN/
125 |
126 | # Windows Installer files
127 | *.cab
128 | *.msi
129 | *.msm
130 | *.msp
131 |
132 | # Windows shortcuts
133 | *.lnk
134 |
135 |
136 | ### OSX ###
137 | .DS_Store
138 | .AppleDouble
139 | .LSOverride
140 |
141 | # Icon must end with two \r
142 | Icon
143 |
144 |
145 | # Thumbnails
146 | ._*
147 |
148 | # Files that might appear on external disk
149 | .Spotlight-V100
150 | .Trashes
151 |
152 | # Directories potentially created on remote AFP share
153 | .AppleDB
154 | .AppleDesktop
155 | Network Trash Folder
156 | Temporary Items
157 | .apdisk
158 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | script: mvn clean package -P strict
4 |
5 | after_success:
6 | - mvn jacoco:report coveralls:report
7 | - bash ./deploy.sh
8 |
9 | jdk:
10 | - oraclejdk8
11 | - oraclejdk9
12 | - openjdk10
13 | - openjdk11
14 |
15 | sudo: false
16 | cache:
17 | directories:
18 | - $HOME/.m2
19 |
20 | env:
21 | global:
22 | - GH_REF: github.com/vbauer/caesar.git
23 | - secure: "eStOv4Qx5mX2IpbkvXUTfolh5dLTV6g4Lge2t5KQHF9gw00Hct0kI0xHJKOr7TXT6e61+dWJdhv2X7AHbQwIE+IGySEOA4jUhiS5bEArylgnjU9Jfcrs7wJZR0oaOWumRjvFuZ1I/o5CAD8EYR06YwNR87wDuzUOnEvok2eT+Uw="
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2015 Vladislav Bauer
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Caesar
3 |
4 | [](http://android-arsenal.com/details/1/1598)
5 | [](https://travis-ci.org/vbauer/caesar)
6 | [](https://coveralls.io/r/vbauer/caesar?branch=master)
7 | [](https://jitpack.io/#vbauer/caesar)
8 | [](https://www.codacy.com/app/bauer-vlad/caesar)
9 |
10 |
11 |
12 | > I came, I saw, I conquered. - Julius Caesar
13 |
14 | **Caesar** is a tiny Java library that allows to create an asynchronous proxy-version of some synchronous bean. It means
15 | that you can still think in terms of your service/bean/object and use its methods instead of writing concurrency code.
16 |
17 | **Use cases:**
18 |
19 | * You have already got some 3-rd party library that works synchronously, but it is necessary to use it asynchronously.
20 | * You need to use both ways (sync & async) in different parts of your applications.
21 |
22 | Caesar will help you to solve these problems.
23 |
24 | **Online documentation:**
25 |
26 | * [Maven site](https://vbauer.github.io/caesar)
27 | * [Javadoc](https://vbauer.github.io/caesar/apidocs)
28 |
29 |
30 | ## Main features:
31 |
32 | * Flexible describing of method signatures:
33 | * using standard Java [Future](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html)
34 | * or using [RxJava](https://github.com/ReactiveX/RxJava) ([Observable](https://github.com/ReactiveX/RxJava/wiki/Observable))
35 | * or using [Guava](https://github.com/google/guava) ([ListenableFuture](https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/ListenableFuture.java), [FutureCallback](https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/FutureCallback.java), [FutureCallbackAdapter](src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java))
36 | * or using custom callbacks ([AsyncCallback](src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java), [AsyncCallbackAdapter](src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java))
37 | * Small library size with zero dependencies
38 | * Compact and very simple API
39 | * Configurable timeouts
40 | * Compatibility:
41 | * Java 8+
42 | * Android
43 |
44 | ## Setup
45 |
46 | Maven:
47 | ```xml
48 |
49 | jitpack.io
50 | https://jitpack.io
51 |
52 |
53 |
54 | com.github.vbauer
55 | caesar
56 | 1.7.0
57 |
58 | ```
59 |
60 | Gradle:
61 | ```groovy
62 | repositories {
63 | maven {
64 | url "https://jitpack.io"
65 | }
66 | }
67 |
68 | dependencies {
69 | compile 'com.github.vbauer:caesar:1.7.0'
70 | }
71 | ```
72 |
73 |
74 | ## Async-proxy creation
75 |
76 | To make async-proxy for some bean, you need to use `AsyncProxyCreator`:
77 |
78 | ```java
79 | public static ASYNC create(
80 | final SYNC bean,
81 | final Class asyncInterface,
82 | final ExecutorService executor,
83 | final boolean validate
84 | )
85 | ```
86 |
87 | **Parameters:**
88 |
89 |
90 |
bean
91 |
Not-null object which will be wrapped by async-proxy.
92 |
asyncInterface
93 |
Class which represents async-proxy. See an example section for more details.
94 |
executor
95 |
Executor service for running background operations. The usual choice is `ThreadPoolExecutor`.
96 |
validate
97 |
Validate mapping between bean and asyncInterface during proxy creation (otherwise it will be checked in runtime). It is an optional parameter (default value is true).
98 |
99 |
100 |
101 | ## Mapping, Naming conventions
102 |
103 | To make correct mapping between object and async-proxy, it is necessary to perform some conventions.
104 | Asynchronous proxy method signature must match the signature of the object method, except several points:
105 |
106 | * To use **Future** as result value, return class must be `Future`
107 | * To use **Guava**:
108 | * return class should be `ListenableFuture`
109 | * or add new parameter `FutureCallback` at the first place of the method signature and change result type to `void`
110 | * To use **RxJava**, return class must be `Observable`
111 | * To use **AsyncCallback**, you need to:
112 | * add new parameter `AsyncCallback` at the first place of the method signature
113 | * change result type to `void`
114 |
115 | If this conventions are not complied, than the corresponding sync-method with the same signature should be invoked.
116 | It will be still invoked in the separate thread to allow to use `@Timeout` annotation.
117 |
118 |
119 | ## Example
120 |
121 | Lets make an async-proxy for the following bean:
122 | ```java
123 | public class Sync {
124 |
125 | public String hello(final String name) {
126 | // Just a simple code for an example.
127 | return String.format("Hello, %s", name);
128 | }
129 |
130 | }
131 | ```
132 |
133 | First of all, we need to create an async-interface for this bean:
134 | ```java
135 | // IMPORTANT: It is just an example. Choose the most appropriate way for you.
136 | // All methods could not be presented at the same time in the real code.
137 | public interface Async {
138 |
139 | // Future will be the new return type.
140 | Future hello(String name);
141 |
142 | // Future will be the new return type.
143 | ListenableFuture hello(String name);
144 |
145 | // Observable will be also the new return type.
146 | Observable hello(String name);
147 |
148 | // AsyncCallback should be added as the first parameter.
149 | void hello(AsyncCallback callback, String name);
150 |
151 | // FutureCallback should be also added as the first parameter.
152 | void hello(FutureCallback callback, String name);
153 |
154 | }
155 | ```
156 |
157 | After that we can create an async-proxy using `AsyncProxyCreator`:
158 | ```java
159 | final AsyncBean asyncBean = AsyncProxyCreator.create(
160 | new Sync(), Async.class, Executors.newFixedThreadPool(5));
161 | ```
162 |
163 | That's all. Now you can use your bean asynchronously. All methods will be invoked in threads from thread pool.
164 |
165 | ```java
166 | // Retrieve result using Future:
167 | final Future future = asyncBean.hello("John");
168 | final String text = future.get(); // text is "Hello, John"
169 |
170 | // Retrieve result using ListenableFuture:
171 | final ListenableFuture listenableFuture = asyncBean.hello("George");
172 | final String text = listenableFuture.get(); // text is "Hello, George"
173 |
174 | // Retrieve result using RxJava and Observable:
175 | final Observable observable = asyncBean.hello("Paul");
176 | final String text = observable.toBlocking().first(); // text is "Hello, Paul"
177 |
178 | // Retrieve result using custom callback:
179 | asyncBean.hello(new AsyncCallbackAdapter() {
180 | @Override
181 | public void onSuccess(final String text) {
182 | // text is "Hello, Ringo"
183 | }
184 | }, "Ringo");
185 |
186 | // Retrieve result using FutureCallback:
187 | asyncBean.hello(new FutureCallback() {
188 | @Override
189 | public void onSuccess(final String text) {
190 | // text is "Hello, guys"
191 | }
192 | @Override
193 | public void onFailure(final Throwable t) {
194 | // it will not be executed
195 | }
196 | }, "guys");
197 | ```
198 |
199 |
200 | ## @Timeout
201 |
202 | Sometimes it is useful to setup timeout value to cancel operation (ex: REST API call which takes a lot of time).
203 | You can use `@Timeout` annotation to do it (cancel operation after 3 seconds):
204 |
205 | ```java
206 | public interface Async {
207 |
208 | @Timeout(value = 3, unit = TimeUnit.SECONDS)
209 | Future hello(String name);
210 |
211 | ```
212 |
213 | It is also possible to configure timeouts for all methods of async-proxy putting annotation on class:
214 |
215 | ```java
216 | @Timeout(5000)
217 | public interface Async {
218 | Future foo1();
219 | Future foo2();
220 | }
221 | ```
222 |
223 | **IMPORTANT:** `ScheduledExecutorService` should be used to switch on this feature.
224 |
225 | ## Development
226 |
227 | To build project in strict mode with tests, you can use your local Maven:
228 |
229 | ```bash
230 | mvn -P strict clean package
231 | ```
232 |
233 |
234 | ## Might also like
235 |
236 | * [jconditions](https://github.com/vbauer/jconditions) - Extra conditional annotations for JUnit.
237 | * [jackdaw](https://github.com/vbauer/jackdaw) - Java Annotation Processor which allows to simplify development.
238 | * [houdini](https://github.com/vbauer/houdini) - Type conversion system for Spring framework.
239 | * [herald](https://github.com/vbauer/herald) - Logging annotation for Spring framework.
240 | * [commons-vfs2-cifs](https://github.com/vbauer/commons-vfs2-cifs) - SMB/CIFS provider for Commons VFS.
241 | * [avconv4java](https://github.com/vbauer/avconv4java) - Java interface to avconv tool.
242 |
243 |
244 | ## License
245 |
246 | Copyright 2015 Vladislav Bauer
247 |
248 | Licensed under the Apache License, Version 2.0 (the "License");
249 | you may not use this file except in compliance with the License.
250 | You may obtain a copy of the License at
251 |
252 | http://www.apache.org/licenses/LICENSE-2.0
253 |
254 | Unless required by applicable law or agreed to in writing, software
255 | distributed under the License is distributed on an "AS IS" BASIS,
256 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
257 | See the License for the specific language governing permissions and
258 | limitations under the License.
259 |
260 | See [LICENSE](LICENSE) file for details.
261 |
--------------------------------------------------------------------------------
/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Exit with nonzero exit code if anything fails
4 | accept -e
5 |
6 | # Lets work only for master
7 | if ! [ "$TRAVIS_BRANCH" = "master" ]
8 | then
9 | echo "Not a master, not deploying"
10 | exit 0
11 | fi
12 |
13 | # Generate Maven site
14 | mvn site
15 |
16 | # Go to the generated directory and create a *new* Git repo
17 | cd target/site
18 | git init
19 |
20 | # Inside this git repo we'll pretend to be a new user
21 | git config user.name "Vladislav Bauer"
22 | git config user.email "bauer.vlad@gmail.com"
23 |
24 | # The first and only commit to this new Git repo contains all the
25 | # files present with the commit message "Generate Maven Site"
26 | git add .
27 | git commit -m "Generate Maven Site"
28 |
29 | # Force push from the current repo's master branch to the remote
30 | # repo's gh-pages branch. (All previous history on the gh-pages branch
31 | # will be lost, since we are overwriting it.) We redirect any output to
32 | # /dev/null to hide any sensitive credential data that might otherwise be exposed
33 | git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:gh-pages > /dev/null 2>&1
34 |
--------------------------------------------------------------------------------
/misc/caesar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vbauer/caesar/bc5f07c0d3fd5e40167ab72b36206b218555f734/misc/caesar.png
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.github.vbauer
8 | caesar
9 | 1.7.0
10 |
11 | Converting synchronous beans to asynchronous
12 | https://github.com/vbauer/caesar
13 | 2015
14 |
15 |
16 |
17 | Apache License, Version 2.0
18 | http://www.apache.org/licenses/LICENSE-2.0
19 | manual
20 |
21 |
22 |
23 |
24 | GitHub Issues
25 | https://github.com/vbauer/caesar/issues
26 |
27 |
28 |
29 | Travis
30 | https://travis-ci.org/vbauer/caesar
31 |
32 |
33 |
34 |
35 | vbauer
36 | Vladislav Bauer
37 | bauer.vlad@gmail.com
38 | http://linkedin.com/in/vladislavbauer
39 |
40 | architect
41 | developer
42 |
43 |
44 |
45 |
46 |
47 | 3.4.0
48 |
49 |
50 |
51 | UTF-8
52 | 1.8
53 |
54 | 1.3.8
55 | 27.0-jre
56 |
57 | 4.12
58 | 1.2.0
59 |
60 | 3.8.0
61 | 3.0.1
62 | 2.22.0
63 | 3.1.0
64 | 2.8.2
65 | 2.5.2
66 | 3.1.0
67 | 3.1.0
68 | 3.7.1
69 | 3.0.0
70 | 3.0.1
71 |
72 | 3.0.0
73 | 3.11.0
74 | 0.8.2
75 | 4.3.0
76 |
77 |
78 |
79 |
80 |
81 | io.reactivex
82 | rxjava
83 | ${rxjava.version}
84 | provided
85 | true
86 |
87 |
88 |
89 | com.google.guava
90 | guava
91 | ${guava.version}
92 | provided
93 | true
94 |
95 |
96 |
97 |
98 |
99 |
100 | junit
101 | junit
102 | ${junit.version}
103 | test
104 |
105 |
106 |
107 | com.pushtorefresh.java-private-constructor-checker
108 | checker
109 | ${checker.version}
110 | test
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 | org.apache.maven.plugins
123 | maven-compiler-plugin
124 | ${maven.compiler.plugin.version}
125 |
126 | ${java.version}
127 | ${java.version}
128 | ${project.build.sourceEncoding}
129 | true
130 |
131 |
132 |
133 |
134 | org.apache.maven.plugins
135 | maven-source-plugin
136 | ${maven.source.plugin.version}
137 |
138 |
139 | attach-sources
140 | verify
141 |
142 | jar-no-fork
143 |
144 |
145 |
146 |
147 |
148 |
149 | org.apache.maven.plugins
150 | maven-surefire-plugin
151 | ${maven.surefire.plugin.version}
152 |
153 |
154 |
155 | org.apache.maven.plugins
156 | maven-clean-plugin
157 | ${maven.clean.plugin.version}
158 |
159 |
160 |
161 | org.apache.maven.plugins
162 | maven-deploy-plugin
163 | ${maven.deploy.plugin.version}
164 |
165 |
166 |
167 | org.apache.maven.plugins
168 | maven-install-plugin
169 | ${maven.install.plugin.version}
170 |
171 |
172 |
173 | org.apache.maven.plugins
174 | maven-jar-plugin
175 | ${maven.jar.plugin.version}
176 |
177 |
178 |
179 | org.apache.maven.plugins
180 | maven-resources-plugin
181 | ${maven.resources.plugin.version}
182 |
183 |
184 |
185 | org.apache.maven.plugins
186 | maven-site-plugin
187 | ${maven.site.plugin.version}
188 |
189 |
190 |
191 | org.apache.maven.plugins
192 | maven-project-info-reports-plugin
193 | ${maven.project.info.reports.plugin.version}
194 |
195 |
196 |
197 |
198 |
199 | org.jacoco
200 | jacoco-maven-plugin
201 | ${maven.jacoco.plugin.version}
202 |
203 |
204 | prepare-agent
205 |
206 | prepare-agent
207 |
208 |
209 |
210 |
211 |
212 |
213 | org.eluder.coveralls
214 | coveralls-maven-plugin
215 | ${maven.coveralls.plugin.version}
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 | strict
226 |
227 |
228 |
229 |
230 | org.apache.maven.plugins
231 | maven-checkstyle-plugin
232 | ${maven.checkstyle.plugin.version}
233 |
234 | true
235 | src/test/resources/checkstyle.xml
236 | false
237 |
238 |
239 |
240 | package
241 |
242 | check
243 |
244 |
245 |
246 |
247 |
248 |
249 | org.apache.maven.plugins
250 | maven-pmd-plugin
251 | ${maven.pmd.plugin.version}
252 |
253 | true
254 | true
255 | true
256 | false
257 |
258 |
259 |
260 | package
261 |
262 | check
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 | org.apache.maven.plugins
279 | maven-javadoc-plugin
280 | ${maven.javadoc.plugin.version}
281 |
282 |
283 |
284 | org.apache.maven.plugins
285 | maven-surefire-report-plugin
286 | ${maven.surefire.plugin.version}
287 |
288 |
289 |
290 |
291 |
292 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/annotation/Timeout.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.annotation;
2 |
3 | import java.lang.annotation.*;
4 | import java.util.concurrent.TimeUnit;
5 |
6 | /**
7 | * Timeout annotation allows to stop operation after some period.
8 | *
9 | * @author Vladislav Bauer
10 | */
11 |
12 | @Documented
13 | @Retention(RetentionPolicy.RUNTIME)
14 | @Target({ ElementType.METHOD, ElementType.TYPE })
15 | public @interface Timeout {
16 |
17 | /**
18 | * @return timeout value
19 | */
20 | long value();
21 |
22 | /**
23 | * @return time unit
24 | */
25 | TimeUnit unit() default TimeUnit.SECONDS;
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/annotation/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Package with annotations.
3 | *
4 | * @author Vladislav Bauer
5 | */
6 | package com.github.vbauer.caesar.annotation;
7 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.callback;
2 |
3 | /**
4 | * @param type of result
5 | * @author Vladislav Bauer
6 | */
7 |
8 | public interface AsyncCallback {
9 |
10 | /**
11 | * Callback-method on success.
12 | *
13 | * @param result result of operation
14 | */
15 | void onSuccess(T result);
16 |
17 | /**
18 | * Callback-method on failure.
19 | *
20 | * @param caught exception
21 | */
22 | void onFailure(Throwable caught);
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.callback;
2 |
3 | /**
4 | * {@link AsyncCallback}
5 | *
6 | * @param type of result
7 | * @author Vladislav Bauer
8 | */
9 |
10 | public class AsyncCallbackAdapter implements AsyncCallback {
11 |
12 | /**
13 | * {@inheritDoc}
14 | */
15 | @Override
16 | public void onSuccess(final T result) {
17 | // Do nothing.
18 | }
19 |
20 | /**
21 | * {@inheritDoc}
22 | */
23 | @Override
24 | public void onFailure(final Throwable caught) {
25 | // Do nothing.
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.callback;
2 |
3 | import com.google.common.util.concurrent.FutureCallback;
4 |
5 | /**
6 | * {@link FutureCallback}
7 | *
8 | * @param type of result
9 | * @author Vladislav Bauer
10 | */
11 |
12 | public class FutureCallbackAdapter implements FutureCallback {
13 |
14 | /**
15 | * {@inheritDoc}
16 | */
17 | @Override
18 | public void onSuccess(final T result) {
19 | // Do nothing.
20 | }
21 |
22 | /**
23 | * {@inheritDoc}
24 | */
25 | @Override
26 | public void onFailure(final Throwable t) {
27 | // Do nothing.
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/callback/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Callback classes for the {@link com.github.vbauer.caesar.runner.impl.AsyncCallbackMethodRunner}.
3 | *
4 | * @author Vladislav Bauer
5 | */
6 | package com.github.vbauer.caesar.callback;
7 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/exception/AbstractCaesarException.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.exception;
2 |
3 | /**
4 | * @author Vladislav Bauer
5 | */
6 |
7 | @SuppressWarnings("serial")
8 | public abstract class AbstractCaesarException extends RuntimeException {
9 |
10 | /**
11 | * {@inheritDoc}
12 | */
13 | @Override
14 | public String getMessage() {
15 | return "Some problem has happened during Caesar work";
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.exception;
2 |
3 | import java.lang.reflect.Method;
4 | import java.util.Arrays;
5 |
6 | /**
7 | * @author Vladislav Bauer
8 | */
9 |
10 | @SuppressWarnings("serial")
11 | public class MissedSyncMethodException extends AbstractCaesarException {
12 |
13 | private final Method method;
14 | private final Object[] arguments;
15 |
16 |
17 | public MissedSyncMethodException(final Method method, final Object... arguments) {
18 | this.method = method;
19 | this.arguments = arguments;
20 | }
21 |
22 |
23 | public Method getMethod() {
24 | return method;
25 | }
26 |
27 | public Object[] getArguments() {
28 | return arguments;
29 | }
30 |
31 |
32 | /**
33 | * {@inheritDoc}
34 | */
35 | @Override
36 | public String getMessage() {
37 | return String.format(
38 | "Can not find appropriate sync-method \"%s\", parameters: %s",
39 | getMethod(), Arrays.toString(getArguments())
40 | );
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.exception;
2 |
3 | import java.util.concurrent.Executor;
4 | import java.util.concurrent.ScheduledExecutorService;
5 |
6 | /**
7 | * @author Vladislav Bauer
8 | */
9 |
10 | @SuppressWarnings("serial")
11 | public class UnsupportedTimeoutException extends AbstractCaesarException {
12 |
13 | private final Executor executor;
14 |
15 |
16 | public UnsupportedTimeoutException(final Executor executor) {
17 | this.executor = executor;
18 | }
19 |
20 |
21 | public Executor getExecutor() {
22 | return executor;
23 | }
24 |
25 |
26 | /**
27 | * {@inheritDoc}
28 | */
29 | @Override
30 | public String getMessage() {
31 | return String.format(
32 | "%s does not support timeouts. Use %s.",
33 | getExecutor(), ScheduledExecutorService.class
34 | );
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/exception/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Exception classes to notify about critical errors.
3 | *
4 | * @author Vladislav Bauer
5 | */
6 | package com.github.vbauer.caesar.exception;
7 |
--------------------------------------------------------------------------------
/src/main/java/com/github/vbauer/caesar/proxy/AsyncInvocationHandler.java:
--------------------------------------------------------------------------------
1 | package com.github.vbauer.caesar.proxy;
2 |
3 | import com.github.vbauer.caesar.annotation.Timeout;
4 | import com.github.vbauer.caesar.exception.MissedSyncMethodException;
5 | import com.github.vbauer.caesar.exception.UnsupportedTimeoutException;
6 | import com.github.vbauer.caesar.runner.AsyncMethodRunner;
7 | import com.github.vbauer.caesar.runner.AsyncMethodRunnerFactory;
8 | import com.github.vbauer.caesar.util.ReflectionUtils;
9 |
10 | import java.lang.reflect.InvocationHandler;
11 | import java.lang.reflect.Method;
12 | import java.util.Collection;
13 | import java.util.concurrent.*;
14 |
15 | /**
16 | * @author Vladislav Bauer
17 | */
18 |
19 | public final class AsyncInvocationHandler implements InvocationHandler {
20 |
21 | private static final Collection METHOD_RUNNERS =
22 | AsyncMethodRunnerFactory.createMethodRunners();
23 |
24 | private final Object origin;
25 | private final ExecutorService executor;
26 |
27 |
28 | private AsyncInvocationHandler(final Object origin, final ExecutorService executor) {
29 | this.origin = origin;
30 | this.executor = executor;
31 | }
32 |
33 |
34 | public static AsyncInvocationHandler create(final Object origin, final ExecutorService executor) {
35 | return new AsyncInvocationHandler(origin, executor);
36 | }
37 |
38 |
39 | /**
40 | * {@inheritDoc}
41 | */
42 | @Override
43 | public Object invoke(
44 | final Object proxy, final Method method, final Object[] args
45 | ) throws Throwable {
46 | final AsyncMethodRunner runner = findAsyncMethodRunner(method);
47 | if (runner == null) {
48 | throw new MissedSyncMethodException(method, args);
49 | }
50 | return runAsyncMethod(runner, method, args);
51 | }
52 |
53 |
54 | protected AsyncMethodRunner findAsyncMethodRunner(final Method method) {
55 | for (final AsyncMethodRunner runner : METHOD_RUNNERS) {
56 | final Method syncMethod = runner.findSyncMethod(origin, method);
57 | if (syncMethod != null) {
58 | return runner;
59 | }
60 | }
61 | return null;
62 | }
63 |
64 |
65 | private Object runAsyncMethod(
66 | final AsyncMethodRunner runner, final Method method, final Object[] args
67 | ) throws Throwable {
68 | final Timeout timeout = getTimeout(method);
69 | if (timeout != null && !(executor instanceof ScheduledExecutorService)) {
70 | throw new UnsupportedTimeoutException(executor);
71 | }
72 |
73 | final Method syncMethod = runner.findSyncMethod(origin, method);
74 | final boolean methodAccessible = syncMethod.isAccessible();
75 | syncMethod.setAccessible(methodAccessible);
76 |
77 | try {
78 | final Callable