List of usage examples for org.springframework.messaging.support MessageBuilder createMessage
@SuppressWarnings("unchecked") public static <T> Message<T> createMessage(@Nullable T payload, MessageHeaders messageHeaders)
From source file:org.openwms.common.comm.synq.TimesyncHandler.java
/** * Builds response message with the current time and the same request header to preserve header information (seq. number etc.) in post * transformation steps./*w w w . j a va 2 s. c o m*/ * * @param timesyncRequest the request * @return the response */ @Override public Message<TimesyncResponse> apply(Message<TimesyncRequest> timesyncRequest) { return MessageBuilder.createMessage(new TimesyncResponse(), timesyncRequest.getHeaders()); }
From source file:org.springframework.samples.portfolio.web.context.ContextPortfolioControllerTests.java
@Test public void getPositions() throws Exception { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE); headers.setSubscriptionId("0"); headers.setDestination("/app/positions"); headers.setSessionId("0"); headers.setUser(new TestPrincipal("fabrice")); headers.setSessionAttributes(new HashMap<String, Object>()); Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); this.clientOutboundChannelInterceptor.setIncludedDestinations("/app/positions"); this.clientOutboundChannelInterceptor.startRecording(); this.clientInboundChannel.send(message); Message<?> reply = this.clientOutboundChannelInterceptor.awaitMessage(5); assertNotNull(reply);//ww w.j a v a 2 s . co m StompHeaderAccessor replyHeaders = StompHeaderAccessor.wrap(reply); assertEquals("0", replyHeaders.getSessionId()); assertEquals("0", replyHeaders.getSubscriptionId()); assertEquals("/app/positions", replyHeaders.getDestination()); String json = new String((byte[]) reply.getPayload(), Charset.forName("UTF-8")); new JsonPathExpectationsHelper("$[0].company").assertValue(json, "Citrix Systems, Inc."); new JsonPathExpectationsHelper("$[1].company").assertValue(json, "Dell Inc."); new JsonPathExpectationsHelper("$[2].company").assertValue(json, "Microsoft"); new JsonPathExpectationsHelper("$[3].company").assertValue(json, "Oracle"); }
From source file:org.springframework.samples.portfolio.web.context.ContextPortfolioControllerTests.java
@Test public void executeTrade() throws Exception { Trade trade = new Trade(); trade.setAction(Trade.TradeAction.Buy); trade.setTicker("DELL"); trade.setShares(25);/*from ww w. j ava2 s . c o m*/ byte[] payload = new ObjectMapper().writeValueAsBytes(trade); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND); headers.setDestination("/app/trade"); headers.setSessionId("0"); headers.setUser(new TestPrincipal("fabrice")); headers.setSessionAttributes(new HashMap<String, Object>()); Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.brokerChannelInterceptor.setIncludedDestinations("/user/**"); this.brokerChannelInterceptor.startRecording(); this.clientInboundChannel.send(message); Message<?> positionUpdate = this.brokerChannelInterceptor.awaitMessage(5); assertNotNull(positionUpdate); StompHeaderAccessor positionUpdateHeaders = StompHeaderAccessor.wrap(positionUpdate); assertEquals("/user/fabrice/queue/position-updates", positionUpdateHeaders.getDestination()); String json = new String((byte[]) positionUpdate.getPayload(), Charset.forName("UTF-8")); new JsonPathExpectationsHelper("$.ticker").assertValue(json, "DELL"); new JsonPathExpectationsHelper("$.shares").assertValue(json, 75); }
From source file:com.qpark.eip.core.sftp.SftpGatewayImpl.java
/** * @see com.qpark.eip.core.sftp.SftpGateway#save(java.io.File, * java.lang.String)/*from w w w . jav a 2 s . c o m*/ */ @Override public boolean save(final File file, final String remoteDirectory) throws Exception { boolean success = false; final Map<String, Object> headers = new HashMap<>(); headers.put("directory", ""); final Message<File> message = MessageBuilder.createMessage(file, new MessageHeaders(headers)); if (!this.template.exists(remoteDirectory)) { this.mkdir(remoteDirectory); } this.logger.debug("save {} {}", remoteDirectory, file.getName()); final String remotePath = this.template.send(message, remoteDirectory, FileExistsMode.REPLACE); if (remotePath != null) { success = true; } return success; }
From source file:org.springframework.cloud.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java
@Test public void sendAndReceiveMessageAsString() { this.contextRunner.run((context) -> { try {/*from w ww.j ava 2 s . com*/ Map<String, Object> headers = new HashMap<>(); // Only String values for now.. headers.put("storm", "lift your skinny fists"); headers.put("static", "lift your skinny fists"); headers.put("sleep", "lift your skinny fists"); Message originalMessage = MessageBuilder.createMessage("I am a message.".getBytes(), new MessageHeaders(headers)); context.getBean("inputChannel", MessageChannel.class).send(originalMessage); Message<?> message = context.getBean("outputChannel", PollableChannel.class).receive(5000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isInstanceOf(byte[].class); String payload = new String((byte[]) message.getPayload()); assertThat(payload).isEqualTo("I am a message."); assertThat(message.getHeaders().size()).isEqualTo(6); assertThat(message.getHeaders().get("storm")).isEqualTo("lift your skinny fists"); assertThat(message.getHeaders().get("static")).isEqualTo("lift your skinny fists"); assertThat(message.getHeaders().get("sleep")).isEqualTo("lift your skinny fists"); assertThat(message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE)).isNotNull(); } finally { PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class); pubSubAdmin.deleteSubscription((String) context.getBean("subscriptionName")); pubSubAdmin.deleteTopic((String) context.getBean("topicName")); } }); }
From source file:org.springframework.kafka.support.converter.BatchMessagingMessageConverter.java
@Override public Message<?> toMessage(List<ConsumerRecord<?, ?>> records, Acknowledgment acknowledgment, Consumer<?, ?> consumer, Type type) { KafkaMessageHeaders kafkaMessageHeaders = new KafkaMessageHeaders(this.generateMessageId, this.generateTimestamp); Map<String, Object> rawHeaders = kafkaMessageHeaders.getRawHeaders(); List<Object> payloads = new ArrayList<>(); List<Object> keys = new ArrayList<>(); List<String> topics = new ArrayList<>(); List<Integer> partitions = new ArrayList<>(); List<Long> offsets = new ArrayList<>(); List<String> timestampTypes = new ArrayList<>(); List<Long> timestamps = new ArrayList<>(); List<Map<String, Object>> convertedHeaders = new ArrayList<>(); List<Headers> natives = new ArrayList<>(); rawHeaders.put(KafkaHeaders.RECEIVED_MESSAGE_KEY, keys); rawHeaders.put(KafkaHeaders.RECEIVED_TOPIC, topics); rawHeaders.put(KafkaHeaders.RECEIVED_PARTITION_ID, partitions); rawHeaders.put(KafkaHeaders.OFFSET, offsets); rawHeaders.put(KafkaHeaders.TIMESTAMP_TYPE, timestampTypes); rawHeaders.put(KafkaHeaders.RECEIVED_TIMESTAMP, timestamps); if (this.headerMapper != null) { rawHeaders.put(KafkaHeaders.BATCH_CONVERTED_HEADERS, convertedHeaders); } else {//from ww w . j a va2s . c o m rawHeaders.put(KafkaHeaders.NATIVE_HEADERS, natives); } if (acknowledgment != null) { rawHeaders.put(KafkaHeaders.ACKNOWLEDGMENT, acknowledgment); } if (consumer != null) { rawHeaders.put(KafkaHeaders.CONSUMER, consumer); } boolean logged = false; for (ConsumerRecord<?, ?> record : records) { payloads.add(this.recordConverter == null || !containerType(type) ? extractAndConvertValue(record, type) : convert(record, type)); keys.add(record.key()); topics.add(record.topic()); partitions.add(record.partition()); offsets.add(record.offset()); timestampTypes.add(record.timestampType().name()); timestamps.add(record.timestamp()); if (this.headerMapper != null) { Map<String, Object> converted = new HashMap<>(); this.headerMapper.toHeaders(record.headers(), converted); convertedHeaders.add(converted); } else { if (this.logger.isDebugEnabled() && !logged) { this.logger.debug("No header mapper is available; Jackson is required for the default mapper; " + "headers (if present) are not mapped but provided raw in " + KafkaHeaders.NATIVE_HEADERS); logged = true; } natives.add(record.headers()); } } return MessageBuilder.createMessage(payloads, kafkaMessageHeaders); }
From source file:org.springframework.kafka.support.converter.MessagingMessageConverter.java
@Override public Message<?> toMessage(ConsumerRecord<?, ?> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer, Type type) {/* w ww . j av a 2s. c o m*/ KafkaMessageHeaders kafkaMessageHeaders = new KafkaMessageHeaders(this.generateMessageId, this.generateTimestamp); Map<String, Object> rawHeaders = kafkaMessageHeaders.getRawHeaders(); if (this.headerMapper != null) { this.headerMapper.toHeaders(record.headers(), rawHeaders); } else { if (this.logger.isDebugEnabled()) { this.logger.debug("No header mapper is available; Jackson is required for the default mapper; " + "headers (if present) are not mapped but provided raw in " + KafkaHeaders.NATIVE_HEADERS); } rawHeaders.put(KafkaHeaders.NATIVE_HEADERS, record.headers()); } rawHeaders.put(KafkaHeaders.RECEIVED_MESSAGE_KEY, record.key()); rawHeaders.put(KafkaHeaders.RECEIVED_TOPIC, record.topic()); rawHeaders.put(KafkaHeaders.RECEIVED_PARTITION_ID, record.partition()); rawHeaders.put(KafkaHeaders.OFFSET, record.offset()); rawHeaders.put(KafkaHeaders.TIMESTAMP_TYPE, record.timestampType().name()); rawHeaders.put(KafkaHeaders.RECEIVED_TIMESTAMP, record.timestamp()); if (acknowledgment != null) { rawHeaders.put(KafkaHeaders.ACKNOWLEDGMENT, acknowledgment); } if (consumer != null) { rawHeaders.put(KafkaHeaders.CONSUMER, consumer); } return MessageBuilder.createMessage(extractAndConvertValue(record, type), kafkaMessageHeaders); }
From source file:org.springframework.messaging.converter.AbstractMessageConverter.java
@Override @Nullable/*from ww w. j a v a 2 s. c o m*/ public final Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) { if (!canConvertTo(payload, headers)) { return null; } Object payloadToUse = convertToInternal(payload, headers, conversionHint); if (payloadToUse == null) { return null; } MimeType mimeType = getDefaultContentType(payloadToUse); if (headers != null) { MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class); if (accessor != null && accessor.isMutable()) { if (mimeType != null) { accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType); } return MessageBuilder.createMessage(payloadToUse, accessor.getMessageHeaders()); } } MessageBuilder<?> builder = MessageBuilder.withPayload(payloadToUse); if (headers != null) { builder.copyHeaders(headers); } if (mimeType != null) { builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType); } return builder.build(); }
From source file:org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.java
@Override public void handleMessage(Message<?> message) throws MessagingException { String destination = getDestination(message); if (destination == null) { return;/*from ww w. j a v a 2 s .com*/ } String lookupDestination = getLookupDestination(destination); if (lookupDestination == null) { return; } MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getMutableAccessor(message); headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, lookupDestination); headerAccessor.setLeaveMutable(true); message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders()); if (logger.isDebugEnabled()) { logger.debug("Searching methods to handle " + headerAccessor.getShortLogMessage(message.getPayload()) + ", lookupDestination='" + lookupDestination + "'"); } handleMessageInternal(message, lookupDestination); headerAccessor.setImmutable(); }
From source file:org.springframework.messaging.simp.broker.OrderedMessageSenderTests.java
@Test public void test() throws InterruptedException { int start = 1; int end = 1000; AtomicInteger index = new AtomicInteger(start); AtomicReference<Object> result = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); this.channel.subscribe(message -> { int expected = index.getAndIncrement(); Integer actual = (Integer) message.getHeaders().getOrDefault("seq", -1); if (actual != expected) { result.set("Expected: " + expected + ", but was: " + actual); latch.countDown();//from w w w .j a va 2 s . c o m return; } if (actual == 100 || actual == 200) { try { Thread.sleep(200); } catch (InterruptedException ex) { result.set(ex.toString()); latch.countDown(); } } if (actual == end) { result.set("Done"); latch.countDown(); } }); for (int i = start; i <= end; i++) { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); accessor.setHeader("seq", i); accessor.setLeaveMutable(true); this.sender.send(MessageBuilder.createMessage("payload", accessor.getMessageHeaders())); } latch.await(10, TimeUnit.SECONDS); assertEquals("Done", result.get()); }