Search in sources :

Example 1 with ListenableFuture

use of org.springframework.util.concurrent.ListenableFuture in project data-prep by Talend.

the class SimpleManagedTaskExecutor method queue.

/**
 * @see ManagedTaskExecutor#queue(ManagedTaskCallable, String, String, AsyncExecutionResult)
 */
@Override
public synchronized AsyncExecution queue(final ManagedTaskCallable task, String executionId, String groupId, AsyncExecutionResult resultUrl) {
    // Create async execution
    final AsyncExecution asyncExecution = ofNullable(groupId).map(s -> new AsyncExecution(groupId)).orElseGet(AsyncExecution::new);
    if (StringUtils.isNotEmpty(executionId)) {
        asyncExecution.setId(executionId);
    }
    asyncExecution.setUserId(security.getUserId());
    asyncExecution.setTenantId(security.getTenantId());
    repository.save(asyncExecution);
    // Wrap callable to get the running status.
    final Callable wrapper = wrapTaskWithProgressInformation(task, asyncExecution);
    asyncExecution.setResult(resultUrl);
    ListenableFuture future = delegate.submitListenable(wrapper);
    future.addCallback(new AsyncListenableFutureCallback(asyncExecution));
    futures.put(asyncExecution.getId(), future);
    LOGGER.debug("Execution {} queued for execution.", asyncExecution.getId());
    return asyncExecution;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) TDPException(org.talend.dataprep.exception.TDPException) TransformationErrorCodes(org.talend.dataprep.exception.error.TransformationErrorCodes) Logger(org.slf4j.Logger) CancellationException(java.util.concurrent.CancellationException) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) Optional.ofNullable(java.util.Optional.ofNullable) ManagedTaskRepository(org.talend.dataprep.async.repository.ManagedTaskRepository) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Callable(java.util.concurrent.Callable) AsyncListenableTaskExecutor(org.springframework.core.task.AsyncListenableTaskExecutor) Signal(org.talend.dataprep.transformation.pipeline.Signal) ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) Component(org.springframework.stereotype.Component) ExceptionContext(org.talend.daikon.exception.ExceptionContext) DONE(org.talend.dataprep.async.AsyncExecution.Status.DONE) Map(java.util.Map) ExecutionContext(org.talend.dataprep.async.progress.ExecutionContext) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Optional(java.util.Optional) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) Security(org.talend.dataprep.security.Security) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) Callable(java.util.concurrent.Callable)

Example 2 with ListenableFuture

use of org.springframework.util.concurrent.ListenableFuture in project data-prep by Talend.

the class SimpleManagedTaskExecutor method resume.

@Override
public AsyncExecution resume(ManagedTaskCallable task, String executionId, AsyncExecutionResult resultUrl) {
    LOGGER.debug("Resuming execution '{}' from repository '{}'", executionId, repository);
    final AsyncExecution execution = repository.get(executionId);
    if (execution == null) {
        LOGGER.error("Execution #{} can be resumed (not found).", executionId);
        throw new TDPException(TransformationErrorCodes.UNABLE_TO_RESUME_EXECUTION, ExceptionContext.withBuilder().put("id", executionId).build());
    } else if (execution.getStatus() != AsyncExecution.Status.RUNNING) {
        // Execution is expected to be created as "RUNNING" before the dispatcher resumes it.
        LOGGER.error("Execution #{} can be resumed (status is {}).", execution.getStatus());
        throw new TDPException(TransformationErrorCodes.UNABLE_TO_RESUME_EXECUTION, ExceptionContext.withBuilder().put("id", executionId).build());
    }
    // Wrap callable to get the running status.
    final Callable wrapper = wrapTaskWithProgressInformation(task, execution);
    execution.setResult(resultUrl);
    ListenableFuture future = delegate.submitListenable(wrapper);
    future.addCallback(new AsyncListenableFutureCallback(execution));
    futures.put(execution.getId(), future);
    LOGGER.debug("Execution {} resumed for execution.", execution.getId());
    return execution;
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) Callable(java.util.concurrent.Callable)

Example 3 with ListenableFuture

use of org.springframework.util.concurrent.ListenableFuture in project pinpoint by naver.

the class AsyncHttpRequestInterceptor method traceAndRecordFuture.

