Caesar


Source link: https://github.com/vbauer/caesar

Caesar

I came, I saw, I conquered. - Julius Caesar

Caesar is a tiny Java library that allows to create an asynchronous proxy-version of some synchronous bean. It means that you can still think in terms of your service/bean/object and use its methods instead of writing concurrency code.

Use cases:

  • You have already got some 3-rd party library that works synchronously, but it is necessary to use it asynchronously.
  • You need to use both ways (sync & async) in different parts of your applications.

Caesar will help you to solve these problems.

Online documentation:

Main features:

Setup

Maven:

<repository>
  <id>jitpack.io</id>
  <url>https://jitpack.io</url> </repository>  <dependency>
  <groupId>com.github.vbauer</groupId>
  <artifactId>caesar</artifactId>
  <version>1.6.3</version> </dependency>

Gradle:

repositories {

  maven {

url "https://jitpack.io"
  
}
 
}
  dependencies {

  compile 'com.github.vbauer:caesar:1.6.3' 
}

Async-proxy creation

To make async-proxy for some bean, you need to use AsyncProxyCreator:

public static <SYNC, ASYNC> ASYNC create(
  final SYNC bean,
  final Class<ASYNC> asyncInterface,
  final ExecutorService executor,
  final boolean validate )

Parameters:

bean
Not-null object which will be wrapped by async-proxy.
asyncInterface
Class which represents async-proxy. See an example section for more details.
executor
Executor service for running background operations. The usual choice is `ThreadPoolExecutor`.
validate
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).

Mapping, Naming conventions

To make correct mapping between object and async-proxy, it is necessary to perform some conventions. Asynchronous proxy method signature must match the signature of the object method, except several points:

  • To use Future as result value, return class must be Future<T>
  • To use Guava:
    • return class should be ListenableFuture<T>
    • or add new parameter FutureCallback<T> at the first place of the method signature and change result type to void
  • To use RxJava, return class must be Observable<T>
  • To use AsyncCallback, you need to:
    • add new parameter AsyncCallback<T> at the first place of the method signature
    • change result type to void

If this conventions are not complied, than the corresponding sync-method with the same signature should be invoked. It will be still invoked in the separate thread to allow to use @Timeout annotation.

Example

Lets make an async-proxy for the following bean:

public class Sync {

public String hello(final String name) {

// Just a simple code for an example.

return String.format("Hello, %s", name);

  
}
  
}

First of all, we need to create an async-interface for this bean:

// IMPORTANT: It is just an example. Choose the most appropriate way for you. // All methods could not be presented at the same time in the real code. public interface Async {

// Future<T> will be the new return type.
  Future<String> hello(String name);

// Future<T> will be the new return type.
  ListenableFuture<String> hello(String name);

// Observable<T> will be also the new return type.
  Observable<String> hello(String name);

// AsyncCallback<T> should be added as the first parameter.
  void hello(AsyncCallback<String> callback, String name);

// FutureCallback<T> should be also added as the first parameter.
  void hello(FutureCallback<String> callback, String name);
  
}

After that we can create an async-proxy using AsyncProxyCreator:

final AsyncBean asyncBean = AsyncProxyCreator.create(
  new Sync(), Async.class, Executors.newFixedThreadPool(5));

That's all. Now you can use your bean asynchronously. All methods will be invoked in threads from thread pool.

// Retrieve result using Future: final Future future = asyncBean.hello("John");
 final String text = future.get();
 // text is "Hello, John"  // Retrieve result using ListenableFuture: final ListenableFuture listenableFuture = asyncBean.hello("George");
 final String text = listenableFuture.get();
 // text is "Hello, George"  // Retrieve result using RxJava and Observable: final Observable<String> observable = asyncBean.hello("Paul");
 final String text = observable.toBlocking().first();
 // text is "Hello, Paul"  // Retrieve result using custom callback: asyncBean.hello(new AsyncCallbackAdapter<String>() {

@Override

public void onSuccess(final String text) {

 // text is "Hello, Ringo"

}
 
}
, "Ringo");
  // Retrieve result using FutureCallback: asyncBean.hello(new FutureCallback<String>() {

  @Override
  public void onSuccess(final String text) {

// text is "Hello, guys"
  
}

  @Override
  public void onFailure(final Throwable t) {

// it will not be executed
  
}
 
}
, "guys");

@Timeout

Sometimes it is useful to setup timeout value to cancel operation (ex: REST API call which takes a lot of time). You can use @Timeout annotation to do it (cancel operation after 3 seconds):

public interface Async {

@Timeout(value = 3, unit = TimeUnit.SECONDS)
  Future<String> hello(String name);
 

It is also possible to configure timeouts for all methods of async-proxy putting annotation on class:

@Timeout(5000) public interface Async {

  Future<Long> foo1();

  Future<Long> foo2();
 
}

IMPORTANT: ScheduledExecutorService should be used to switch on this feature.

Development

To build project in strict mode with tests, you can use your local Maven:

mvn -P strict clean package

Might also like

  • jconditions - Extra conditional annotations for JUnit.
  • jackdaw - Java Annotation Processor which allows to simplify development.
  • houdini - Type conversion system for Spring framework.
  • herald - Logging annotation for Spring framework.
  • commons-vfs2-cifs - SMB/CIFS provider for Commons VFS.
  • avconv4java - Java interface to avconv tool.

License

Copyright 2015 Vladislav Bauer

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0 

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

See LICENSE file for details.

Resources

Template engine for java with statically checked and compiled templates. Compilation is performed alone with java sources.

This library implements Algebraic Data Types for Java. ADT4J provides annotation processor for @GenerateValueClassForVisitor annotation.

This library can help to configure strikethrough, color & blur on a part of text in TextView easily.

RxAnimations is a library with the main goal to make android animations more solid and cohesive.

Create square float action button using this example!

In this example we are creating an square floating action button which will be different from float action button, but will work the same

Are you creating a music app? Or maybe you want to add some creative detail to an existing one? Then you’ve come to the right place! Play Widget for Android created by Cleveroad can be easily integrated with your music app to spruce the user experience up. Break the monotony and make your music player unique!

New distinct things encourage users to launch your app again. Add the Play Widget component to your app and enjoy the benefits — it’s easy as one-two-three.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes