List of usage examples for org.springframework.messaging Message getPayload
T getPayload();
From source file:org.springframework.messaging.simp.stomp.StompWebSocketHandler.java
/** * Handle incoming WebSocket messages from clients. *///from w w w . jav a 2 s. c o m @Override protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) { try { String payload = textMessage.getPayload(); Message<?> message = this.stompMessageConverter.toMessage(payload); // TODO: validate size limits // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits if (logger.isTraceEnabled()) { logger.trace("Processing STOMP message: " + message); } try { StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); headers.setSessionId(session.getId()); headers.setUser(session.getPrincipal()); message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); if (SimpMessageType.CONNECT.equals(headers.getMessageType())) { handleConnect(session, message); } this.dispatchChannel.send(message); } catch (Throwable t) { logger.error("Terminating STOMP session due to failure to send message: ", t); sendErrorMessage(session, t); } // TODO: send RECEIPT message if incoming message has "receipt" header // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt } catch (Throwable error) { sendErrorMessage(session, error); } }
From source file:org.springframework.messaging.simp.stomp.StompWebSocketHandler.java
/** * Handle STOMP messages going back out to WebSocket clients. *///from ww w . ja v a 2 s. c o m @Override public void handleMessage(Message<?> message) { StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); headers.setCommandIfNotSet(StompCommand.MESSAGE); if (StompCommand.CONNECTED.equals(headers.getCommand())) { // Ignore for now since we already sent it return; } String sessionId = headers.getSessionId(); if (sessionId == null) { // TODO: failed message delivery mechanism logger.error("Ignoring message, no sessionId header: " + message); return; } WebSocketSession session = this.sessions.get(sessionId); if (session == null) { // TODO: failed message delivery mechanism logger.error("Ignoring message, sessionId not found: " + message); return; } if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) { // TODO: failed message delivery mechanism logger.error("Ignoring message, no subscriptionId header: " + message); return; } if (!(message.getPayload() instanceof byte[])) { // TODO: failed message delivery mechanism logger.error("Ignoring message, expected byte[] content: " + message); return; } try { message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); byte[] bytes = this.stompMessageConverter.fromMessage(message); session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); } catch (Throwable t) { sendErrorMessage(session, t); } finally { if (StompCommand.ERROR.equals(headers.getCommand())) { try { session.close(CloseStatus.PROTOCOL_ERROR); } catch (IOException e) { } } } }
From source file:org.springframework.messaging.simp.user.UserDestinationMessageHandler.java
@Override public void handleMessage(Message<?> message) throws MessagingException { Message<?> messageToUse = message; if (this.broadcastHandler != null) { messageToUse = this.broadcastHandler.preHandle(message); if (messageToUse == null) { return; }//from w w w . j a va 2 s.c o m } UserDestinationResult result = this.destinationResolver.resolveDestination(messageToUse); if (result == null) { return; } if (result.getTargetDestinations().isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("No active sessions for user destination: " + result.getSourceDestination()); } if (this.broadcastHandler != null) { this.broadcastHandler.handleUnresolved(messageToUse); } return; } SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(messageToUse); initHeaders(accessor); accessor.setNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, result.getSubscribeDestination()); accessor.setLeaveMutable(true); messageToUse = MessageBuilder.createMessage(messageToUse.getPayload(), accessor.getMessageHeaders()); if (logger.isTraceEnabled()) { logger.trace("Translated " + result.getSourceDestination() + " -> " + result.getTargetDestinations()); } for (String target : result.getTargetDestinations()) { this.messagingTemplate.send(target, messageToUse); } }
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);/*from ww w .j av a 2 s .c om*/ 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 a v a 2 s .co 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:org.springframework.samples.portfolio.web.standalone.StandalonePortfolioControllerTests.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.withPayload(new byte[0]).setHeaders(headers).build(); this.annotationMethodMessageHandler.handleMessage(message); assertEquals(1, this.clientOutboundChannel.getMessages().size()); Message<?> reply = this.clientOutboundChannel.getMessages().get(0); 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.statemachine.state.AbstractState.java
@Override public boolean shouldDefer(Message<E> event) { return deferred.contains(event.getPayload()); }
From source file:org.springframework.statemachine.support.AbstractStateMachine.java
protected synchronized boolean acceptEvent(Message<E> message) { if ((currentState != null && currentState.shouldDefer(message))) { log.info("Current state " + currentState + " deferred event " + message); stateMachineExecutor.queueDeferredEvent(message); return true; }//from w w w . j av a2s . c o m if ((currentState != null && currentState.sendEvent(message))) { return true; } if (log.isDebugEnabled()) { log.debug("Queue event " + message + " " + this); } for (Transition<S, E> transition : transitions) { State<S, E> source = transition.getSource(); Trigger<S, E> trigger = transition.getTrigger(); if (StateMachineUtils.containsAtleastOne(source.getIds(), currentState.getIds())) { if (trigger != null && trigger.evaluate(new DefaultTriggerContext<S, E>(message.getPayload()))) { stateMachineExecutor.queueEvent(message); return true; } } } // if we're about to not accept event, check defer again in case // state was changed between original check and now if ((currentState != null && currentState.shouldDefer(message))) { log.info("Current state " + currentState + " deferred event " + message); stateMachineExecutor.queueDeferredEvent(message); return true; } return false; }
From source file:org.springframework.statemachine.support.DefaultStateMachineExecutor.java
private boolean processEventQueue() { if (log.isDebugEnabled()) { log.debug("Process event queue, size=" + eventQueue.size()); }/*ww w . j a v a 2s .co m*/ Message<E> queuedEvent = eventQueue.poll(); State<S, E> currentState = stateMachine.getState(); if (queuedEvent != null) { if ((currentState != null && currentState.shouldDefer(queuedEvent))) { log.info("Current state " + currentState + " deferred event " + queuedEvent); queueDeferredEvent(queuedEvent); return true; } for (Transition<S, E> transition : transitions) { State<S, E> source = transition.getSource(); Trigger<S, E> trigger = transition.getTrigger(); if (StateMachineUtils.containsAtleastOne(source.getIds(), currentState.getIds())) { if (trigger != null && trigger.evaluate(new DefaultTriggerContext<S, E>(queuedEvent.getPayload()))) { queueTrigger(trigger, queuedEvent); return true; } } } } return false; }
From source file:org.springframework.statemachine.support.DefaultStateMachineExecutor.java
private synchronized boolean processDeferList() { if (log.isDebugEnabled()) { log.debug("Process defer list, size=" + deferList.size()); }/*from ww w . java 2s. c om*/ ListIterator<Message<E>> iterator = deferList.listIterator(); State<S, E> currentState = stateMachine.getState(); while (iterator.hasNext()) { Message<E> event = iterator.next(); if (currentState.shouldDefer(event)) { // if current state still defers, just continue with others continue; } for (Transition<S, E> transition : transitions) { State<S, E> source = transition.getSource(); Trigger<S, E> trigger = transition.getTrigger(); if (source.equals(currentState)) { if (trigger != null && trigger.evaluate(new DefaultTriggerContext<S, E>(event.getPayload()))) { triggerQueue.add(new TriggerQueueItem(trigger, event)); iterator.remove(); // bail out when first deferred message is causing a trigger to fire return true; } } } } return false; }