how to catch astyanax failures in asynchronous executions - java

The project I work on uses astyanax driver to access Cassandra. I want to implement an asynchronous operation:
MutationBatch m;
//…
ListenableFuture<OperationResult<Void>> lf = m.executeAsync();
lf.addListener(myRunnableCallback, myExecutor);
Question: assuming the exception was not thrown right away within executeAsync() call, how do I distinguish between successful and failed executions?
The only way I can think of is that when the completion callback is invoked lf.get() throws an exception in case of failure. If this is the right way, is there a document or lines in astyanax sources confirming that?

I found a workaround: instead of ListenableFuture's addListener method taking Runnable parameter I can use Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor). FutureCallback has 2 methods: onSuccess and onFailure. That solves my problem.
https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained

Related

IllegalStateException: The current thread cannot be blocked: vert.x-eventloop-thread-1

I am trying to use quarkus reactive api to fetch data from another hibernate reactive project.
I am getting this error whenever i try to get data from my hibernate project. I've figured that the error occurs in methods where i've called another method as well.the error i am getting
code for quarkus api
#GET
#Path("/getEquipCls")
public Uni<List<Tuple>> getMethod() {
return reactiveMethod();
}
code for service class of hibernate reactive method
#Override
public Uni<List<Tuple>> reactiveMethod(params) {
Long variable = methodForVariable.await().indefinitely();
return reactiveMethod(variable);
}
I've tried #Blocking & #NonBlocking annotations but none of them worked.
Any help would be greatly appreciated.
It seems there is a bit of misunderstanding, Reactive is not the same as Mutiny.
Returning Type Uni<> or Multi<> from your method is Mutiny. Which could be Reactive, but it's not always the case depending on what dependencies you added.
That said, I've seen that you call await().indefinitely(); which wait for result and then give the correct non Uni type.
Disclaimer: I'm not a Mutiny expert so i'll try to help as much as i can.
Maybe you should try with this :
return methodForVariable.onItem()
.transform(variable -> reactiveMethod(variable))
instead of this :
Long variable = methodForVariable.await().indefinitely();
return reactiveMethod(variable);
I think your blocking problem comes from here, where you try to block thread to wait for async processing, and then call an async method with previously fetched value.
The way i suggested always keep processing async, so it should do the trick.
For more, be sure to check Mutiny's documentation

How to manipulate the order of the Before-/AfterScenarios in JBehave?

In our project we are currently encountering multiple Before-/AfterScenarios, which all by definition get executed before/after every Scenario. However some of the methods are dependent on the execution of the others.
More precisely: A third party framework uses BeforeScenario in their code, that should always be executed before our BeforeScenario. JBehave has a way of prioritizing steps when it comes to chosing the correct step for execution.
#Then(value="the value returned is empty", priority=1)
public void theValueIsEmpty()
#Then("the value returned is $value")
public void theValueIs(String value)
Is there something similar for the Before-/AfterScenario annotation?
There is no way to order execution of #BeforeScenario/#AfterScenrio in JBehave. But you can try using new Lifecycle functionality:
Lifecycle:
Before:
Scope: SCENARIO
[steps to be executed before each scenario]
After:
Scope: SCENARIO
[steps to be executed after each scenario]
More details can be found in the official documentation: Lifecycle
Alternative approach: file a new JIRA ticket for Before/After prioritizing and implement it or wait for implementation from JBehave contributors.

Mockito: Expected exception in asynchronous callback

