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;
}
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;
}
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();
}
}
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);
}
}
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;
}
}
Aggregations