List of usage examples for java.util.concurrent CompletableFuture handle
public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn)
From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java
public static <T> Response createFunction(IServiceContext service_context, String service_type, String access_level, String service_identifier, Optional<String> bucket_full_names, final FileDescriptor file_upload, Optional<String> json) { //TODO some validation that we are getting back a file crud service (so we cant send the wrong args) final Either<String, Tuple2<ICrudService<T>, Class<T>>> crud_service_either = RestUtils .getCrudService(service_context, service_type, access_level, service_identifier, bucket_full_names); if (crud_service_either.isLeft()) return Response.status(Status.BAD_REQUEST).entity(crud_service_either.left().value()).build(); final Optional<CompletableFuture<Supplier<Object>>> maybe_fut = json .<CompletableFuture<Supplier<Object>>>map(j -> { //TODO exception when this isn't a shared lib bean final SharedLibraryBean slb = BeanTemplateUtils.from(j, SharedLibraryBean.class).get(); final ICrudService<Tuple2<ICrudService<T>, Class<T>>> crud_service = (ICrudService<Tuple2<ICrudService<T>, Class<T>>>) crud_service_either .right().value()._1(); return (CompletableFuture<Supplier<Object>>) crud_service .storeObject(new Tuple2(slb, file_upload)); });/*from w w w . j ava2 s . c o m*/ final CompletableFuture<Supplier<Object>> fut = maybe_fut // (sun didn't like this in one statement so split into 2 for compile reasons) .orElseGet(() -> { final ICrudService<FileDescriptor> crud_service = (ICrudService<FileDescriptor>) crud_service_either .right().value()._1(); return (CompletableFuture<Supplier<Object>>) crud_service.storeObject(file_upload); }); try { final Tuple3<String, Boolean, String> id_or_error = fut.handle((ok, ex) -> { if (ok != null) return new Tuple3<String, Boolean, String>(ok.get().toString(), true, "ok"); else if (ex != null) return new Tuple3<String, Boolean, String>(null, false, ErrorUtils.getLongForm("Exception storing object: {0}", ex)); else return new Tuple3<String, Boolean, String>(null, false, "something went very wrong, shouldn't have reached this piece of code"); }).get(); return Response.ok(RestUtils .convertObjectToJson(new CreateResponse(id_or_error._1(), id_or_error._2(), id_or_error._3())) .toString()).build(); } catch (Exception e) { return Response.status(Status.BAD_REQUEST).entity(ErrorUtils.getLongForm("Error: {0}", e)).build(); } }
From source file:com.carlomicieli.jtrains.infrastructure.web.CompletableFutureReturnValueHandler.java
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { final DeferredResult<Object> deferredResult = new DeferredResult<>(); final CompletableFuture<?> future = (CompletableFuture<?>) returnValue; final CompletableFuture<Object> completedFuture = future.handle((ret, err) -> { if (ret != null) { deferredResult.setResult(ret); return ret; } else {/*from ww w . j av a 2s . co m*/ deferredResult.setErrorResult(err); return null; } }); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer); }
From source file:org.apache.pulsar.broker.service.BrokerService.java
/** * It creates a topic async and returns CompletableFuture. It also throttles down configured max-concurrent topic * loading and puts them into queue once in-process topics are created. * //from w w w . jav a 2 s . c o m * @param topic persistent-topic name * @return CompletableFuture<Topic> * @throws RuntimeException */ protected CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException { checkTopicNsOwnership(topic); final CompletableFuture<Topic> topicFuture = new CompletableFuture<>(); final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get(); if (topicLoadSemaphore.tryAcquire()) { createPersistentTopic(topic, topicFuture); topicFuture.handle((persistentTopic, ex) -> { // release permit and process pending topic topicLoadSemaphore.release(); createPendingLoadTopic(); return null; }); } else { pendingTopicLoadingQueue.add(new ImmutablePair<String, CompletableFuture<Topic>>(topic, topicFuture)); if (log.isDebugEnabled()) { log.debug("topic-loading for {} added into pending queue", topic); } } return topicFuture; }
From source file:org.apache.pulsar.broker.service.BrokerService.java
/** * Create pending topic and on completion it picks the next one until processes all topics in * {@link #pendingTopicLoadingQueue}.<br/> * It also tries to acquire {@link #topicLoadRequestSemaphore} so throttle down newly incoming topics and release * permit if it was successful to acquire it. */// w w w . j ava 2s.c o m private void createPendingLoadTopic() { Pair<String, CompletableFuture<Topic>> pendingTopic = pendingTopicLoadingQueue.poll(); if (pendingTopic == null) { return; } final String topic = pendingTopic.getLeft(); try { checkTopicNsOwnership(topic); CompletableFuture<Topic> pendingFuture = pendingTopic.getRight(); final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get(); final boolean acquiredPermit = topicLoadSemaphore.tryAcquire(); createPersistentTopic(topic, pendingFuture); pendingFuture.handle((persistentTopic, ex) -> { // release permit and process next pending topic if (acquiredPermit) { topicLoadSemaphore.release(); } createPendingLoadTopic(); return null; }); } catch (RuntimeException re) { log.error("Failed to create pending topic {} {}", topic, re); pendingTopic.getRight().completeExceptionally(re.getCause()); // schedule to process next pending topic inactivityMonitor.schedule(() -> createPendingLoadTopic(), 100, TimeUnit.MILLISECONDS); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldRaiseExceptionInWithResultOfLifeCycle() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final GremlinExecutor.LifeCycle lc = GremlinExecutor.LifeCycle.build().withResult(r -> { throw new RuntimeException("no worky"); }).create();/*from w w w .j a v a2s .com*/ final AtomicBoolean exceptionRaised = new AtomicBoolean(false); final CompletableFuture<Object> future = gremlinExecutor.eval("1+1", "gremlin-groovy", new SimpleBindings(), lc); future.handle((r, t) -> { exceptionRaised.set(t != null && t instanceof RuntimeException && t.getMessage().equals("no worky")); return null; }).get(); assertThat(exceptionRaised.get(), is(true)); gremlinExecutor.close(); }
From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java
/** * A generalized implementation of the "eval" operation. It handles script evaluation and iteration of results * so as to write {@link ResponseMessage} objects down the Netty pipeline. It also handles script timeouts, * iteration timeouts, metrics and building bindings. Note that result iteration is delegated to the * {@link #handleIterator} method, so those extending this class could override that method for better control * over result iteration./* w ww . j av a2 s. c om*/ * * @param context The current Gremlin Server {@link Context} * @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the * script evaluation. * @param bindingsSupplier A function that returns the {@link Bindings} to provide to the * {@link GremlinExecutor#eval} method. */ protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier, final BindingSupplier bindingsSupplier) throws OpProcessorException { final Timer.Context timerContext = evalOpTimer.time(); final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final RequestMessage msg = context.getRequestMessage(); final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get(); final Settings settings = context.getSettings(); final Map<String, Object> args = msg.getArgs(); final String script = (String) args.get(Tokens.ARGS_GREMLIN); final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE) : null; final Bindings bindings = new SimpleBindings(); // sessionless requests are always transaction managed, but in-session requests are configurable. final boolean managedTransactionsForRequest = manageTransactions ? true : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false); final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build().beforeEval(b -> { try { b.putAll(bindingsSupplier.get()); } catch (OpProcessorException ope) { // this should bubble up in the GremlinExecutor properly as the RuntimeException will be // unwrapped and the root cause thrown throw new RuntimeException(ope); } }).withResult(o -> { final Iterator itty = IteratorUtils.asIterator(o); logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg, Thread.currentThread().getName()); try { handleIterator(context, itty); } catch (TimeoutException ex) { final String errorMessage = String.format( "Response iteration exceeded the configured threshold for request [%s] - %s", msg, ex.getMessage()); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } catch (Exception ex) { logger.warn(String.format("Exception processing a script on request [%s].", msg), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } }).create(); final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle); evalFuture.handle((v, t) -> { timerContext.stop(); if (t != null) { if (t instanceof OpProcessorException) { ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage()); } else if (t instanceof TimedInterruptTimeoutException) { // occurs when the TimedInterruptCustomizerProvider is in play final String errorMessage = String.format( "A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider", msg); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage( "Timeout during script evaluation triggered by TimedInterruptCustomizerProvider") .create()); } else if (t instanceof TimeoutException) { final String errorMessage = String.format( "Response evaluation exceeded the configured threshold for request [%s] - %s", msg, t.getMessage()); logger.warn(errorMessage, t); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(t.getMessage()).create()); } else { logger.warn(String.format("Exception processing a script on request [%s].", msg), t); ctx.writeAndFlush( ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION) .statusMessage(t.getMessage()).create()); } } return null; }); }