I'm creating a database wrapper. This wrapper has a series of states:
it is created
you are signing in
you are signed id
you are connected to a specific table
Methods on my database wrapper can trigger the state transitions.
But the database interactions are asynchronous, so you don't get immediate feedback. Instead, you can register as a listener for onStateChanged events.
I'm using mockito to test the transitions, and so far I'm really amazed at how clean the use of InOrder and verify are.
But now I'm running into a problem. I'm trying to test a forbidden transition. My Database wrapper will catch that you're not in the correct state and throw an AssertionException. This Exception let's the testing crash. I'm trying to register this as an expected exception with Mockito, but I can't figure out how to do this in the correct way.
The following code is all in one function, the exception is expected by JUnit:
#Test(expected = AssertionError.class)
public void cantCreateTwice() throws Exception{
...
First I'm creating a connection, and I'm setting up a StateChangeListener which attempts the forbidden transition:
final FirebaseConnection connection = new FirebaseConnection();
StateChangeListener stateChangeListener = new StateChangeListener() {
#Override
public void onStateChanged(DBState newState) {
if(newState==DBState.SignedIn){
connection.createParty();
connection.createParty(); // forbidden
}
}
};
Next, I'm registering this listener and a mock:
StateChangeListener mockedListener = mock(StateChangeListener.class);
connection.addStateChangeListener(stateChangeListener);
connection.addStateChangeListener(mockedListener);
Then I tell Mockito about the expected exception and start the test:
doThrow(new AssertionError()).when(mockedListener).onStateChanged(DBState.SignedIn);
connection.signIn();
verify(mockedListener, times(1)).onStateChanged(DBState.SigninIn);
verify(mockedListener, times(1)).onStateChanged(DBState.SignedIn);
This will result in:
Test running failed: Instrumentation run failed due to 'Process
crashed.'
The exception that crashed the process is the expected AssertionError:
java.lang.AssertionError: the connection is not in the necessary state
I think the problem is that my exception is not triggered when a function is called on the mocked listener, but on the anonymous implementation.
But I need the anonymous implementation to trigger the forbidden functionality.
I also need the verify since my callbacks are asynchronous. If I remove the verify then the test will simply return immediately without any exception being thrown.
It seems to me that I somehow need to convert my anonymous implementation into a Mock object that can be supervised by Mockito. But mock() doesn't work on anonymous classes. And I think it's not correct to have an individual class for every snippet of logic in my test cases.
How can I tell Mockito to expect this exception ?
EDIT:
I think I've found a way, I'm using verify with a timeout:
verify(mockedListener, timeout(1000).times(1)).onStateChanged(DBState.SigninIn);
verify(mockedListener, timeout(1000).times(1)).onStateChanged(DBState.SignedIn);
connection.createParty();
connection.createParty();
This blocks until the sign-in was completed. Then it tries to create a party twice, which fails and throws the expected exception.
But I think I'm now basically misusing a feature of Mockito for synchronization. Is this the correct way to use Mockito for my problem ?

RxJava Schedulers.immediate() behavior while Unit Testing

I am trying to write test for my DAO object that uses reactive interface. I have a table with recipes and I want to test that when I insert data to this table, the subscriber receives list with recipes.
I am using TestSubscriber class and performing asserts on that class. My simple test look like this:
#Test
fun testSubscriber() {
insertItem()
val testSubscriber = TestSubscriber.create<List<Recipe>>()
recipeDao
.getRecipes()
.subscribeOn(Schedulers.immediate())
.subscribe(testSubscriber)
testSubscriber.assertNoErrors()
testSubscriber.assertNoTerminalEvent()
testSubscriber.assertNotCompleted()
testSubscriber.assertValueCount(1)
assertEquals(1, testSubscriber.onNextEvents[0].size)
}
The problem is that assertion testSubscriber.assertValueCount(1) fails because no item was emitted. But when I insert this line above
testSubscriber.awaitTerminalEvent(500, TimeUnit.MILLISECONDS), the test is successful. My observable does not emit terminal event and therefore the timeout is performed, but in the meantime of waiting, the onNext was called with list of recipes.
My getRecipes method:
fun getRecipes(): Observable<List<Recipe>> {
return query(SELECT("*")
.FROM(Recipe.TABLE_NAME)
.ORDER_BY(Recipe.COL_NAME))
.run()
.mapToList(RecipeMapper.MAPPER)
}
How is that possible? I thought that when I use Schedulers.immediate(), the operation will be performed on the same thread and my TestSubscriber receives the events. If not, how should I write this test so it succeeds? I want to test that onNext is called and I don't want to insert artificial sleep commands between.
The problem was that I was using library SqlBrite with additional framework SqlBrite-Dao. SqlBrite is observing a query on specific Scheduler and when none was provided to DaoManager of SqlBrite-Dao, Schedulers.io() was used. The solution is to provide scheduler to DaoManager.Builder or apply RxJavaPlugins and return Schedulers.immediate() as all Schedulers.

Concept of promises in Java

Is there a concept of using promises in java (just like ut is used in JavaScript) instead of using nested callbacks ?
If so, is there an example of how the callback is implemented in java and handlers are chained ?
Yep! Java 8 calls it CompletableFuture. It lets you implement stuff like this.
class MyCompletableFuture<T> extends CompletableFuture<T> {
static final Executor myExecutor = ...;
public MyCompletableFuture() { }
public <U> CompletableFuture<U> newIncompleteFuture() {
return new MyCompletableFuture<U>();
}
public Executor defaultExecutor() {
return myExecutor;
}
public void obtrudeValue(T value) {
throw new UnsupportedOperationException();
}
public void obtrudeException(Throwable ex) {
throw new UnsupportedOperationException();
}
}
The basic design is a semi-fluent API in which you can arrange:
(sequential or async)
(functions or actions)
triggered on completion of
i) ("then") ,or ii) ("andThen" and "orThen")
others. As in:
MyCompletableFuture<String> f = ...; g = ...
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
or
f.andThen(g, (s, t) -> combineStrings).or(CompletableFuture.async(()->...)....
UPDATE 7/20/17
I wanted to edit that there is also a Library called "ReactFX" which is supposed to be JavaFX as a reactive framework. There are many Reactive Java libraries from what I've seen, and since Play is based on the Reactive principal, I would assume that these Reactive libraries follow that same principal of non-blocking i/o, async calls from server to client and back while having communication be send by either end.
These libraries seem to be made for the client side of things, but there might be a Server reactive library as well, but I would assume that it would be wiser to use Play! with one of these client side reactive libraries.
You can take a look at https://www.playframework.com/
which implements this functionality here
https://www.playframework.com/documentation/2.2.0/api/java/play/libs/F.Promise.html
Additonal reading https://www.playframework.com/documentation/2.5.x/JavaAsync
Creating non-blocking actions
Because of the way Play works, action code must be as fast as possible, i.e., non-blocking. So what should we return from our action if we are not yet able to compute the result? We should return the promise of a result!
Java 8 provides a generic promise API called CompletionStage. A CompletionStage<Result> will eventually be redeemed with a value of type Result. By using a CompletionStage<Result> instead of a normal Result, we are able to return from our action quickly without blocking anything. Play will then serve the result as soon as the promise is redeemed.
The web client will be blocked while waiting for the response, but nothing will be blocked on the server, and server resources can be used to serve other clients.
How to create a CompletionStage
To create a CompletionStage<Result> we need another promise first: the promise that will give us the actual value we need to compute the result:
CompletionStage<Double> promiseOfPIValue = computePIAsynchronously();
CompletionStage<Result> promiseOfResult = promiseOfPIValue.thenApply(pi ->
ok("PI value computed: " + pi)
);
Play asynchronous API methods give you a CompletionStage. This is the case when you are calling an external web service using the play.libs.WS API, or if you are using Akka to schedule asynchronous tasks or to communicate with Actors using play.libs.Akka.
A simple way to execute a block of code asynchronously and to get a CompletionStage is to use the CompletableFuture.supplyAsync() helper:
CompletionStage<Integer> promiseOfInt = CompletableFuture.supplyAsync(() -> intensiveComputation());
Note: It’s important to understand which thread code runs on which promises. Here, the intensive computation will just be run on another thread.
You can’t magically turn synchronous IO into asynchronous by wrapping it in a CompletionStage. If you can’t change the application’s architecture to avoid blocking operations, at some point that operation will have to be executed, and that thread is going to block. So in addition to enclosing the operation in a CompletionStage, it’s necessary to configure it to run in a separate execution context that has been configured with enough threads to deal with the expected concurrency. See Understanding Play thread pools for more information.
It can also be helpful to use Actors for blocking operations. Actors provide a clean model for handling timeouts and failures, setting up blocking execution contexts, and managing any state that may be associated with the service. Also Actors provide patterns like ScatterGatherFirstCompletedRouter to address simultaneous cache and database requests and allow remote execution on a cluster of backend servers. But an Actor may be overkill depending on what you need.
Async results
We have been returning Result up until now. To send an asynchronous result our action needs to return a CompletionStage<Result>:
public CompletionStage<Result> index() {
return CompletableFuture.supplyAsync(() -> intensiveComputation())
.thenApply(i -> ok("Got result: " + i));
}
Actions are asynchronous by default
Play actions are asynchronous by default. For instance, in the controller code below, the returned Result is internally enclosed in a promise:
public Result index() {
return ok("Got request " + request() + "!");
}
Note: Whether the action code returns a Result or a CompletionStage<Result>, both kinds of returned object are handled internally in the same way. There is a single kind of Action, which is asynchronous, and not two kinds (a synchronous one and an asynchronous one). Returning a CompletionStage is a technique for writing non-blocking code.
Some info on CompletionStage
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html
which is a subclass of the class mentioned in #Debosmit Ray's answer called CompletableFuture
This Youtube Video by LinkedIn dev Mr. Brikman explains a bit about Promises in
https://youtu.be/8z3h4Uv9YbE?t=15m46s
and
https://www.youtube.com/watch?v=4b1XLka0UIw
I believe the first video gives an example of a promise, the second video might also give some good info, I don't really recall which video had what content.
Either way the information here is very good, and worth looking into.
I personally do not use Play, but I have been looking at it for a long, long time, as it does a lot of really good stuff.
If you want to do Promise even before Java7, "java-promise" may be useful. (Of course it works with Java8)
You can easily control asynchronous operations like JavaScript's Promise.
https://github.com/riversun/java-promise
example
import org.riversun.promise.Promise;
public class Example {
public static void main(String[] args) {
Promise.resolve("foo")
.then(new Promise((action, data) -> {
new Thread(() -> {
String newData = data + "bar";
action.resolve(newData);
}).start();
}))
.then(new Promise((action, data) -> {
System.out.println(data);
action.resolve();
}))
.start();
System.out.println("Promise in Java");
}
}
result:
Promise in Java
foobar

Categories