List of usage examples for org.springframework.messaging Message getHeaders
MessageHeaders getHeaders();
From source file:nz.co.senanque.messaging.OrderEndpoint.java
public Message<Order> issueResponseFor(Message<Order> order) { if (order.getPayload().getOrderName().equals("fatal error")) { throw new RuntimeException("fatal error"); }//from w w w .j ava 2s .c o m if (order.getPayload().getOrderName().equals("recoverable error")) { throw new RuntimeException("recoverable error"); } Order ret = new ObjectFactory().createOrder(); OrderItem orderItem = new ObjectFactory().createOrderItem(); orderItem.setItemName("#1"); ret.setRejected(false); ret.setOrderName("whatever"); ret.getOrderItems().add(orderItem); log.debug("processed order: correlationId {}", order.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID, Long.class)); MessageBuilder<Order> messageBuilder = MessageBuilder.withPayload(ret); messageBuilder.copyHeaders(order.getHeaders()); return messageBuilder.build(); }
From source file:com.kinglcc.spring.jms.core.Jackson2PayloadArgumentResolver.java
@Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Payload ann = parameter.getParameterAnnotation(Payload.class); if (ann != null && StringUtils.hasText(ann.value())) { throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); }//from www. java2 s. c o m Object payload = message.getPayload(); boolean isGeneric = isGenericMessage(payload); if (isGeneric) { payload = ((GenericMessage) payload).getContent(); MessageBuilder<Object> builder = MessageBuilder.withPayload(payload); message = builder.copyHeadersIfAbsent(message.getHeaders()).build(); } if (isEmptyPayload(payload)) { if (ann == null || ann.required()) { bindEmptyPayloadError(parameter, message, payload); } return null; } if (isGeneric) { return convertFromMessage(parameter, message); } else { if (ClassUtils.isAssignable(parameter.getParameterType(), payload.getClass())) { validate(message, parameter, payload); return payload; } return convertFromMessage(parameter, message); } }
From source file:com.consol.citrus.samples.flightbooking.BookingSplitter.java
@Splitter @Transactional//from ww w . j a v a 2 s . c o m public Object splitMessage(Message<?> message) { List<Message<FlightBookingRequestMessage>> flightRequests = new ArrayList<Message<FlightBookingRequestMessage>>(); if (!(message.getPayload() instanceof TravelBookingRequestMessage)) { throw new IllegalStateException("Unsupported message type: " + message.getPayload().getClass()); } TravelBookingRequestMessage request = ((TravelBookingRequestMessage) message.getPayload()); //Save customer if not already present if (customerDao.find(request.getCustomer().getId()) == null) { customerDao.persist(request.getCustomer()); } for (Flight flight : request.getFlights().getFlights()) { //Save flight if necessary if (flightDao.find(flight.getFlightId()) == null) { flightDao.persist(flight); } FlightBookingRequestMessage flightRequest = new FlightBookingRequestMessage(); flightRequest.setFlight(flight); flightRequest.setCorrelationId(request.getCorrelationId()); flightRequest.setCustomer(request.getCustomer()); flightRequest.setBookingId("Bx" + bookingIndex.incrementAndGet()); MessageBuilder<FlightBookingRequestMessage> messageBuilder = MessageBuilder.withPayload(flightRequest); messageBuilder.copyHeaders(message.getHeaders()); flightRequests.add(messageBuilder.build()); } return flightRequests; }
From source file:com.qpark.eip.core.spring.PayloadLogger.java
/** * {@link Message} to string./* w w w . ja va 2 s . c o m*/ * * @param message * the {@link Message}. * @return the {@link Message} as string. */ private String getMessage(final Message<?> message) { Object logMessage = this.expression.getValue(this.evaluationContext, message); if (JAXBElement.class.isInstance(logMessage)) { final JAXBElement<?> elem = (JAXBElement<?>) logMessage; try { if (Objects.nonNull(this.jaxb2Marshaller)) { final StringResult sw = new StringResult(); this.jaxb2Marshaller.marshal(logMessage, sw); logMessage = sw.toString(); } else { final Marshaller marshaller = this.getMarshaller(); if (Objects.nonNull(marshaller)) { final StringWriter sw = new StringWriter(); marshaller.marshal(logMessage, sw); logMessage = sw.toString(); } } } catch (final Exception e) { logMessage = elem.getValue(); } } else if (logMessage instanceof Throwable) { final StringWriter stringWriter = new StringWriter(); if (logMessage instanceof AggregateMessageDeliveryException) { stringWriter.append(((Throwable) logMessage).getMessage()); for (final Exception exception : (List<? extends Exception>) ((AggregateMessageDeliveryException) logMessage) .getAggregatedExceptions()) { exception.printStackTrace(new PrintWriter(stringWriter, true)); } } else { ((Throwable) logMessage).printStackTrace(new PrintWriter(stringWriter, true)); } logMessage = stringWriter.toString(); } final StringBuffer sb = new StringBuffer(1024); sb.append(MessageHeaders.ID).append("=").append(message.getHeaders().getId()); final Object correlationId = new IntegrationMessageHeaderAccessor(message).getCorrelationId(); if (correlationId != null) { sb.append(", "); sb.append(IntegrationMessageHeaderAccessor.CORRELATION_ID).append("=").append(correlationId); } sb.append("\n"); sb.append(String.valueOf(logMessage)); return sb.toString(); }
From source file:org.eclipse.hawkbit.event.BusProtoStuffMessageConverter.java
@Override public Object convertFromInternal(final Message<?> message, final Class<?> targetClass, final Object conversionHint) { final Object payload = message.getPayload(); try {//from ww w. j av a 2 s . c om final Class<?> deserializeClass = ClassUtils .getClass(message.getHeaders().get(DEFAULT_CLASS_FIELD_NAME).toString()); if (payload instanceof byte[]) { @SuppressWarnings("unchecked") final Schema<Object> schema = (Schema<Object>) RuntimeSchema.getSchema(deserializeClass); final Object deserializeEvent = schema.newMessage(); ProtobufIOUtil.mergeFrom((byte[]) message.getPayload(), deserializeEvent, schema); return deserializeEvent; } } catch (final ClassNotFoundException e) { LOG.error("Protostuff cannot find derserialize class", e); throw new MessageConversionException(message, "Failed to read payload", e); } return null; }
From source file:org.springframework.cloud.aws.messaging.listener.QueueMessageHandler.java
@Override protected String getDestination(Message<?> message) { return message.getHeaders().get(Headers.LOGICAL_RESOURCE_ID_MESSAGE_HEADER_KEY).toString(); }
From source file:org.springframework.cloud.contract.stubrunner.messaging.integration.StubRunnerIntegrationMessageSelector.java
private boolean headersMatch(Message<?> message) { Map<String, Object> headers = message.getHeaders(); boolean matches = true; for (Header it : this.groovyDsl.getInput().getMessageHeaders().getEntries()) { String name = it.getName(); Object value = it.getClientValue(); Object valueInHeader = headers.get(name); matches &= value instanceof Pattern ? ((Pattern) value).matcher(valueInHeader.toString()).matches() : valueInHeader != null && valueInHeader.equals(value); }//from www . j av a2s . c o m return matches; }
From source file:org.springframework.cloud.contract.stubrunner.messaging.stream.StubRunnerStreamMessageSelector.java
private boolean headersMatch(Message<?> message) { Map<String, Object> headers = message.getHeaders(); for (Header it : this.groovyDsl.getInput().getMessageHeaders().getEntries()) { String name = it.getName(); Object value = it.getClientValue(); Object valueInHeader = headers.get(name); boolean matches; if (value instanceof Pattern) { Pattern pattern = (Pattern) value; matches = pattern.matcher(valueInHeader.toString()).matches(); } else {/*from w ww. j a va 2 s . com*/ matches = valueInHeader != null && valueInHeader.equals(value); } if (!matches) { return false; } } return true; }
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); }/* w w w .j a v a 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(/*from www. ja va2 s . c o m*/ "--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); } }