// reason for virtual Method
// //////////////////////////////////////////////////
// 1. if virtualMethod not crated
// executeAsync
// - Asynchronous Invocation (for future set)
// - some trace (like connect, write, etc ...)
// //////////////////////////
// 2. if virtualMethod crated
// executeAsync
// 
// - some trace (like connect, write, etc ...)
// - Asynchronous Invocation (for future set)
// //////////////////////////////////////////////////
private void traceAndRecordFuture(Object result, Throwable throwable) {
    if (throwable != null) {
        return;
    }
    if (!(result instanceof ListenableFuture)) {
        return;
    }
    final Trace virtualMethodTrace = traceContext.currentTraceObject();
    try {
        SpanEventRecorder recorder = virtualMethodTrace.traceBlockBegin();
        recorder.recordServiceType(RestTemplateConstants.SERVICE_TYPE);
        recorder.recordApi(execAsyncResultMethodDescriptor);
        if (isAsynchronousInvocation(result)) {
            // set asynchronous trace
            final AsyncContext asyncContext = recorder.recordNextAsyncContext();
            ((AsyncContextAccessor) result)._$PINPOINT$_setAsyncContext(asyncContext);
            if (isDebug) {
                logger.debug("Set AsyncContext {}", asyncContext);
            }
            if (result instanceof TraceFutureFlagAccessor) {
                ((TraceFutureFlagAccessor) result)._$PINPOINT$_setTraceFlag(true);
            }
        }
    } finally {
        virtualMethodTrace.traceBlockEnd();
    }
}
Also used : Trace(com.navercorp.pinpoint.bootstrap.context.Trace) TraceFutureFlagAccessor(com.navercorp.pinpoint.plugin.resttemplate.field.accessor.TraceFutureFlagAccessor) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) AsyncContextAccessor(com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) AsyncContext(com.navercorp.pinpoint.bootstrap.context.AsyncContext)

Example 4 with ListenableFuture

use of org.springframework.util.concurrent.ListenableFuture in project spring-integration by spring-projects.

the class AbstractMessageProducingHandler method produceOutput.

protected void produceOutput(Object reply, final Message<?> requestMessage) {
    final MessageHeaders requestHeaders = requestMessage.getHeaders();
    Object replyChannel = null;
    if (getOutputChannel() == null) {
        Map<?, ?> routingSlipHeader = requestHeaders.get(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Map.class);
        if (routingSlipHeader != null) {
            Assert.isTrue(routingSlipHeader.size() == 1, "The RoutingSlip header value must be a SingletonMap");
            Object key = routingSlipHeader.keySet().iterator().next();
            Object value = routingSlipHeader.values().iterator().next();
            Assert.isInstanceOf(List.class, key, "The RoutingSlip key must be List");
            Assert.isInstanceOf(Integer.class, value, "The RoutingSlip value must be Integer");
            List<?> routingSlip = (List<?>) key;
            AtomicInteger routingSlipIndex = new AtomicInteger((Integer) value);
            replyChannel = getOutputChannelFromRoutingSlip(reply, requestMessage, routingSlip, routingSlipIndex);
            if (replyChannel != null) {
                // TODO Migrate to the SF MessageBuilder
                AbstractIntegrationMessageBuilder<?> builder = null;
                if (reply instanceof Message) {
                    builder = this.getMessageBuilderFactory().fromMessage((Message<?>) reply);
                } else if (reply instanceof AbstractIntegrationMessageBuilder) {
                    builder = (AbstractIntegrationMessageBuilder<?>) reply;
                } else {
                    builder = this.getMessageBuilderFactory().withPayload(reply);
                }
                builder.setHeader(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Collections.singletonMap(routingSlip, routingSlipIndex.get()));
                reply = builder;
            }
        }
        if (replyChannel == null) {
            replyChannel = requestHeaders.getReplyChannel();
            if (replyChannel == null && reply instanceof Message) {
                replyChannel = ((Message<?>) reply).getHeaders().getReplyChannel();
            }
        }
    }
    if (this.async && (reply instanceof ListenableFuture<?> || reply instanceof Publisher<?>)) {
        if (reply instanceof ListenableFuture<?> || !(getOutputChannel() instanceof ReactiveStreamsSubscribableChannel)) {
            ListenableFuture<?> future;
            if (reply instanceof ListenableFuture<?>) {
                future = (ListenableFuture<?>) reply;
            } else {
                SettableListenableFuture<Object> settableListenableFuture = new SettableListenableFuture<>();
                Mono.from((Publisher<?>) reply).subscribe(settableListenableFuture::set, settableListenableFuture::setException);
                future = settableListenableFuture;
            }
            Object theReplyChannel = replyChannel;
            future.addCallback(new ListenableFutureCallback<Object>() {

                @Override
                public void onSuccess(Object result) {
                    Message<?> replyMessage = null;
                    try {
                        replyMessage = createOutputMessage(result, requestHeaders);
                        sendOutput(replyMessage, theReplyChannel, false);
                    } catch (Exception e) {
                        Exception exceptionToLogAndSend = e;
                        if (!(e instanceof MessagingException)) {
                            exceptionToLogAndSend = new MessageHandlingException(requestMessage, e);
                            if (replyMessage != null) {
                                exceptionToLogAndSend = new MessagingException(replyMessage, exceptionToLogAndSend);
                            }
                        }
                        logger.error("Failed to send async reply: " + result.toString(), exceptionToLogAndSend);
                        onFailure(exceptionToLogAndSend);
                    }
                }

                @Override
                public void onFailure(Throwable ex) {
                    sendErrorMessage(requestMessage, ex);
                }
            });
        } else {
            ((ReactiveStreamsSubscribableChannel) getOutputChannel()).subscribeTo(Flux.from((Publisher<?>) reply).map(result -> createOutputMessage(result, requestHeaders)));
        }
    } else {
        sendOutput(createOutputMessage(reply, requestHeaders), replyChannel, false);
    }
}
Also used : MessagingException(org.springframework.messaging.MessagingException) Arrays(java.util.Arrays) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) HashMap(java.util.HashMap) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) MessagingTemplate(org.springframework.integration.core.MessagingTemplate) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Map(java.util.Map) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) RoutingSlipRouteStrategy(org.springframework.integration.routingslip.RoutingSlipRouteStrategy) Message(org.springframework.messaging.Message) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) PatternMatchUtils(org.springframework.util.PatternMatchUtils) Set(java.util.Set) Mono(reactor.core.publisher.Mono) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageProducer(org.springframework.integration.core.MessageProducer) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) Publisher(org.reactivestreams.Publisher) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) List(java.util.List) MessageHeaders(org.springframework.messaging.MessageHeaders)

