Java Code Examples for org.springframework.messaging.Message#getPayload()
The following examples show how to use
org.springframework.messaging.Message#getPayload() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericMessageConverter.java From rqueue with Apache License 2.0 | 6 votes |
/** * Convert the payload of a {@link Message} from a serialized form to a typed Object of type * stored in message it self. * * <p>If the converter cannot perform the conversion it returns {@code null}. * * @param message the input message * @param targetClass the target class for the conversion * @return the result of the conversion, or {@code null} if the converter cannot perform the * conversion. */ @Override public Object fromMessage(Message<?> message, Class<?> targetClass) { try { String payload = (String) message.getPayload(); if (SerializationUtils.isJson(payload)) { Msg msg = objectMapper.readValue(payload, Msg.class); Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(msg.getName()); return objectMapper.readValue(msg.msg, c); } } catch (IOException | ClassCastException | ClassNotFoundException e) { log.warn("Exception", e); } return null; }
Example 2
Source File: DefaultStompSession.java From java-technology-stack with MIT License | 6 votes |
private void invokeHandler(StompFrameHandler handler, Message<byte[]> message, StompHeaders headers) { if (message.getPayload().length == 0) { handler.handleFrame(headers, null); return; } Type payloadType = handler.getPayloadType(headers); Class<?> resolvedType = ResolvableType.forType(payloadType).resolve(); if (resolvedType == null) { throw new MessageConversionException("Unresolvable payload type [" + payloadType + "] from handler type [" + handler.getClass() + "]"); } Object object = getMessageConverter().fromMessage(message, resolvedType); if (object == null) { throw new MessageConversionException("No suitable converter for payload type [" + payloadType + "] from handler type [" + handler.getClass() + "]"); } handler.handleFrame(headers, object); }
Example 3
Source File: WebSocketTransport.java From WeEvent with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private void handleMessageFrame(StompHeaderAccessor stompHeaderAccessor, Message<byte[]> stompMsg) { String subscriptionId = stompHeaderAccessor.getFirstNativeHeader("subscription-id"); // custom properties, eventId is in native header Map<String, String> extensions = new HashMap<>(); for (Map.Entry<String, List<String>> entry : ((Map<String, List<String>>) stompMsg.getHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).entrySet()) { if (entry.getKey().startsWith("weevent-")) { extensions.put(entry.getKey(), entry.getValue().get(0)); } } WeEvent event = new WeEvent(stompHeaderAccessor.getDestination(), stompMsg.getPayload(), extensions); event.setEventId(stompHeaderAccessor.getFirstNativeHeader("eventId")); log.info("received: {}", event); if (this.subscription2EventCache.containsKey(subscriptionId)) { IWeEventClient.EventListener listener = this.subscription2EventCache.get(subscriptionId).getSecond(); listener.onEvent(event); // update the cache eventId this.subscription2EventCache.get(subscriptionId).getFirst().setOffset(event.getEventId()); } }
Example 4
Source File: DefaultStompSession.java From spring-analysis-note with MIT License | 6 votes |
private void invokeHandler(StompFrameHandler handler, Message<byte[]> message, StompHeaders headers) { if (message.getPayload().length == 0) { handler.handleFrame(headers, null); return; } Type payloadType = handler.getPayloadType(headers); Class<?> resolvedType = ResolvableType.forType(payloadType).resolve(); if (resolvedType == null) { throw new MessageConversionException("Unresolvable payload type [" + payloadType + "] from handler type [" + handler.getClass() + "]"); } Object object = getMessageConverter().fromMessage(message, resolvedType); if (object == null) { throw new MessageConversionException("No suitable converter for payload type [" + payloadType + "] from handler type [" + handler.getClass() + "]"); } handler.handleFrame(headers, object); }
Example 5
Source File: PayloadMethodArgumentResolver.java From spring-analysis-note with MIT License | 6 votes |
@SuppressWarnings("unchecked") private Flux<DataBuffer> extractContent(MethodParameter parameter, Message<?> message) { Object payload = message.getPayload(); if (payload instanceof DataBuffer) { return Flux.just((DataBuffer) payload); } if (payload instanceof Publisher) { return Flux.from((Publisher<?>) payload).map(value -> { if (value instanceof DataBuffer) { return (DataBuffer) value; } String className = value.getClass().getName(); throw getUnexpectedPayloadError(message, parameter, "Publisher<" + className + ">"); }); } return Flux.error(getUnexpectedPayloadError(message, parameter, payload.getClass().getName())); }
Example 6
Source File: StompDecoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void decodeFrameWithInvalidContentLength() { Message<byte[]> message = decode("SEND\ncontent-length:-1\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(1, headers.toNativeHeaderMap().size()); assertEquals(Integer.valueOf(-1), headers.getContentLength()); String bodyText = new String(message.getPayload()); assertEquals("The body of the message", bodyText); }
Example 7
Source File: StompDecoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void decodeFrame() throws UnsupportedEncodingException { Message<byte[]> frame = decode("SEND\ndestination:test\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(headers.toNativeHeaderMap().toString(), 1, headers.toNativeHeaderMap().size()); assertEquals("test", headers.getDestination()); String bodyText = new String(frame.getPayload()); assertEquals("The body of the message", bodyText); }
Example 8
Source File: SendToMethodReturnValueHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void jsonView() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; Message<?> inputMessage = createMessage(sessionId, "sub1", "/app", "/dest", null); this.jsonHandler.handleReturnValue(handleAndSendToJsonView(), this.jsonViewReturnType, inputMessage); verify(this.messageChannel).send(this.messageCaptor.capture()); Message<?> message = this.messageCaptor.getValue(); assertNotNull(message); String bytes = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); assertEquals("{\"withView1\":\"with\"}", bytes); }
Example 9
Source File: StompDecoderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void decodeFrameWithContentLengthZero() { Message<byte[]> frame = decode("SEND\ncontent-length:0\n\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(1, headers.toNativeHeaderMap().size()); assertEquals(Integer.valueOf(0), headers.getContentLength()); String bodyText = new String(frame.getPayload()); assertEquals("", bodyText); }
Example 10
Source File: WebSocketStompClient.java From spring-analysis-note with MIT License | 5 votes |
public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor, "No StompHeaderAccessor available"); byte[] payload = message.getPayload(); byte[] bytes = ENCODER.encode(accessor.getMessageHeaders(), payload); boolean useBinary = (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); return (useBinary ? new BinaryMessage(bytes) : new TextMessage(bytes)); }
Example 11
Source File: MarshallingMessageConverterTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void toMessage() throws Exception { MyBean payload = new MyBean(); payload.setName("Foo"); Message<?> message = this.converter.toMessage(payload, null); assertNotNull(message); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); assertThat(actual, isSimilarTo("<myBean><name>Foo</name></myBean>").withDifferenceEvaluator(ev)); }
Example 12
Source File: MappingJackson2MessageConverter.java From java-technology-stack with MIT License | 5 votes |
@Override @Nullable protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { JavaType javaType = getJavaType(targetClass, conversionHint); Object payload = message.getPayload(); Class<?> view = getSerializationView(conversionHint); // Note: in the view case, calling withType instead of forType for compatibility with Jackson <2.5 try { if (payload instanceof byte[]) { if (view != null) { return this.objectMapper.readerWithView(view).forType(javaType).readValue((byte[]) payload); } else { return this.objectMapper.readValue((byte[]) payload, javaType); } } else { if (view != null) { return this.objectMapper.readerWithView(view).forType(javaType).readValue(payload.toString()); } else { return this.objectMapper.readValue(payload.toString(), javaType); } } } catch (IOException ex) { throw new MessageConversionException(message, "Could not read JSON: " + ex.getMessage(), ex); } }
Example 13
Source File: StompDecoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void decodeFrameWithContentLengthZero() { Message<byte[]> frame = decode("SEND\ncontent-length:0\n\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(1, headers.toNativeHeaderMap().size()); assertEquals(Integer.valueOf(0), headers.getContentLength()); String bodyText = new String(frame.getPayload()); assertEquals("", bodyText); }
Example 14
Source File: SendToMethodReturnValueHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void jsonView() throws Exception { given(this.messageChannel.send(any(Message.class))).willReturn(true); String sessionId = "sess1"; Message<?> inputMessage = createMessage(sessionId, "sub1", "/app", "/dest", null); this.jsonHandler.handleReturnValue(handleAndSendToJsonView(), this.jsonViewReturnType, inputMessage); verify(this.messageChannel).send(this.messageCaptor.capture()); Message<?> message = this.messageCaptor.getValue(); assertNotNull(message); String bytes = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); assertEquals("{\"withView1\":\"with\"}", bytes); }
Example 15
Source File: MappingJackson2MessageConverter.java From spring-analysis-note with MIT License | 5 votes |
@Override @Nullable protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { JavaType javaType = getJavaType(targetClass, conversionHint); Object payload = message.getPayload(); Class<?> view = getSerializationView(conversionHint); // Note: in the view case, calling withType instead of forType for compatibility with Jackson <2.5 try { if (payload instanceof byte[]) { if (view != null) { return this.objectMapper.readerWithView(view).forType(javaType).readValue((byte[]) payload); } else { return this.objectMapper.readValue((byte[]) payload, javaType); } } else if (targetClass.isInstance(payload)) { return payload; } else { if (view != null) { return this.objectMapper.readerWithView(view).forType(javaType).readValue(payload.toString()); } else { return this.objectMapper.readValue(payload.toString(), javaType); } } } catch (IOException ex) { throw new MessageConversionException(message, "Could not read JSON: " + ex.getMessage(), ex); } }
Example 16
Source File: StompDecoderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void decodeFrame() throws UnsupportedEncodingException { Message<byte[]> frame = decode("SEND\ndestination:test\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(headers.toNativeHeaderMap().toString(), 1, headers.toNativeHeaderMap().size()); assertEquals("test", headers.getDestination()); String bodyText = new String(frame.getPayload()); assertEquals("The body of the message", bodyText); }
Example 17
Source File: StompDecoderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void decodeFrameWithNullOctectsInTheBody() { Message<byte[]> frame = decode("SEND\ncontent-length:23\n\nThe b\0dy \0f the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); assertEquals(StompCommand.SEND, headers.getCommand()); assertEquals(1, headers.toNativeHeaderMap().size()); assertEquals(Integer.valueOf(23), headers.getContentLength()); String bodyText = new String(frame.getPayload()); assertEquals("The b\0dy \0f the message", bodyText); }
Example 18
Source File: MessageBuilder.java From spring-analysis-note with MIT License | 4 votes |
private MessageBuilder(Message<T> originalMessage) { Assert.notNull(originalMessage, "Message must not be null"); this.payload = originalMessage.getPayload(); this.originalMessage = originalMessage; this.headerAccessor = new MessageHeaderAccessor(originalMessage); }
Example 19
Source File: MessagingMessageListenerAdapterTests.java From spring-analysis-note with MIT License | 4 votes |
public JmsResponse<String> replyPayloadNoDestination(Message<String> input) { return new JmsResponse<>(input.getPayload(), null); }
Example 20
Source File: StompSubProtocolHandler.java From spring-analysis-note with MIT License | 4 votes |
/** * Handle STOMP messages going back out to WebSocket clients. */ @Override @SuppressWarnings("unchecked") public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message.getPayload() instanceof byte[])) { if (logger.isErrorEnabled()) { logger.error("Expected byte[] payload. Ignoring " + message + "."); } return; } StompHeaderAccessor accessor = getStompHeaderAccessor(message); StompCommand command = accessor.getCommand(); if (StompCommand.MESSAGE.equals(command)) { if (accessor.getSubscriptionId() == null && logger.isWarnEnabled()) { logger.warn("No STOMP \"subscription\" header in " + message); } String origDestination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); if (origDestination != null) { accessor = toMutableAccessor(accessor, message); accessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION); accessor.setDestination(origDestination); } } else if (StompCommand.CONNECTED.equals(command)) { this.stats.incrementConnectedCount(); accessor = afterStompSessionConnected(message, accessor, session); if (this.eventPublisher != null) { try { SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); SimpAttributesContextHolder.setAttributes(simpAttributes); Principal user = getUser(session); publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user)); } finally { SimpAttributesContextHolder.resetAttributes(); } } } byte[] payload = (byte[]) message.getPayload(); if (StompCommand.ERROR.equals(command) && getErrorHandler() != null) { Message<byte[]> errorMessage = getErrorHandler().handleErrorMessageToClient((Message<byte[]>) message); if (errorMessage != null) { accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); Assert.state(accessor != null, "No StompHeaderAccessor"); payload = errorMessage.getPayload(); } } sendToClient(session, accessor, payload); }