List of usage examples for org.springframework.util.concurrent SettableListenableFuture setException
public boolean setException(Throwable exception)
From source file:org.springframework.cloud.deployer.spi.yarn.YarnAppDeployer.java
@Override public String deploy(AppDeploymentRequest request) { logger.info("Deploy request for {}", request); final AppDefinition definition = request.getDefinition(); Map<String, String> definitionParameters = definition.getProperties(); Map<String, String> deploymentProperties = request.getDeploymentProperties(); logger.info("Deploying request for definition {}", definition); logger.info("Parameters for definition {}", definitionParameters); logger.info("Deployment properties for request {}", deploymentProperties); int count = 1; String countString = request.getDeploymentProperties().get(AppDeployer.COUNT_PROPERTY_KEY); if (StringUtils.hasText(countString)) { count = Integer.parseInt(countString); }/*from ww w . java 2 s .c o m*/ final String group = request.getDeploymentProperties().get(AppDeployer.GROUP_PROPERTY_KEY); Resource resource = request.getResource(); final String clusterId = group + ":" + definition.getName(); // contextRunArgs are passed to boot app ran to control yarn apps ArrayList<String> contextRunArgs = new ArrayList<String>(); contextRunArgs.add("--spring.yarn.appName=scdstream:app:" + group); // deployment properties override servers.yml which overrides application.yml for (Entry<String, String> entry : deploymentProperties.entrySet()) { if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.streamappmaster")) { contextRunArgs.add("--" + entry.getKey() + "=" + entry.getValue()); } else if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.streamcontainer")) { // weird format with '--' is just straight pass to appmaster contextRunArgs.add("--spring.yarn.client.launchcontext.arguments.--" + entry.getKey() + "='" + entry.getValue() + "'"); } } String baseDir = yarnDeployerProperties.getBaseDir(); if (!baseDir.endsWith("/")) { baseDir = baseDir + "/"; } String artifactPath = isHdfsResource(resource) ? getHdfsArtifactPath(resource) : baseDir + "/artifacts/cache/"; contextRunArgs .add("--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.artifact=" + artifactPath); // TODO: using default app name "app" until we start to customise // via deploymentProperties final Message<String> message = MessageBuilder.withPayload(AppDeployerStateMachine.EVENT_DEPLOY) .setHeader(AppDeployerStateMachine.HEADER_APP_VERSION, "app") .setHeader(AppDeployerStateMachine.HEADER_CLUSTER_ID, clusterId) .setHeader(AppDeployerStateMachine.HEADER_GROUP_ID, group) .setHeader(AppDeployerStateMachine.HEADER_COUNT, count) .setHeader(AppDeployerStateMachine.HEADER_ARTIFACT, resource) .setHeader(AppDeployerStateMachine.HEADER_ARTIFACT_DIR, artifactPath) .setHeader(AppDeployerStateMachine.HEADER_DEFINITION_PARAMETERS, definitionParameters) .setHeader(AppDeployerStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs).build(); // Use of future here is to set id when it becomes available from machine final SettableListenableFuture<String> id = new SettableListenableFuture<>(); final StateMachineListener<String, String> listener = new StateMachineListenerAdapter<String, String>() { @Override public void stateContext(StateContext<String, String> stateContext) { if (stateContext.getStage() == Stage.STATE_ENTRY && stateContext.getTarget().getId().equals(AppDeployerStateMachine.STATE_READY)) { if (ObjectUtils.nullSafeEquals(message.getHeaders().getId().toString(), stateContext .getExtendedState().get(AppDeployerStateMachine.VAR_MESSAGE_ID, String.class))) { Exception exception = stateContext.getExtendedState().get(AppDeployerStateMachine.VAR_ERROR, Exception.class); if (exception != null) { id.setException(exception); } else { String applicationId = stateContext.getStateMachine().getExtendedState() .get(AppDeployerStateMachine.VAR_APPLICATION_ID, String.class); DeploymentKey key = new DeploymentKey(group, definition.getName(), applicationId); id.set(key.toString()); } } } } }; stateMachine.addStateListener(listener); id.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { stateMachine.removeStateListener(listener); } @Override public void onFailure(Throwable ex) { stateMachine.removeStateListener(listener); } }); stateMachine.sendEvent(message); // we need to block here until SPI supports // returning id asynchronously try { return id.get(2, TimeUnit.MINUTES); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.springframework.cloud.deployer.spi.yarn.YarnTaskLauncher.java
@Override public String launch(AppDeploymentRequest request) { logger.info("Deploy request for {}", request); logger.info("Deploy request deployment properties {}", request.getDeploymentProperties()); logger.info("Deploy definition {}", request.getDefinition()); Resource resource = request.getResource(); AppDefinition definition = request.getDefinition(); String artifact = resource.getFilename(); final String name = definition.getName(); Map<String, String> definitionParameters = definition.getProperties(); Map<String, String> deploymentProperties = request.getDeploymentProperties(); List<String> commandlineArguments = request.getCommandlineArguments(); String appName = "scdtask:" + name; // contextRunArgs are passed to boot app ran to control yarn apps // we pass needed args to control module coordinates and params, // weird format with '--' is just straight pass to container ArrayList<String> contextRunArgs = new ArrayList<String>(); contextRunArgs.add("--spring.yarn.appName=" + appName); for (Entry<String, String> entry : definitionParameters.entrySet()) { if (StringUtils.hasText(entry.getValue())) { contextRunArgs.add(// w w w.j a va2 s .com "--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.parameters." + entry.getKey() + ".='" + entry.getValue() + "'"); } } int index = 0; for (String commandlineArgument : commandlineArguments) { contextRunArgs.add("--spring.yarn.client.launchcontext.argumentsList[" + index + "]='--spring.cloud.deployer.yarn.appmaster.commandlineArguments[" + index + "]=" + commandlineArgument + "'"); index++; } String baseDir = yarnDeployerProperties.getBaseDir(); if (!baseDir.endsWith("/")) { baseDir = baseDir + "/"; } String artifactPath = isHdfsResource(resource) ? getHdfsArtifactPath(resource) : baseDir + "/artifacts/cache/"; contextRunArgs.add( "--spring.yarn.client.launchcontext.arguments.--spring.yarn.appmaster.launchcontext.archiveFile=" + artifact); contextRunArgs .add("--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.artifact=" + artifactPath + artifact); // deployment properties override servers.yml which overrides application.yml for (Entry<String, String> entry : deploymentProperties.entrySet()) { if (StringUtils.hasText(entry.getValue())) { if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskcontainer")) { contextRunArgs.add("--spring.yarn.client.launchcontext.arguments.--" + entry.getKey() + "='" + entry.getValue() + "'"); } else if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskappmaster")) { contextRunArgs.add("--" + entry.getKey() + "=" + entry.getValue()); } } } final Message<String> message = MessageBuilder.withPayload(TaskLauncherStateMachine.EVENT_LAUNCH) .setHeader(TaskLauncherStateMachine.HEADER_APP_VERSION, "app") .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT, resource) .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT_DIR, artifactPath) .setHeader(TaskLauncherStateMachine.HEADER_DEFINITION_PARAMETERS, definitionParameters) .setHeader(TaskLauncherStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs).build(); // setup future, listen event from machine and finally unregister listener, // and set future value final SettableListenableFuture<String> id = new SettableListenableFuture<>(); final StateMachineListener<String, String> listener = new StateMachineListenerAdapter<String, String>() { @Override public void stateContext(StateContext<String, String> stateContext) { if (stateContext.getStage() == Stage.STATE_ENTRY && stateContext.getTarget().getId().equals(TaskLauncherStateMachine.STATE_READY)) { if (ObjectUtils.nullSafeEquals(message.getHeaders().getId().toString(), stateContext .getExtendedState().get(TaskLauncherStateMachine.VAR_MESSAGE_ID, String.class))) { Exception exception = stateContext.getExtendedState() .get(TaskLauncherStateMachine.VAR_ERROR, Exception.class); if (exception != null) { id.setException(exception); } else { String applicationId = stateContext.getStateMachine().getExtendedState() .get(TaskLauncherStateMachine.VAR_APPLICATION_ID, String.class); DeploymentKey key = new DeploymentKey(name, applicationId); id.set(key.toString()); } } } } }; stateMachine.addStateListener(listener); id.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { stateMachine.removeStateListener(listener); } @Override public void onFailure(Throwable ex) { stateMachine.removeStateListener(listener); } }); stateMachine.sendEvent(message); // we need to block here until SPI supports // returning id asynchronously try { return id.get(2, TimeUnit.MINUTES); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.springframework.cloud.gcp.pubsub.core.publisher.PubSubPublisherTemplate.java
@Override public ListenableFuture<String> publish(final String topic, PubsubMessage pubsubMessage) { Assert.hasText(topic, "The topic can't be null or empty."); Assert.notNull(pubsubMessage, "The pubsubMessage can't be null."); ApiFuture<String> publishFuture = this.publisherFactory.createPublisher(topic).publish(pubsubMessage); final SettableListenableFuture<String> settableFuture = new SettableListenableFuture<>(); ApiFutures.addCallback(publishFuture, new ApiFutureCallback<String>() { @Override/* w w w . ja v a 2 s .co m*/ public void onFailure(Throwable throwable) { LOGGER.warn("Publishing to " + topic + " topic failed.", throwable); settableFuture.setException(throwable); } @Override public void onSuccess(String result) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Publishing to " + topic + " was successful. Message ID: " + result); } settableFuture.set(result); } }); return settableFuture; }
From source file:org.springframework.integration.handler.AsyncHandlerTests.java
@Before public void setup() { this.handler = new AbstractReplyProducingMessageHandler() { @Override// w w w . ja va 2 s . c o m protected Object handleRequestMessage(Message<?> requestMessage) { final SettableListenableFuture<String> future = new SettableListenableFuture<String>(); Executors.newSingleThreadExecutor().execute(() -> { try { latch.await(10, TimeUnit.SECONDS); switch (whichTest) { case 0: future.set("reply"); break; case 1: future.setException(new RuntimeException("foo")); break; case 2: future.setException(new MessagingException(requestMessage)); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); return future; } }; this.handler.setAsync(true); this.handler.setOutputChannel(this.output); this.handler.setBeanFactory(mock(BeanFactory.class)); this.latch = new CountDownLatch(1); Log logger = spy(TestUtils.getPropertyValue(this.handler, "logger", Log.class)); new DirectFieldAccessor(this.handler).setPropertyValue("logger", logger); doAnswer(invocation -> { failedCallbackMessage = invocation.getArgument(0); failedCallbackException = invocation.getArgument(1); exceptionLatch.countDown(); return null; }).when(logger).error(anyString(), any(Throwable.class)); }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private void expire(String correlationId) { final SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> future = this.futures .remove(correlationId);/* www. ja va 2 s . c om*/ if (future != null) { try { if (getRequiresReply()) { future.setException(new JmsTimeoutException("No reply in " + this.receiveTimeout + " ms")); } else { if (logger.isDebugEnabled()) { logger.debug("Reply expired and reply not required for " + correlationId); } } } catch (Exception e) { logger.error("Exception while expiring future"); } } }
From source file:org.springframework.kafka.core.KafkaTemplate.java
/** * Send the producer record./*from www . jav a2s . com*/ * @param producerRecord the producer record. * @return a Future for the {@link RecordMetadata}. */ protected ListenableFuture<SendResult<K, V>> doSend(final ProducerRecord<K, V> producerRecord) { getTheProducer(); if (this.logger.isTraceEnabled()) { this.logger.trace("Sending: " + producerRecord); } final SettableListenableFuture<SendResult<K, V>> future = new SettableListenableFuture<>(); getTheProducer().send(producerRecord, new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception == null) { future.set(new SendResult<>(producerRecord, metadata)); if (KafkaTemplate.this.producerListener != null && KafkaTemplate.this.producerListener.isInterestedInSuccess()) { KafkaTemplate.this.producerListener.onSuccess(producerRecord.topic(), producerRecord.partition(), producerRecord.key(), producerRecord.value(), metadata); } } else { future.setException(new KafkaProducerException(producerRecord, "Failed to send", exception)); if (KafkaTemplate.this.producerListener != null) { KafkaTemplate.this.producerListener.onError(producerRecord.topic(), producerRecord.partition(), producerRecord.key(), producerRecord.value(), exception); } } } }); if (this.autoFlush) { flush(); } if (this.logger.isTraceEnabled()) { this.logger.trace("Sent: " + producerRecord); } return future; }
From source file:org.springframework.web.socket.sockjs.client.SockJsClient.java
@Override public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler handler, @Nullable WebSocketHttpHeaders headers, URI url) { Assert.notNull(handler, "WebSocketHandler is required"); Assert.notNull(url, "URL is required"); String scheme = url.getScheme(); if (!supportedProtocols.contains(scheme)) { throw new IllegalArgumentException("Invalid scheme: '" + scheme + "'"); }//from www. ja v a 2s .c om SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<>(); try { SockJsUrlInfo sockJsUrlInfo = new SockJsUrlInfo(url); ServerInfo serverInfo = getServerInfo(sockJsUrlInfo, getHttpRequestHeaders(headers)); createRequest(sockJsUrlInfo, headers, serverInfo).connect(handler, connectFuture); } catch (Throwable exception) { if (logger.isErrorEnabled()) { logger.error("Initial SockJS \"Info\" request to server failed, url=" + url, exception); } connectFuture.setException(exception); } return connectFuture; }
From source file:org.springframework.web.socket.sockjs.client.WebSocketTransport.java
@Override public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) { final SettableListenableFuture<WebSocketSession> future = new SettableListenableFuture<>(); WebSocketClientSockJsSession session = new WebSocketClientSockJsSession(request, handler, future); handler = new ClientSockJsWebSocketHandler(session); request.addTimeoutTask(session.getTimeoutTask()); URI url = request.getTransportUrl(); WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHandshakeHeaders()); if (logger.isDebugEnabled()) { logger.debug("Starting WebSocket session on " + url); }//from ww w. ja v a 2 s . com this.webSocketClient.doHandshake(handler, headers, url) .addCallback(new ListenableFutureCallback<WebSocketSession>() { @Override public void onSuccess(@Nullable WebSocketSession webSocketSession) { // WebSocket session ready, SockJS Session not yet } @Override public void onFailure(Throwable ex) { future.setException(ex); } }); return future; }