Example 5 with ListenableFuture

use of org.springframework.util.concurrent.ListenableFuture in project spring-framework by spring-projects.

the class JettyWebSocketClient method doHandshakeInternal.

@Override
public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler, HttpHeaders headers, final URI uri, List<String> protocols, List<WebSocketExtension> extensions, Map<String, Object> attributes) {
    final ClientUpgradeRequest request = new ClientUpgradeRequest();
    request.setSubProtocols(protocols);
    for (WebSocketExtension extension : extensions) {
        request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(extension));
    }
    request.setHeaders(headers);
    Principal user = getUser();
    JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
    Callable<WebSocketSession> connectTask = () -> {
        JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);
        Future<Session> future = this.client.connect(adapter, uri, request);
        future.get(this.client.getConnectTimeout() + 2000, TimeUnit.MILLISECONDS);
        return wsSession;
    };
    if (this.taskExecutor != null) {
        return this.taskExecutor.submitListenable(connectTask);
    } else {
        ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask);
        task.run();
        return task;
    }
}
Also used : WebSocketExtension(org.springframework.web.socket.WebSocketExtension) ListenableFutureTask(org.springframework.util.concurrent.ListenableFutureTask) WebSocketToJettyExtensionConfigAdapter(org.springframework.web.socket.adapter.jetty.WebSocketToJettyExtensionConfigAdapter) JettyWebSocketSession(org.springframework.web.socket.adapter.jetty.JettyWebSocketSession) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) Future(java.util.concurrent.Future) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) Principal(java.security.Principal) JettyWebSocketHandlerAdapter(org.springframework.web.socket.adapter.jetty.JettyWebSocketHandlerAdapter) WebSocketSession(org.springframework.web.socket.WebSocketSession) JettyWebSocketSession(org.springframework.web.socket.adapter.jetty.JettyWebSocketSession)

Aggregations

ListenableFuture (org.springframework.util.concurrent.ListenableFuture)5 Map (java.util.Map)2 Callable (java.util.concurrent.Callable)2 ListenableFutureCallback (org.springframework.util.concurrent.ListenableFutureCallback)2 TDPException (org.talend.dataprep.exception.TDPException)2 AsyncContextAccessor (com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor)1 AsyncContext (com.navercorp.pinpoint.bootstrap.context.AsyncContext)1 SpanEventRecorder (com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder)1 Trace (com.navercorp.pinpoint.bootstrap.context.Trace)1 TraceFutureFlagAccessor (com.navercorp.pinpoint.plugin.resttemplate.field.accessor.TraceFutureFlagAccessor)1 Principal (java.security.Principal)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Optional (java.util.Optional)1 Optional.ofNullable (java.util.Optional.ofNullable)1 Set (java.util.Set)1