├── .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 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Caesar-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1598) 5 | [![Build Status](https://travis-ci.org/vbauer/caesar.svg)](https://travis-ci.org/vbauer/caesar) 6 | [![Coverage Status](https://coveralls.io/repos/vbauer/caesar/badge.svg?branch=master)](https://coveralls.io/r/vbauer/caesar?branch=master) 7 | [![Maven](https://img.shields.io/github/tag/vbauer/caesar.svg?label=maven)](https://jitpack.io/#vbauer/caesar) 8 | [![Codacy Badge](https://api.codacy.com/project/badge/grade/defb1d30427c4220aa8cf8fc9fa7830c)](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 task = runner.createCall(origin, syncMethod, args); 79 | final Future future = schedule(task, timeout); 80 | return runner.processResultFuture(future, executor); 81 | } finally { 82 | syncMethod.setAccessible(methodAccessible); 83 | } 84 | } 85 | 86 | private Timeout getTimeout(final Method method) { 87 | return ReflectionUtils.findAnnotationFromMethodOrClass(method, Timeout.class); 88 | } 89 | 90 | private Future schedule(final Callable task, final Timeout timeout) { 91 | final Future future = executor.submit(task); 92 | 93 | if (timeout != null) { 94 | final long value = timeout.value(); 95 | if (value > 0) { 96 | final TimeUnit unit = timeout.unit(); 97 | final Runnable cancelOperation = () -> future.cancel(true); 98 | final ScheduledExecutorService scheduler = (ScheduledExecutorService) executor; 99 | scheduler.schedule(cancelOperation, value, unit); 100 | } 101 | } 102 | 103 | return future; 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.proxy; 2 | 3 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 4 | import com.github.vbauer.caesar.runner.AsyncMethodRunner; 5 | import com.github.vbauer.caesar.util.ReflectionUtils; 6 | 7 | import java.lang.reflect.Method; 8 | import java.lang.reflect.Proxy; 9 | import java.util.concurrent.ExecutorService; 10 | 11 | /** 12 | * Proxy creator that makes asynchronous variant of bean. 13 | * 14 | * @author Vladislav Bauer 15 | */ 16 | 17 | public final class AsyncProxyCreator { 18 | 19 | private AsyncProxyCreator() { 20 | throw new UnsupportedOperationException(); 21 | } 22 | 23 | 24 | public static ASYNC create( 25 | final SYNC bean, final Class asyncInterface, final ExecutorService executor 26 | ) { 27 | return create(bean, asyncInterface, executor, true); 28 | } 29 | 30 | @SuppressWarnings("unchecked") 31 | public static ASYNC create( 32 | final SYNC bean, final Class asyncInterface, final ExecutorService executor, final boolean validate 33 | ) { 34 | final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); 35 | final Class beanClass = bean.getClass(); 36 | final ClassLoader classLoader = beanClass.getClassLoader(); 37 | final Class[] interfaces = { 38 | asyncInterface, 39 | }; 40 | 41 | final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); 42 | return validate ? validate(proxy, handler) : proxy; 43 | } 44 | 45 | 46 | private static T validate(final T proxy, final AsyncInvocationHandler handler) { 47 | final Class targetClass = ReflectionUtils.getClassWithoutProxies(proxy); 48 | final Method[] methods = targetClass.getDeclaredMethods(); 49 | 50 | for (final Method method : methods) { 51 | final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); 52 | if (runner == null) { 53 | throw new MissedSyncMethodException(method); 54 | } 55 | } 56 | 57 | return proxy; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/proxy/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Proxy-related classes, ex: for proxy creation and methods invocation. 3 | * 4 | * @author Vladislav Bauer 5 | */ 6 | package com.github.vbauer.caesar.proxy; 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Future; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface AsyncMethodRunner { 13 | 14 | Method findSyncMethod(Object origin, Method asyncMethod); 15 | 16 | Callable createCall(Object origin, Method syncMethod, Object[] args); 17 | 18 | Object processResultFuture(Future future, ExecutorService executor) throws Throwable; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactory.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner; 2 | 3 | import com.github.vbauer.caesar.util.ReflectionUtils; 4 | 5 | import java.util.Arrays; 6 | import java.util.Collection; 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | /** 11 | * @author Vladislav Bauer 12 | */ 13 | 14 | public final class AsyncMethodRunnerFactory { 15 | 16 | public static final String PACKAGE_NAME = "com.github.vbauer.caesar.runner.impl"; 17 | 18 | /** 19 | * Immutable list with class names of method runners. 20 | * 21 | * IMPORTANT: 22 | * This classes must be listed in the right order: from more-specific to less-specific classes. 23 | */ 24 | public static final List CLASS_NAMES = Collections.unmodifiableList( 25 | Arrays.asList( 26 | "ObservableMethodRunner", 27 | "ListenableFutureMethodRunner", 28 | "FutureCallbackMethodRunner", 29 | "FutureMethodRunner", 30 | "AsyncCallbackMethodRunner", 31 | "SyncMethodRunner" 32 | ) 33 | ); 34 | 35 | 36 | private AsyncMethodRunnerFactory() { 37 | throw new UnsupportedOperationException(); 38 | } 39 | 40 | 41 | public static Collection createMethodRunners() { 42 | final Collection classNames = 43 | ReflectionUtils.classNames(PACKAGE_NAME, CLASS_NAMES); 44 | 45 | return ReflectionUtils.createObjects(classNames); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.callback.AsyncCallback; 4 | import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; 5 | import com.github.vbauer.caesar.runner.task.AsyncCallbackTask; 6 | 7 | import java.lang.reflect.Method; 8 | import java.util.concurrent.Callable; 9 | 10 | /** 11 | * @author Vladislav Bauer 12 | */ 13 | 14 | @SuppressWarnings("all") 15 | public class AsyncCallbackMethodRunner extends AbstractCallbackMethodRunner { 16 | 17 | /** 18 | * {@inheritDoc} 19 | */ 20 | @Override 21 | protected Callable createCall( 22 | final Object origin, final Method syncMethod, final Object callback, final Object[] args 23 | ) { 24 | return new AsyncCallbackTask(origin, syncMethod, args, (AsyncCallback) callback); 25 | } 26 | 27 | /** 28 | * {@inheritDoc} 29 | */ 30 | @Override 31 | protected Class getCallbackClass() { 32 | return AsyncCallback.class; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; 4 | import com.github.vbauer.caesar.runner.task.FutureCallbackTask; 5 | import com.google.common.util.concurrent.FutureCallback; 6 | 7 | import java.lang.reflect.Method; 8 | import java.util.concurrent.Callable; 9 | 10 | /** 11 | * @author Vladislav Bauer 12 | */ 13 | 14 | @SuppressWarnings("all") 15 | public class FutureCallbackMethodRunner extends AbstractCallbackMethodRunner { 16 | 17 | /** 18 | * {@inheritDoc} 19 | */ 20 | @Override 21 | protected Callable createCall( 22 | final Object origin, final Method syncMethod, final Object callback, final Object[] args 23 | ) { 24 | return new FutureCallbackTask(origin, syncMethod, args, (FutureCallback) callback); 25 | } 26 | 27 | /** 28 | * {@inheritDoc} 29 | */ 30 | @Override 31 | protected Class getCallbackClass() { 32 | return FutureCallback.class; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.runner.impl.base.AbstractReturnMethodRunner; 4 | 5 | import java.util.concurrent.Future; 6 | 7 | /** 8 | * @author Vladislav Bauer 9 | */ 10 | 11 | @SuppressWarnings("all") 12 | public class FutureMethodRunner extends AbstractReturnMethodRunner { 13 | 14 | /** 15 | * {@inheritDoc} 16 | */ 17 | @Override 18 | protected Class getReturnClass(final Class originReturnType) { 19 | return Future.class; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/ListenableFutureMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.runner.impl.base.AbstractReturnMethodRunner; 4 | import com.google.common.util.concurrent.JdkFutureAdapters; 5 | import com.google.common.util.concurrent.ListenableFuture; 6 | 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Future; 9 | 10 | /** 11 | * @author Vladislav Bauer 12 | */ 13 | 14 | @SuppressWarnings("all") 15 | public class ListenableFutureMethodRunner extends AbstractReturnMethodRunner { 16 | 17 | /** 18 | * {@inheritDoc} 19 | */ 20 | @Override 21 | public Object processResultFuture(final Future future, final ExecutorService executor) { 22 | return JdkFutureAdapters.listenInPoolThread(future, executor); 23 | } 24 | 25 | /** 26 | * {@inheritDoc} 27 | */ 28 | @Override 29 | protected Class getReturnClass(final Class originReturnType) { 30 | return ListenableFuture.class; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/ObservableMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.runner.impl.base.AbstractReturnMethodRunner; 4 | import rx.Observable; 5 | 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Future; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | @SuppressWarnings("all") 14 | public class ObservableMethodRunner extends AbstractReturnMethodRunner { 15 | 16 | /** 17 | * {@inheritDoc} 18 | */ 19 | @Override 20 | public Object processResultFuture(final Future future, final ExecutorService executor) { 21 | return Observable.from(future); 22 | } 23 | 24 | /** 25 | * {@inheritDoc} 26 | */ 27 | @Override 28 | protected Class getReturnClass(final Class originReturnType) { 29 | return Observable.class; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/SyncMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.runner.impl.base.AbstractReturnMethodRunner; 4 | 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Future; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | @SuppressWarnings("all") 13 | public class SyncMethodRunner extends AbstractReturnMethodRunner { 14 | 15 | /** 16 | * {@inheritDoc} 17 | */ 18 | @Override 19 | protected Class getReturnClass(final Class originReturnType) { 20 | return originReturnType; 21 | } 22 | 23 | /** 24 | * {@inheritDoc} 25 | */ 26 | @Override 27 | public Object processResultFuture( 28 | final Future future, final ExecutorService executor 29 | ) throws Throwable { 30 | return future.get(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractAsyncMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl.base; 2 | 3 | import com.github.vbauer.caesar.runner.AsyncMethodRunner; 4 | import com.github.vbauer.caesar.runner.task.SimpleInvokeTask; 5 | import com.github.vbauer.caesar.util.ReflectionUtils; 6 | 7 | import java.lang.reflect.Method; 8 | import java.util.concurrent.Callable; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Future; 11 | 12 | /** 13 | * @author Vladislav Bauer 14 | */ 15 | 16 | public abstract class AbstractAsyncMethodRunner implements AsyncMethodRunner { 17 | 18 | /** 19 | * {@inheritDoc} 20 | */ 21 | @Override 22 | public final Method findSyncMethod(final Object origin, final Method asyncMethod) { 23 | final Class targetClass = ReflectionUtils.getClassWithoutProxies(origin); 24 | final String methodName = asyncMethod.getName(); 25 | 26 | final Class returnType = asyncMethod.getReturnType(); 27 | final Class[] parameterTypes = asyncMethod.getParameterTypes(); 28 | 29 | return findSyncMethod(targetClass, methodName, returnType, parameterTypes); 30 | } 31 | 32 | /** 33 | * {@inheritDoc} 34 | */ 35 | @Override 36 | public Callable createCall( 37 | final Object origin, final Method syncMethod, final Object[] args 38 | ) { 39 | return new SimpleInvokeTask<>(origin, syncMethod, args); 40 | } 41 | 42 | /** 43 | * {@inheritDoc} 44 | */ 45 | @Override 46 | public Object processResultFuture( 47 | final Future future, final ExecutorService executor 48 | ) throws Throwable { 49 | return future; 50 | } 51 | 52 | 53 | protected abstract Method findSyncMethod( 54 | Class targetClass, String methodName, Class returnType, Class[] parameterTypes 55 | ); 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl.base; 2 | 3 | import com.github.vbauer.caesar.util.ReflectionUtils; 4 | 5 | import java.lang.reflect.Method; 6 | import java.util.Arrays; 7 | import java.util.concurrent.Callable; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { 14 | 15 | /** 16 | * {@inheritDoc} 17 | */ 18 | @Override 19 | public Callable createCall(final Object origin, final Method syncMethod, final Object[] args) { 20 | final Object asyncCallback = args[0]; 21 | final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); 22 | 23 | return createCall(origin, syncMethod, asyncCallback, restArgs); 24 | } 25 | 26 | /** 27 | * {@inheritDoc} 28 | */ 29 | @Override 30 | protected Method findSyncMethod( 31 | final Class targetClass, final String methodName, 32 | final Class returnType, final Class[] parameterTypes 33 | ) { 34 | if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { 35 | final Class lastParam = parameterTypes[0]; 36 | final Class callbackClass = getCallbackClass(); 37 | 38 | if (callbackClass.isAssignableFrom(lastParam)) { 39 | final Class[] restParamTypes = 40 | Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); 41 | 42 | return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); 43 | } 44 | 45 | } 46 | return null; 47 | } 48 | 49 | 50 | protected abstract Callable createCall( 51 | Object origin, Method syncMethod, Object callback, Object[] args 52 | ); 53 | 54 | protected abstract Class getCallbackClass(); 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractReturnMethodRunner.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl.base; 2 | 3 | import com.github.vbauer.caesar.util.ReflectionUtils; 4 | 5 | import java.lang.reflect.Method; 6 | import java.util.Objects; 7 | 8 | /** 9 | * {@link AbstractAsyncMethodRunner} 10 | * 11 | * @author Vladislav Bauer 12 | */ 13 | 14 | public abstract class AbstractReturnMethodRunner extends AbstractAsyncMethodRunner { 15 | 16 | /** 17 | * {@inheritDoc} 18 | */ 19 | @Override 20 | protected Method findSyncMethod( 21 | final Class targetClass, final String methodName, 22 | final Class returnType, final Class[] parameterTypes 23 | ) { 24 | final Class returnClass = getReturnClass(returnType); 25 | return Objects.equals(returnClass, returnType) 26 | ? ReflectionUtils.findDeclaredMethod(targetClass, methodName, parameterTypes) : null; 27 | } 28 | 29 | 30 | protected abstract Class getReturnClass(Class originReturnType); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/base/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Base classes for method runners to aggregate common logic. 3 | */ 4 | package com.github.vbauer.caesar.runner.impl.base; 5 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/impl/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Implementations of {@link com.github.vbauer.caesar.runner.AsyncMethodRunner} 3 | * 4 | * @author Vladislav Bauer 5 | */ 6 | package com.github.vbauer.caesar.runner.impl; 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Classes related to {@link com.github.vbauer.caesar.runner.AsyncMethodRunner}. 3 | * 4 | * @author Vladislav Bauer 5 | */ 6 | package com.github.vbauer.caesar.runner; 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.task; 2 | 3 | import com.github.vbauer.caesar.callback.AsyncCallback; 4 | 5 | import java.lang.reflect.Method; 6 | import java.util.concurrent.Callable; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | * @param result type 11 | */ 12 | 13 | public class AsyncCallbackTask implements Callable { 14 | 15 | private final Object origin; 16 | private final Object[] args; 17 | private final Method syncMethod; 18 | private final AsyncCallback asyncCallback; 19 | 20 | 21 | public AsyncCallbackTask( 22 | final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback 23 | ) { 24 | this.origin = origin; 25 | this.args = args; 26 | this.syncMethod = syncMethod; 27 | this.asyncCallback = asyncCallback; 28 | } 29 | 30 | 31 | @SuppressWarnings("unchecked") 32 | public T call() { 33 | final Object result; 34 | 35 | try { 36 | result = syncMethod.invoke(origin, args); 37 | } catch (final Throwable ex) { 38 | asyncCallback.onFailure(ex.getCause()); 39 | return null; 40 | } 41 | 42 | asyncCallback.onSuccess(result); 43 | 44 | return (T) result; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/task/FutureCallbackTask.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.task; 2 | 3 | import com.google.common.util.concurrent.FutureCallback; 4 | 5 | import java.lang.reflect.Method; 6 | import java.util.concurrent.Callable; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | * @param result type 11 | */ 12 | 13 | public class FutureCallbackTask implements Callable { 14 | 15 | private final Object origin; 16 | private final Object[] args; 17 | private final Method syncMethod; 18 | private final FutureCallback futureCallback; 19 | 20 | 21 | public FutureCallbackTask( 22 | final Object origin, final Method syncMethod, final Object[] args, 23 | final FutureCallback futureCallback 24 | ) { 25 | this.origin = origin; 26 | this.args = args; 27 | this.syncMethod = syncMethod; 28 | this.futureCallback = futureCallback; 29 | } 30 | 31 | 32 | @SuppressWarnings("unchecked") 33 | public T call() { 34 | final Object result; 35 | 36 | try { 37 | result = syncMethod.invoke(origin, args); 38 | } catch (final Throwable ex) { 39 | futureCallback.onFailure(ex.getCause()); 40 | return null; 41 | } 42 | 43 | futureCallback.onSuccess(result); 44 | 45 | return (T) result; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/task/SimpleInvokeTask.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.task; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.concurrent.Callable; 5 | 6 | /** 7 | * @author Vladislav Bauer 8 | * @param result type 9 | */ 10 | 11 | public class SimpleInvokeTask implements Callable { 12 | 13 | private final Method syncMethod; 14 | private final Object[] args; 15 | private final Object origin; 16 | 17 | 18 | public SimpleInvokeTask(final Object origin, final Method syncMethod, final Object[] args) { 19 | this.syncMethod = syncMethod; 20 | this.args = args; 21 | this.origin = origin; 22 | } 23 | 24 | 25 | @SuppressWarnings("unchecked") 26 | public T call() throws Exception { 27 | return (T) syncMethod.invoke(origin, args); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/runner/task/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Callable-classes for execution service to make invocation of sync-methods. 3 | * 4 | * @author Vladislav Bauer 5 | */ 6 | package com.github.vbauer.caesar.runner.task; 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.util; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Method; 5 | import java.util.ArrayList; 6 | import java.util.Collection; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | @SuppressWarnings("unchecked") 14 | public final class ReflectionUtils { 15 | 16 | public static final String PACKAGE_SEPARATOR = "."; 17 | 18 | 19 | private ReflectionUtils() { 20 | throw new UnsupportedOperationException(); 21 | } 22 | 23 | 24 | public static Class getClassWithoutProxies(final Object object) { 25 | try { 26 | // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. 27 | return (Class) Class.forName("org.hibernate.proxy.HibernateProxyHelper") 28 | .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) 29 | .invoke(null, object); 30 | } catch (final Exception ex) { 31 | return getClassSafe(object); 32 | } 33 | } 34 | 35 | public static Class getClassSafe(final Object object) { 36 | return object != null ? (Class) object.getClass() : null; 37 | } 38 | 39 | public static T createObject(final String className) { 40 | try { 41 | final Class clazz = Class.forName(className); 42 | return (T) clazz.newInstance(); 43 | } catch (final Throwable ex) { 44 | return null; 45 | } 46 | } 47 | 48 | public static Collection createObjects(final Collection classNames) { 49 | final List objects = new ArrayList<>(); 50 | for (final String className : classNames) { 51 | final T object = createObject(className); 52 | if (object != null) { 53 | objects.add(object); 54 | } 55 | } 56 | return objects; 57 | } 58 | 59 | public static Collection classNames(final String packageName, final Collection classNames) { 60 | final List result = new ArrayList<>(); 61 | for (final String className : classNames) { 62 | result.add(packageName + PACKAGE_SEPARATOR + className); 63 | } 64 | return result; 65 | } 66 | 67 | public static Method findDeclaredMethod( 68 | final Class objectClass, final String methodName, final Class[] parameterTypes 69 | ) { 70 | try { 71 | return objectClass.getDeclaredMethod(methodName, parameterTypes); 72 | } catch (final Throwable ignored) { 73 | return null; 74 | } 75 | } 76 | 77 | public static T findAnnotationFromMethodOrClass( 78 | final Method method, final Class annotationClass 79 | ) { 80 | final T annotation = method.getAnnotation(annotationClass); 81 | if (annotation != null) { 82 | return annotation; 83 | } 84 | 85 | final Class originClass = method.getDeclaringClass(); 86 | return originClass.getAnnotation(annotationClass); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/github/vbauer/caesar/util/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Package with utility classes (helpers). 3 | * 4 | * @author Vladislav Bauer 5 | */ 6 | package com.github.vbauer.caesar.util; 7 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.annotation; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import com.github.vbauer.caesar.bean.SimpleAsync; 5 | import com.github.vbauer.caesar.bean.SimpleSync; 6 | import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; 7 | import com.github.vbauer.caesar.proxy.AsyncProxyCreator; 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | 11 | import java.util.concurrent.ExecutorService; 12 | import java.util.concurrent.Executors; 13 | 14 | /** 15 | * @author Vladislav Bauer 16 | */ 17 | 18 | public class TimeoutAnnotationTest extends BasicTest { 19 | 20 | @Test 21 | public void testGoodExecutorService() throws Exception { 22 | final ExecutorService executor = Executors.newScheduledThreadPool(1); 23 | try { 24 | final SimpleAsync proxy = createProxy(executor); 25 | Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get()); 26 | } finally { 27 | executor.shutdown(); 28 | } 29 | } 30 | 31 | @Test(expected = UnsupportedTimeoutException.class) 32 | public void testBadExecutorService() throws Exception { 33 | final ExecutorService executor = Executors.newFixedThreadPool(1); 34 | try { 35 | final SimpleAsync proxy = createProxy(executor); 36 | Assert.fail(String.valueOf(proxy.timeout().get())); 37 | } finally { 38 | executor.shutdown(); 39 | } 40 | } 41 | 42 | private SimpleAsync createProxy(final ExecutorService executor) { 43 | final SimpleSync bean = new SimpleSync(1); 44 | return AsyncProxyCreator.create(bean, SimpleAsync.class, executor); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.basic; 2 | 3 | import com.github.vbauer.caesar.bean.CallbackAsync; 4 | import com.github.vbauer.caesar.bean.FutureAsync; 5 | import com.github.vbauer.caesar.bean.FutureCallbackAsync; 6 | import com.github.vbauer.caesar.bean.ListenableFutureAsync; 7 | import com.github.vbauer.caesar.bean.ObservableAsync; 8 | import com.github.vbauer.caesar.bean.Sync; 9 | import com.github.vbauer.caesar.proxy.AsyncProxyCreator; 10 | import org.junit.After; 11 | import org.junit.Before; 12 | 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.Executors; 15 | 16 | /** 17 | * @author Vladislav Bauer 18 | */ 19 | 20 | public abstract class BasicRunnerTest extends BasicTest { 21 | 22 | protected static final String PARAMETER = "World"; 23 | 24 | private final ThreadLocal executorServiceHolder = new ThreadLocal<>(); 25 | private final ThreadLocal syncBeanHolder = new ThreadLocal<>(); 26 | private final ThreadLocal callbackAsyncHolder = new ThreadLocal<>(); 27 | private final ThreadLocal futureCallbackAsyncHolder = new ThreadLocal<>(); 28 | private final ThreadLocal futureAsyncHolder = new ThreadLocal<>(); 29 | private final ThreadLocal listenableFutureAsyncHolder = new ThreadLocal<>(); 30 | private final ThreadLocal observableAsyncHolder = new ThreadLocal<>(); 31 | 32 | @Before 33 | public final void before() { 34 | final ExecutorService executor = Executors.newScheduledThreadPool(5); 35 | final Sync sync = new Sync(); 36 | final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); 37 | final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); 38 | final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); 39 | final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); 40 | final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); 41 | 42 | executorServiceHolder.set(executor); 43 | syncBeanHolder.set(sync); 44 | callbackAsyncHolder.set(callbackAsync); 45 | futureCallbackAsyncHolder.set(futureCallbackAsync); 46 | futureAsyncHolder.set(futureAsync); 47 | listenableFutureAsyncHolder.set(listenableFutureAsync); 48 | observableAsyncHolder.set(observableAsync); 49 | } 50 | 51 | @After 52 | public final void after() { 53 | getExecutorService().shutdown(); 54 | executorServiceHolder.remove(); 55 | syncBeanHolder.remove(); 56 | callbackAsyncHolder.remove(); 57 | futureCallbackAsyncHolder.remove(); 58 | futureAsyncHolder.remove(); 59 | listenableFutureAsyncHolder.remove(); 60 | observableAsyncHolder.remove(); 61 | } 62 | 63 | 64 | protected ExecutorService getExecutorService() { 65 | return executorServiceHolder.get(); 66 | } 67 | 68 | protected Sync getSync() { 69 | return syncBeanHolder.get(); 70 | } 71 | 72 | protected CallbackAsync getCallbackAsync() { 73 | return callbackAsyncHolder.get(); 74 | } 75 | 76 | protected FutureCallbackAsync getFutureCallbackAsync() { 77 | return futureCallbackAsyncHolder.get(); 78 | } 79 | 80 | protected FutureAsync getFutureAsync() { 81 | return futureAsyncHolder.get(); 82 | } 83 | 84 | protected ListenableFutureAsync getListenableFutureAsync() { 85 | return listenableFutureAsyncHolder.get(); 86 | } 87 | 88 | protected ObservableAsync getObservableAsync() { 89 | return observableAsyncHolder.get(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/basic/BasicTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.basic; 2 | 3 | import com.pushtorefresh.private_constructor_checker.PrivateConstructorChecker; 4 | import org.junit.Assert; 5 | import org.junit.runner.RunWith; 6 | import org.junit.runners.BlockJUnit4ClassRunner; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | @RunWith(BlockJUnit4ClassRunner.class) 13 | public abstract class BasicTest { 14 | 15 | protected final boolean checkUtilConstructorContract(final Class... utilClasses) { 16 | Assert.assertTrue(utilClasses.length > 0); 17 | 18 | PrivateConstructorChecker 19 | .forClasses(utilClasses) 20 | .expectedTypeOfException(UnsupportedOperationException.class) 21 | .check(); 22 | 23 | return true; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | import com.github.vbauer.caesar.callback.AsyncCallback; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface CallbackAsync { 13 | 14 | void hello(AsyncCallback callback, String name1, String name2); 15 | 16 | void hello(AsyncCallback callback, String name); 17 | 18 | void emptyHello(AsyncCallback callback, String name); 19 | 20 | void empty(AsyncCallback callback); 21 | 22 | void exception(AsyncCallback callback); 23 | 24 | void methodWithoutSyncImpl(AsyncCallback callback); 25 | 26 | @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) 27 | void timeout(AsyncCallback callback); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/FutureAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | 5 | import java.util.concurrent.Future; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface FutureAsync { 13 | 14 | Future hello(String name1, String name2); 15 | 16 | Future hello(String name); 17 | 18 | Future emptyHello(String name); 19 | 20 | Future empty(); 21 | 22 | Future exception(); 23 | 24 | Future methodWithoutSyncImpl(); 25 | 26 | @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) 27 | Future timeout(); 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/FutureCallbackAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | import com.google.common.util.concurrent.FutureCallback; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface FutureCallbackAsync { 13 | 14 | void hello(FutureCallback callback, String name1, String name2); 15 | 16 | void hello(FutureCallback callback, String name); 17 | 18 | void emptyHello(FutureCallback callback, String name); 19 | 20 | void empty(FutureCallback callback); 21 | 22 | void exception(FutureCallback callback); 23 | 24 | void methodWithoutSyncImpl(FutureCallback callback); 25 | 26 | @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) 27 | void timeout(FutureCallback callback); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/ListenableFutureAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | import com.google.common.util.concurrent.ListenableFuture; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface ListenableFutureAsync { 13 | 14 | ListenableFuture hello(String name1, String name2); 15 | 16 | ListenableFuture hello(String name); 17 | 18 | ListenableFuture emptyHello(String name); 19 | 20 | ListenableFuture empty(); 21 | 22 | ListenableFuture exception(); 23 | 24 | ListenableFuture methodWithoutSyncImpl(); 25 | 26 | @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) 27 | ListenableFuture timeout(); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/ObservableAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | import rx.Observable; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Vladislav Bauer 10 | */ 11 | 12 | public interface ObservableAsync { 13 | 14 | Observable hello(String name1, String name2); 15 | 16 | Observable hello(String name); 17 | 18 | Observable emptyHello(String name); 19 | 20 | Observable empty(); 21 | 22 | Observable exception(); 23 | 24 | Observable methodWithoutSyncImpl(); 25 | 26 | @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) 27 | Observable timeout(); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | import com.github.vbauer.caesar.annotation.Timeout; 4 | 5 | import java.util.concurrent.Future; 6 | 7 | /** 8 | * @author Vladislav Bauer 9 | */ 10 | 11 | @Timeout(5) 12 | public interface SimpleAsync { 13 | 14 | Future getId(); 15 | 16 | Future timeout(); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | /** 4 | * @author Vladislav Bauer 5 | */ 6 | 7 | public class SimpleSync { 8 | 9 | public static final boolean TIMEOUT_VALUE = true; 10 | private final int id; 11 | 12 | 13 | public SimpleSync(final int id) { 14 | this.id = id; 15 | } 16 | 17 | 18 | public int getId() { 19 | return id; 20 | } 21 | 22 | public Boolean timeout() throws InterruptedException { 23 | Thread.sleep(1000); 24 | return TIMEOUT_VALUE; 25 | } 26 | 27 | 28 | @Override 29 | public int hashCode() { 30 | return id; 31 | } 32 | 33 | @Override 34 | public boolean equals(final Object obj) { 35 | if (obj instanceof SimpleSync) { 36 | final SimpleSync other = (SimpleSync) obj; 37 | return other.getId() == getId(); 38 | } 39 | return false; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return String.valueOf(getId()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/bean/Sync.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.bean; 2 | 3 | /** 4 | * @author Vladislav Bauer 5 | */ 6 | 7 | public class Sync { 8 | 9 | public String hello(final String name) { 10 | return String.format("Hello, %s", name); 11 | } 12 | 13 | public String hello(final String name1, final String name2) { 14 | return String.format("Hello, %s and %s", name1, name2); 15 | } 16 | 17 | public void empty() { 18 | // Do nothing. 19 | } 20 | 21 | public void emptyHello(@SuppressWarnings("unused") final String name) { 22 | // Do nothing. 23 | } 24 | 25 | public void exception() { 26 | throw new UnsupportedOperationException(); 27 | } 28 | 29 | public Boolean timeout() throws InterruptedException { 30 | Thread.sleep(1000); 31 | return true; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapterTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.callback; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import java.util.concurrent.atomic.AtomicBoolean; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | public class AsyncCallbackAdapterTest extends BasicTest { 14 | 15 | @Test 16 | public void testCallback() { 17 | final AtomicBoolean onSuccess = new AtomicBoolean(false); 18 | final AtomicBoolean onFailure = new AtomicBoolean(false); 19 | 20 | final AsyncCallbackAdapter callback = new AsyncCallbackAdapter() { 21 | @Override 22 | public void onSuccess(final Object result) { 23 | super.onSuccess(result); 24 | onSuccess.set(true); 25 | } 26 | 27 | @Override 28 | public void onFailure(final Throwable caught) { 29 | super.onFailure(caught); 30 | onFailure.set(true); 31 | } 32 | }; 33 | 34 | callback.onSuccess(null); 35 | callback.onFailure(null); 36 | 37 | Assert.assertTrue(onSuccess.get()); 38 | Assert.assertTrue(onFailure.get()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/callback/FutureCallbackAdapterTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.callback; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import java.util.concurrent.atomic.AtomicBoolean; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | public class FutureCallbackAdapterTest extends BasicTest { 14 | 15 | @Test 16 | public void testCallback() { 17 | final AtomicBoolean onSuccess = new AtomicBoolean(false); 18 | final AtomicBoolean onFailure = new AtomicBoolean(false); 19 | 20 | final FutureCallbackAdapter callback = new FutureCallbackAdapter() { 21 | @Override 22 | public void onSuccess(final Object result) { 23 | super.onSuccess(result); 24 | onSuccess.set(true); 25 | } 26 | 27 | @Override 28 | public void onFailure(final Throwable caught) { 29 | super.onFailure(caught); 30 | onFailure.set(true); 31 | } 32 | }; 33 | 34 | callback.onSuccess(null); 35 | callback.onFailure(null); 36 | 37 | Assert.assertTrue(onSuccess.get()); 38 | Assert.assertTrue(onFailure.get()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/exception/CaesarExceptionTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.exception; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import java.lang.reflect.Modifier; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | public class CaesarExceptionTest extends BasicTest { 14 | 15 | @Test(expected = RuntimeException.class) 16 | public void testAbstractCaesarException() { 17 | final Class clazz = AbstractCaesarException.class; 18 | final int modifiers = clazz.getModifiers(); 19 | Assert.assertTrue(Modifier.isAbstract(modifiers)); 20 | 21 | final AbstractCaesarException ex = new AbstractCaesarException() {}; 22 | checkCommon(ex, RuntimeException.class); 23 | } 24 | 25 | @Test(expected = AbstractCaesarException.class) 26 | public void testMissedSyncMethodException() { 27 | final MissedSyncMethodException ex = new MissedSyncMethodException(null); 28 | Assert.assertEquals(0, ex.getArguments().length); 29 | Assert.assertNull(ex.getMethod()); 30 | checkCommon(ex, AbstractCaesarException.class); 31 | } 32 | 33 | @Test(expected = AbstractCaesarException.class) 34 | public void testUnsupportedTimeoutException() { 35 | final UnsupportedTimeoutException ex = new UnsupportedTimeoutException(null); 36 | Assert.assertNull(ex.getExecutor()); 37 | checkCommon(ex, AbstractCaesarException.class); 38 | } 39 | 40 | 41 | private void checkCommon(final RuntimeException ex, final Class parentClass) { 42 | Assert.assertFalse(ex.getMessage().isEmpty()); 43 | Assert.assertTrue(parentClass.isAssignableFrom(ex.getClass().getSuperclass())); 44 | throw ex; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.proxy; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import com.github.vbauer.caesar.bean.CallbackAsync; 5 | import com.github.vbauer.caesar.bean.SimpleAsync; 6 | import com.github.vbauer.caesar.bean.SimpleSync; 7 | import com.github.vbauer.caesar.bean.Sync; 8 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 9 | import org.junit.AfterClass; 10 | import org.junit.Assert; 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | 14 | import java.util.List; 15 | import java.util.concurrent.ExecutorService; 16 | import java.util.concurrent.Executors; 17 | 18 | /** 19 | * @author Vladislav Bauer 20 | */ 21 | 22 | public class AsyncProxyCreatorTest extends BasicTest { 23 | 24 | private static final ThreadLocal EXECUTOR = new ThreadLocal<>(); 25 | 26 | 27 | @BeforeClass 28 | public static void setUp() { 29 | EXECUTOR.set(Executors.newScheduledThreadPool(5)); 30 | } 31 | 32 | @AfterClass 33 | public static void tearDown() { 34 | executor().shutdown(); 35 | } 36 | 37 | @Test 38 | public void testConstructorContract() { 39 | Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); 40 | } 41 | 42 | @Test(expected = MissedSyncMethodException.class) 43 | public void testIncorrectProxy() { 44 | Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); 45 | } 46 | 47 | @Test(expected = MissedSyncMethodException.class) 48 | public void testBadProxy() { 49 | Assert.fail(String.valueOf( 50 | AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor()) 51 | )); 52 | } 53 | 54 | @Test 55 | public void testCorrectProxy() throws Throwable { 56 | final SimpleSync bean1 = new SimpleSync(1); 57 | final SimpleAsync proxy1 = AsyncProxyCreator.create(bean1, SimpleAsync.class, executor()); 58 | Assert.assertNotNull(proxy1); 59 | Assert.assertEquals(bean1.getId(), (int) proxy1.getId().get()); 60 | 61 | final SimpleSync bean2 = new SimpleSync(2); 62 | final SimpleAsync proxy2 = AsyncProxyCreator.create(bean2, SimpleAsync.class, executor()); 63 | Assert.assertNotNull(proxy2); 64 | Assert.assertEquals(bean2.getId(), (int) proxy2.getId().get()); 65 | 66 | Assert.assertNotEquals(proxy1, proxy2); 67 | Assert.assertNotEquals(proxy1.hashCode(), proxy2.hashCode()); 68 | Assert.assertNotEquals(proxy1.toString(), proxy2.toString()); 69 | Assert.assertNotNull(proxy1.toString()); 70 | } 71 | 72 | 73 | private static ExecutorService executor() { 74 | return EXECUTOR.get(); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | 7 | import java.util.Collection; 8 | 9 | /** 10 | * @author Vladislav Bauer 11 | */ 12 | 13 | public class AsyncMethodRunnerFactoryTest extends BasicTest { 14 | 15 | @Test 16 | public void testConstructorContract() { 17 | Assert.assertTrue(checkUtilConstructorContract(AsyncMethodRunnerFactory.class)); 18 | } 19 | 20 | @Test 21 | public void testCreateMethodRunners() { 22 | final int runnersCount = AsyncMethodRunnerFactory.CLASS_NAMES.size(); 23 | final Collection methodRunners = 24 | AsyncMethodRunnerFactory.createMethodRunners(); 25 | 26 | Assert.assertEquals(runnersCount, methodRunners.size()); 27 | for (final AsyncMethodRunner methodRunner : methodRunners) { 28 | Assert.assertNotNull(methodRunner); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.basic.BasicRunnerTest; 4 | import com.github.vbauer.caesar.callback.AsyncCallback; 5 | import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; 6 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.util.concurrent.Semaphore; 11 | import java.util.concurrent.atomic.AtomicReference; 12 | import java.util.function.Consumer; 13 | 14 | /** 15 | * @author Vladislav Bauer 16 | */ 17 | 18 | public class AsyncCallbackMethodRunnerTest extends BasicRunnerTest { 19 | 20 | @Test 21 | public void testTimeout() throws Throwable { 22 | check( 23 | callback -> getCallbackAsync().timeout(callback), 24 | new AsyncCallback() { 25 | @Override 26 | public void onSuccess(final Boolean result) { 27 | Assert.fail(); 28 | } 29 | @Override 30 | public void onFailure(final Throwable caught) { 31 | Assert.assertNull(caught); 32 | } 33 | }, 34 | false 35 | ); 36 | } 37 | 38 | @Test 39 | public void testWithoutResult() throws Throwable { 40 | Assert.assertTrue( 41 | check( 42 | callback -> getCallbackAsync().empty(callback), 43 | notNullResultCallback(), 44 | true 45 | ) 46 | ); 47 | } 48 | 49 | @Test 50 | public void test1ArgumentWithoutResult() throws Throwable { 51 | Assert.assertTrue( 52 | check( 53 | callback -> getCallbackAsync().emptyHello(callback, PARAMETER), 54 | notNullResultCallback(), 55 | true 56 | ) 57 | ); 58 | } 59 | 60 | @Test 61 | public void test1ArgumentWithResult() throws Throwable { 62 | Assert.assertTrue( 63 | check( 64 | callback -> getCallbackAsync().hello(callback, PARAMETER), 65 | new AsyncCallbackAdapter() { 66 | @Override 67 | public void onSuccess(final String result) { 68 | Assert.assertEquals(getSync().hello(PARAMETER), result); 69 | } 70 | }, 71 | true 72 | ) 73 | ); 74 | } 75 | 76 | @Test 77 | public void test2ArgumentsWithResult() throws Throwable { 78 | Assert.assertTrue( 79 | check( 80 | callback -> getCallbackAsync().hello(callback, PARAMETER, PARAMETER), 81 | new AsyncCallbackAdapter() { 82 | @Override 83 | public void onSuccess(final String result) { 84 | Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); 85 | } 86 | }, 87 | true 88 | ) 89 | ); 90 | } 91 | 92 | @Test(expected = UnsupportedOperationException.class) 93 | public void testException() throws Throwable { 94 | Assert.assertTrue( 95 | check( 96 | callback -> getCallbackAsync().exception(callback), 97 | new AsyncCallbackAdapter(), 98 | true 99 | ) 100 | ); 101 | } 102 | 103 | @Test(expected = MissedSyncMethodException.class) 104 | public void testIncorrectProxyOnDemand() { 105 | getCallbackAsync().methodWithoutSyncImpl(new AsyncCallbackAdapter<>()); 106 | Assert.fail(); 107 | } 108 | 109 | 110 | private boolean check( 111 | final Consumer> operation, final AsyncCallback callback, 112 | final boolean failOnError 113 | ) throws Throwable { 114 | final AtomicReference error = new AtomicReference<>(); 115 | final Semaphore semaphore = new Semaphore(1, true); 116 | semaphore.acquire(); 117 | 118 | final AsyncCallback semaphoreCallback = new AsyncCallback() { 119 | public void onSuccess(final T result) { 120 | try { 121 | callback.onSuccess(result); 122 | } finally { 123 | semaphore.release(); 124 | } 125 | } 126 | 127 | public void onFailure(final Throwable caught) { 128 | try { 129 | error.set(caught); 130 | callback.onFailure(caught); 131 | } finally { 132 | semaphore.release(); 133 | } 134 | } 135 | }; 136 | 137 | operation.accept(semaphoreCallback); 138 | semaphore.acquire(); 139 | 140 | if (failOnError) { 141 | final Throwable throwable = error.get(); 142 | if (throwable != null) { 143 | throw throwable; 144 | } 145 | } 146 | 147 | return true; 148 | } 149 | 150 | private AsyncCallbackAdapter notNullResultCallback() { 151 | return new AsyncCallbackAdapter() { 152 | @Override 153 | public void onSuccess(final Void result) { 154 | Assert.assertNull(result); 155 | } 156 | }; 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.basic.BasicRunnerTest; 4 | import com.github.vbauer.caesar.callback.FutureCallbackAdapter; 5 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 6 | import com.google.common.util.concurrent.FutureCallback; 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.util.concurrent.Semaphore; 11 | import java.util.concurrent.atomic.AtomicReference; 12 | import java.util.function.Consumer; 13 | 14 | /** 15 | * @author Vladislav Bauer 16 | */ 17 | 18 | public class FutureCallbackMethodRunnerTest extends BasicRunnerTest { 19 | 20 | @Test 21 | public void testTimeout() throws Throwable { 22 | Assert.assertTrue( 23 | check( 24 | callback -> getFutureCallbackAsync().timeout(callback), 25 | new FutureCallback() { 26 | @Override 27 | public void onSuccess(final Boolean result) { 28 | Assert.fail(); 29 | } 30 | @Override 31 | public void onFailure(final Throwable t) { 32 | Assert.assertNotNull(t); 33 | } 34 | }, 35 | false 36 | ) 37 | ); 38 | } 39 | 40 | @Test 41 | public void testWithoutResult() throws Throwable { 42 | Assert.assertTrue(check(callback -> getFutureCallbackAsync().empty(callback), notNullResultCallback(), true)); 43 | } 44 | 45 | @Test 46 | public void test1ArgumentWithoutResult() throws Throwable { 47 | Assert.assertTrue( 48 | check(callback -> getFutureCallbackAsync().emptyHello(callback, PARAMETER), notNullResultCallback(), true) 49 | ); 50 | } 51 | 52 | @Test 53 | public void test1ArgumentWithResult() throws Throwable { 54 | Assert.assertTrue( 55 | check( 56 | callback -> getFutureCallbackAsync().hello(callback, PARAMETER), 57 | new FutureCallbackAdapter() { 58 | @Override 59 | public void onSuccess(final String result) { 60 | Assert.assertEquals(getSync().hello(PARAMETER), result); 61 | } 62 | }, 63 | true 64 | ) 65 | ); 66 | } 67 | 68 | @Test 69 | public void test2ArgumentsWithResult() throws Throwable { 70 | Assert.assertTrue( 71 | check( 72 | callback -> getFutureCallbackAsync().hello(callback, PARAMETER, PARAMETER), 73 | new FutureCallbackAdapter() { 74 | @Override 75 | public void onSuccess(final String result) { 76 | Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); 77 | } 78 | }, 79 | true 80 | ) 81 | ); 82 | } 83 | 84 | @Test(expected = UnsupportedOperationException.class) 85 | public void testException() throws Throwable { 86 | Assert.assertTrue( 87 | check(callback -> getFutureCallbackAsync().exception(callback), new FutureCallbackAdapter(), true) 88 | ); 89 | } 90 | 91 | @Test(expected = MissedSyncMethodException.class) 92 | public void testIncorrectProxyOnDemand() { 93 | getFutureCallbackAsync().methodWithoutSyncImpl(new FutureCallbackAdapter<>()); 94 | Assert.fail(); 95 | } 96 | 97 | 98 | private boolean check( 99 | final Consumer> operation, final FutureCallback callback, 100 | final boolean failOnError 101 | ) throws Throwable { 102 | final AtomicReference error = new AtomicReference<>(); 103 | final Semaphore semaphore = new Semaphore(1, true); 104 | semaphore.acquire(); 105 | 106 | final FutureCallback semaphoreCallback = new FutureCallback() { 107 | public void onSuccess(final T result) { 108 | try { 109 | callback.onSuccess(result); 110 | } finally { 111 | semaphore.release(); 112 | } 113 | } 114 | 115 | public void onFailure(final Throwable caught) { 116 | try { 117 | error.set(caught); 118 | callback.onFailure(caught); 119 | } finally { 120 | semaphore.release(); 121 | } 122 | } 123 | }; 124 | 125 | operation.accept(semaphoreCallback); 126 | semaphore.acquire(); 127 | 128 | if (failOnError) { 129 | final Throwable throwable = error.get(); 130 | if (throwable != null) { 131 | throw throwable; 132 | } 133 | } 134 | 135 | return true; 136 | } 137 | 138 | private FutureCallbackAdapter notNullResultCallback() { 139 | return new FutureCallbackAdapter() { 140 | @Override 141 | public void onSuccess(final Void result) { 142 | Assert.assertNull(result); 143 | } 144 | }; 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.basic.BasicRunnerTest; 4 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | import java.util.concurrent.CancellationException; 9 | import java.util.concurrent.ExecutionException; 10 | import java.util.concurrent.Future; 11 | 12 | /** 13 | * @author Vladislav Bauer 14 | */ 15 | 16 | public class FutureMethodRunnerTest extends BasicRunnerTest { 17 | 18 | @Test(expected = CancellationException.class) 19 | public void testTimeout() throws Throwable { 20 | final Future future = getFutureAsync().timeout(); 21 | Assert.assertNotNull(future); 22 | Assert.fail(String.valueOf(future.get())); 23 | } 24 | 25 | @Test 26 | public void testWithoutResult() throws Throwable { 27 | getSync().empty(); 28 | 29 | final Future future = getFutureAsync().empty(); 30 | Assert.assertNotNull(future); 31 | Assert.assertNull(future.get()); 32 | } 33 | 34 | @Test 35 | public void test1ArgumentWithoutResult() throws Throwable { 36 | getSync().emptyHello(PARAMETER); 37 | 38 | final Future future = getFutureAsync().emptyHello(PARAMETER); 39 | Assert.assertNotNull(future); 40 | Assert.assertNull(future.get()); 41 | } 42 | 43 | @Test 44 | public void test1ArgumentWithResult() throws Throwable { 45 | Assert.assertEquals(getSync().hello(PARAMETER), getFutureAsync().hello(PARAMETER).get()); 46 | } 47 | 48 | @Test 49 | public void test2ArgumentsWithResult() throws Throwable { 50 | Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), getFutureAsync().hello(PARAMETER, PARAMETER).get()); 51 | } 52 | 53 | @Test(expected = ExecutionException.class) 54 | public void testException() throws Throwable { 55 | getFutureAsync().exception().get(); 56 | Assert.fail(); 57 | } 58 | 59 | @Test(expected = MissedSyncMethodException.class) 60 | public void testIncorrectProxyOnDemand() { 61 | Assert.fail(String.valueOf(getFutureAsync().methodWithoutSyncImpl())); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/impl/ListenableFutureMethodRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.basic.BasicRunnerTest; 4 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 5 | import com.google.common.util.concurrent.ListenableFuture; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import java.util.concurrent.CancellationException; 10 | import java.util.concurrent.ExecutionException; 11 | 12 | /** 13 | * @author Vladislav Bauer 14 | */ 15 | 16 | public class ListenableFutureMethodRunnerTest extends BasicRunnerTest { 17 | 18 | @Test(expected = CancellationException.class) 19 | public void testTimeout() throws Throwable { 20 | final ListenableFuture future = getListenableFutureAsync().timeout(); 21 | Assert.assertNotNull(future); 22 | Assert.fail(String.valueOf(future.get())); 23 | } 24 | 25 | @Test 26 | public void testWithoutResult() throws Throwable { 27 | getSync().empty(); 28 | 29 | final ListenableFuture future = getListenableFutureAsync().empty(); 30 | Assert.assertNotNull(future); 31 | Assert.assertNull(future.get()); 32 | } 33 | 34 | @Test 35 | public void test1ArgumentWithoutResult() throws Throwable { 36 | getSync().emptyHello(PARAMETER); 37 | 38 | final ListenableFuture future = getListenableFutureAsync().emptyHello(PARAMETER); 39 | Assert.assertNotNull(future); 40 | Assert.assertNull(future.get()); 41 | } 42 | 43 | @Test 44 | public void test1ArgumentWithResult() throws Throwable { 45 | Assert.assertEquals( 46 | getSync().hello(PARAMETER), 47 | getListenableFutureAsync().hello(PARAMETER).get() 48 | ); 49 | } 50 | 51 | @Test 52 | public void test2ArgumentsWithResult() throws Throwable { 53 | Assert.assertEquals( 54 | getSync().hello(PARAMETER, PARAMETER), 55 | getListenableFutureAsync().hello(PARAMETER, PARAMETER).get() 56 | ); 57 | } 58 | 59 | @Test(expected = ExecutionException.class) 60 | public void testException() throws Throwable { 61 | getListenableFutureAsync().exception().get(); 62 | Assert.fail(); 63 | } 64 | 65 | @Test(expected = MissedSyncMethodException.class) 66 | public void testIncorrectProxyOnDemand() { 67 | Assert.fail(String.valueOf(getListenableFutureAsync().methodWithoutSyncImpl())); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/runner/impl/ObservableMethodRunnerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.runner.impl; 2 | 3 | import com.github.vbauer.caesar.basic.BasicRunnerTest; 4 | import com.github.vbauer.caesar.exception.MissedSyncMethodException; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | import rx.Observable; 8 | 9 | import java.util.concurrent.CancellationException; 10 | 11 | /** 12 | * @author Vladislav Bauer 13 | */ 14 | 15 | public class ObservableMethodRunnerTest extends BasicRunnerTest { 16 | 17 | @Test(expected = CancellationException.class) 18 | public void testTimeout() { 19 | final Observable observable = getObservableAsync().timeout(); 20 | Assert.assertNotNull(observable); 21 | Assert.fail(String.valueOf(observable.toBlocking().first())); 22 | } 23 | 24 | @Test 25 | public void testWithoutResult() { 26 | getSync().empty(); 27 | 28 | final Observable observable = getObservableAsync().empty(); 29 | Assert.assertNotNull(observable); 30 | Assert.assertNull(observable.toBlocking().first()); 31 | } 32 | 33 | @Test 34 | public void test1ArgumentWithoutResult() { 35 | getSync().emptyHello(PARAMETER); 36 | 37 | final Observable observable = getObservableAsync().emptyHello(PARAMETER); 38 | Assert.assertNotNull(observable); 39 | Assert.assertNull(observable.toBlocking().first()); 40 | } 41 | 42 | @Test 43 | public void test1ArgumentWithResult() { 44 | Assert.assertEquals( 45 | getSync().hello(PARAMETER), 46 | getObservableAsync().hello(PARAMETER).toBlocking().first() 47 | ); 48 | } 49 | 50 | @Test 51 | public void test2ArgumentsWithResult() { 52 | Assert.assertEquals( 53 | getSync().hello(PARAMETER, PARAMETER), 54 | getObservableAsync().hello(PARAMETER, PARAMETER).toBlocking().first() 55 | ); 56 | } 57 | 58 | @Test(expected = RuntimeException.class) 59 | public void testException() { 60 | getObservableAsync().exception().toBlocking().first(); 61 | Assert.fail(); 62 | } 63 | 64 | @Test(expected = MissedSyncMethodException.class) 65 | public void testIncorrectProxyOnDemand() { 66 | Assert.fail(String.valueOf(getObservableAsync().methodWithoutSyncImpl())); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/test/java/com/github/vbauer/caesar/util/ReflectionUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.github.vbauer.caesar.util; 2 | 3 | import com.github.vbauer.caesar.basic.BasicTest; 4 | import com.github.vbauer.caesar.runner.AsyncMethodRunnerFactory; 5 | import com.google.common.collect.Lists; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import java.util.Arrays; 10 | import java.util.Collection; 11 | import java.util.List; 12 | 13 | /** 14 | * @author Vladislav Bauer 15 | */ 16 | 17 | public class ReflectionUtilsTest extends BasicTest { 18 | 19 | private static final String CLASS_OBJECT = "java.lang.Object"; 20 | private static final String CLASS_STRING = "java.lang.String"; 21 | 22 | 23 | @Test 24 | public void testConstructorContract() { 25 | Assert.assertTrue(checkUtilConstructorContract(ReflectionUtils.class)); 26 | } 27 | 28 | @Test 29 | public void testCreateObject() { 30 | Assert.assertEquals( 31 | Object.class, 32 | ReflectionUtils.getClassSafe(ReflectionUtils.createObject(CLASS_OBJECT)) 33 | ); 34 | Assert.assertArrayEquals((Object[]) null, ReflectionUtils.createObject(null)); 35 | } 36 | 37 | @Test 38 | public void testCreateObjects() { 39 | final List objects = Lists.newArrayList( 40 | ReflectionUtils.createObjects( 41 | Arrays.asList(CLASS_OBJECT, CLASS_STRING) 42 | ) 43 | ); 44 | 45 | Assert.assertEquals(Object.class, objects.get(0).getClass()); 46 | Assert.assertEquals(String.class, objects.get(1).getClass()); 47 | Assert.assertEquals(2, objects.size()); 48 | } 49 | 50 | @Test 51 | public void testClassNames() { 52 | final String packageName = AsyncMethodRunnerFactory.PACKAGE_NAME; 53 | final List classNames = AsyncMethodRunnerFactory.CLASS_NAMES; 54 | final Collection result = 55 | ReflectionUtils.classNames(packageName, classNames); 56 | 57 | Assert.assertEquals(classNames.size(), result.size()); 58 | Assert.assertEquals( 59 | packageName + ReflectionUtils.PACKAGE_SEPARATOR + classNames.get(0), 60 | result.iterator().next() 61 | ); 62 | } 63 | 64 | @Test 65 | public void testGetClassSafe() { 66 | Assert.assertNull(ReflectionUtils.getClassSafe(null)); 67 | Assert.assertEquals( 68 | String.class, ReflectionUtils.getClassSafe(ReflectionUtils.PACKAGE_SEPARATOR) 69 | ); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/test/resources/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | --------------------------------------------------------------------------------