Search in sources :

Example 1 with CompletionStage

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);
    });
}
Also used : ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) CompletableFuture(java.util.concurrent.CompletableFuture) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Collectors(java.util.stream.Collectors) Suspended(javax.ws.rs.container.Suspended) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) Uri(org.glassfish.jersey.server.Uri) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) Queue(java.util.Queue) WebTarget(javax.ws.rs.client.WebTarget) Collections(java.util.Collections) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) ExecutorService(java.util.concurrent.ExecutorService) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) WebTarget(javax.ws.rs.client.WebTarget) CompletionStage(java.util.concurrent.CompletionStage) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation)

Example 2 with CompletionStage

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());
}
Also used : Function(java.util.function.Function) Phone(io.requery.test.model.Phone) Person(io.requery.test.model.Person) CompletionStage(java.util.concurrent.CompletionStage) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 3 with CompletionStage

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;
        }
    };
}
Also used : StreamCache(org.apache.camel.StreamCache) Expression(org.apache.camel.Expression) AsyncCallback(org.apache.camel.AsyncCallback) AccessibleObject(java.lang.reflect.AccessibleObject) InvocationTargetException(java.lang.reflect.InvocationTargetException) Callable(java.util.concurrent.Callable) CompletionStage(java.util.concurrent.CompletionStage)

Example 4 with CompletionStage

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();
}
Also used : Consumer(java.util.function.Consumer) Person(io.requery.test.model.Person) CompletionStage(java.util.concurrent.CompletionStage) Test(org.junit.Test)

Example 5 with CompletionStage

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);
}
Also used : AnalyzedOplogBatch(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatch) BatchAnalyzerFactory(com.torodb.mongodb.repl.oplogreplier.batch.BatchAnalyzer.BatchAnalyzerFactory) BiFunction(java.util.function.BiFunction) Flow(akka.stream.javadsl.Flow) Source(akka.stream.javadsl.Source) Supplier(com.google.common.base.Supplier) KillSwitch(akka.stream.KillSwitch) Materializer(akka.stream.Materializer) CompletableFuture(java.util.concurrent.CompletableFuture) UniqueKillSwitch(akka.stream.UniqueKillSwitch) OplogManager(com.torodb.mongodb.repl.OplogManager) BatchAnalyzer(com.torodb.mongodb.repl.oplogreplier.batch.BatchAnalyzer) Inject(javax.inject.Inject) ActorMaterializer(akka.stream.ActorMaterializer) Keep(akka.stream.javadsl.Keep) RunnableGraph(akka.stream.javadsl.RunnableGraph) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation) Empty(com.eightkdata.mongowp.server.api.tools.Empty) OplogManagerPersistException(com.torodb.mongodb.repl.OplogManager.OplogManagerPersistException) AnalyzedOplogBatchExecutor(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatchExecutor) ConcurrentToolsFactory(com.torodb.core.concurrent.ConcurrentToolsFactory) AnalyzedOplogBatch(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatch) OplogFetcher(com.torodb.mongodb.repl.oplogreplier.fetcher.OplogFetcher) Shutdowner(com.torodb.core.Shutdowner) Done(akka.Done) CancellationException(java.util.concurrent.CancellationException) FiniteDuration(scala.concurrent.duration.FiniteDuration) Predicate(java.util.function.Predicate) ToIntFunction(java.util.function.ToIntFunction) Sink(akka.stream.javadsl.Sink) Throwables(com.google.common.base.Throwables) CompletionException(java.util.concurrent.CompletionException) KillSwitches(akka.stream.KillSwitches) WriteOplogTransaction(com.torodb.mongodb.repl.OplogManager.WriteOplogTransaction) ExecutionContexts(akka.dispatch.ExecutionContexts) Pair(akka.japi.Pair) TimeUnit(java.util.concurrent.TimeUnit) Duration(scala.concurrent.duration.Duration) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CompletionStage(java.util.concurrent.CompletionStage) NotUsed(akka.NotUsed) BatchFlow(com.torodb.concurrent.akka.BatchFlow) ActorSystem(akka.actor.ActorSystem) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) Await(scala.concurrent.Await) Done(akka.Done) UniqueKillSwitch(akka.stream.UniqueKillSwitch) Empty(com.eightkdata.mongowp.server.api.tools.Empty) CancellationException(java.util.concurrent.CancellationException) CompletionException(java.util.concurrent.CompletionException) Materializer(akka.stream.Materializer) ActorMaterializer(akka.stream.ActorMaterializer) CompletionStage(java.util.concurrent.CompletionStage) Pair(akka.japi.Pair)

Aggregations

CompletionStage (java.util.concurrent.CompletionStage)5 Person (io.requery.test.model.Person)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Done (akka.Done)1 NotUsed (akka.NotUsed)1 ActorSystem (akka.actor.ActorSystem)1 ExecutionContexts (akka.dispatch.ExecutionContexts)1 Pair (akka.japi.Pair)1 ActorMaterializer (akka.stream.ActorMaterializer)1 KillSwitch (akka.stream.KillSwitch)1 KillSwitches (akka.stream.KillSwitches)1 Materializer (akka.stream.Materializer)1 UniqueKillSwitch (akka.stream.UniqueKillSwitch)1 Flow (akka.stream.javadsl.Flow)1 Keep (akka.stream.javadsl.Keep)1 RunnableGraph (akka.stream.javadsl.RunnableGraph)1 Sink (akka.stream.javadsl.Sink)1 Source (akka.stream.javadsl.Source)1 OplogOperation (com.eightkdata.mongowp.server.api.oplog.OplogOperation)1