use of java.util.concurrent.CompletionStage in project jersey by jersey.
the class CompletionStageAgentResource method recommended.
private CompletionStage<List<Recommendation>> recommended(final WebTarget destinationTarget, final ExecutorService executor, final Queue<String> errors) {
// Recommended places.
final CompletionStage<List<Destination>> recommended = destinationTarget.path("recommended").request().header("Rx-User", "CompletionStage").rx(executor).get(new GenericType<List<Destination>>() {
}).exceptionally(throwable -> {
errors.offer("Recommended: " + throwable.getMessage());
return Collections.emptyList();
});
return recommended.thenCompose(destinations -> {
final WebTarget finalForecast = forecastTarget;
final WebTarget finalCalculation = calculationTarget;
List<CompletionStage<Recommendation>> recommendations = destinations.stream().map(destination -> {
final CompletionStage<Forecast> forecast = finalForecast.resolveTemplate("destination", destination.getDestination()).request().rx(executor).get(Forecast.class).exceptionally(throwable -> {
errors.offer("Forecast: " + throwable.getMessage());
return new Forecast(destination.getDestination(), "N/A");
});
final CompletionStage<Calculation> calculation = finalCalculation.resolveTemplate("from", "Moon").resolveTemplate("to", destination.getDestination()).request().rx(executor).get(Calculation.class).exceptionally(throwable -> {
errors.offer("Calculation: " + throwable.getMessage());
return new Calculation("Moon", destination.getDestination(), -1);
});
return CompletableFuture.completedFuture(new Recommendation(destination)).thenCombine(forecast, Recommendation::forecast).thenCombine(calculation, Recommendation::calculation);
}).collect(Collectors.toList());
return sequence(recommendations);
});
}
use of java.util.concurrent.CompletionStage in project requery by requery.
the class CompletableEntityStoreTest method testInsertOneToMany.
@Test
public void testInsertOneToMany() throws Exception {
final Person person = randomPerson();
data.insert(person).thenApply(new Function<Person, Phone>() {
@Override
public Phone apply(Person person) {
Phone phone1 = randomPhone();
phone1.setOwner(person);
return phone1;
}
}).thenCompose(new Function<Phone, CompletionStage<Phone>>() {
@Override
public CompletionStage<Phone> apply(Phone phone) {
return data.insert(phone);
}
}).toCompletableFuture().get();
HashSet<Phone> set = new HashSet<>(person.getPhoneNumbers().toList());
assertEquals(1, set.size());
}
use of java.util.concurrent.CompletionStage in project camel by apache.
the class MethodInfo method createMethodInvocation.
public MethodInvocation createMethodInvocation(final Object pojo, final Exchange exchange) {
final Object[] arguments = parametersExpression.evaluate(exchange, Object[].class);
return new MethodInvocation() {
public Method getMethod() {
return method;
}
public Object[] getArguments() {
return arguments;
}
public boolean proceed(AsyncCallback callback) {
Object body = exchange.getIn().getBody();
if (body != null && body instanceof StreamCache) {
// ensure the stream cache is reset before calling the method
((StreamCache) body).reset();
}
try {
return doProceed(callback);
} catch (InvocationTargetException e) {
exchange.setException(e.getTargetException());
callback.done(true);
return true;
} catch (Throwable e) {
exchange.setException(e);
callback.done(true);
return true;
}
}
private boolean doProceed(AsyncCallback callback) throws Exception {
// dynamic router should be invoked beforehand
if (dynamicRouter != null) {
if (!dynamicRouter.isStarted()) {
ServiceHelper.startService(dynamicRouter);
}
// use a expression which invokes the method to be used by dynamic router
Expression expression = new DynamicRouterExpression(pojo);
return dynamicRouter.doRoutingSlip(exchange, expression, callback);
}
// invoke pojo
if (LOG.isTraceEnabled()) {
LOG.trace(">>>> invoking: {} on bean: {} with arguments: {} for exchange: {}", new Object[] { method, pojo, asString(arguments), exchange });
}
Object result = invoke(method, pojo, arguments, exchange);
// the method may be a closure or chained method returning a callable which should be called
if (result instanceof Callable) {
LOG.trace("Method returned Callback which will be called: {}", result);
Object callableResult = ((Callable) result).call();
if (callableResult != null) {
result = callableResult;
} else {
// if callable returned null we should not change the body
result = Void.TYPE;
}
}
if (recipientList != null) {
// ensure its started
if (!recipientList.isStarted()) {
ServiceHelper.startService(recipientList);
}
return recipientList.sendToRecipientList(exchange, result, callback);
}
if (routingSlip != null) {
if (!routingSlip.isStarted()) {
ServiceHelper.startService(routingSlip);
}
return routingSlip.doRoutingSlip(exchange, result, callback);
}
//If it's Java 8 async result
if (CompletionStage.class.isAssignableFrom(getMethod().getReturnType())) {
CompletionStage<?> completionStage = (CompletionStage<?>) result;
completionStage.whenComplete((resultObject, e) -> {
if (e != null) {
exchange.setException(e);
} else if (resultObject != null) {
fillResult(exchange, resultObject);
}
callback.done(false);
});
return false;
}
// if the method returns something then set the value returned on the Exchange
if (!getMethod().getReturnType().equals(Void.TYPE) && result != Void.TYPE) {
fillResult(exchange, result);
}
// we did not use any of the eips, but just invoked the bean
// so notify the callback we are done synchronously
callback.done(true);
return true;
}
public Object getThis() {
return pojo;
}
public AccessibleObject getStaticPart() {
return method;
}
};
}
use of java.util.concurrent.CompletionStage in project requery by requery.
the class CompletableEntityStoreTest method testInsertCount.
@Test
public void testInsertCount() throws Exception {
Person person = randomPerson();
data.insert(person).thenAccept(new Consumer<Person>() {
@Override
public void accept(Person person) {
assertTrue(person.getId() > 0);
}
}).thenCompose(new Function<Void, CompletionStage<Integer>>() {
@Override
public CompletionStage<Integer> apply(Void aVoid) {
return data.count(Person.class).get().toCompletableFuture();
}
}).toCompletableFuture().get();
}
use of java.util.concurrent.CompletionStage in project torodb by torodb.
the class DefaultOplogApplier method apply.
@Override
public ApplyingJob apply(OplogFetcher fetcher, ApplierContext applierContext) {
Materializer materializer = ActorMaterializer.create(actorSystem);
RunnableGraph<Pair<UniqueKillSwitch, CompletionStage<Done>>> graph = createOplogSource(fetcher).async().via(createBatcherFlow(applierContext)).viaMat(KillSwitches.single(), Keep.right()).async().map(analyzedElem -> {
for (AnalyzedOplogBatch analyzedOplogBatch : analyzedElem.analyzedBatch) {
batchExecutor.apply(analyzedOplogBatch, applierContext);
}
return analyzedElem;
}).map(this::metricExecution).toMat(Sink.foreach(this::storeLastAppliedOp), (killSwitch, completionStage) -> new Pair<>(killSwitch, completionStage));
Pair<UniqueKillSwitch, CompletionStage<Done>> pair = graph.run(materializer);
UniqueKillSwitch killSwitch = pair.first();
CompletableFuture<Empty> whenComplete = pair.second().toCompletableFuture().thenApply(done -> Empty.getInstance()).whenComplete((done, t) -> {
fetcher.close();
if (done != null) {
LOGGER.trace("Oplog replication stream finished normally");
} else {
Throwable cause;
if (t instanceof CompletionException) {
cause = t.getCause();
} else {
cause = t;
}
//the completable future has been cancelled
if (cause instanceof CancellationException) {
LOGGER.debug("Oplog replication stream has been cancelled");
killSwitch.shutdown();
} else {
//in this case the exception should came from the stream
cause = Throwables.getRootCause(cause);
LOGGER.error("Oplog replication stream finished exceptionally: " + cause.getLocalizedMessage(), cause);
//the stream should be finished exceptionally, but just in case we
//notify the kill switch to stop the stream.
killSwitch.shutdown();
}
}
});
return new DefaultApplyingJob(killSwitch, whenComplete);
}
Aggregations