List of usage examples for org.springframework.messaging.simp.stomp StompHeaderAccessor setSessionAttributes
public void setSessionAttributes(@Nullable Map<String, Object> attributes)
From source file:org.springframework.samples.portfolio.web.standalone.StandalonePortfolioControllerTests.java
@Test public void executeTrade() throws Exception { Trade trade = new Trade(); trade.setAction(Trade.TradeAction.Buy); trade.setTicker("DELL"); trade.setShares(25);/*from w w w .ja v a 2 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.withPayload(payload).setHeaders(headers).build(); this.annotationMethodMessageHandler.handleMessage(message); assertEquals(1, this.tradeService.getTrades().size()); Trade actual = this.tradeService.getTrades().get(0); assertEquals(Trade.TradeAction.Buy, actual.getAction()); assertEquals("DELL", actual.getTicker()); assertEquals(25, actual.getShares()); assertEquals("fabrice", actual.getUsername()); }
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.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 w ww. j av a 2s . 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: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);/* w w w .ja v a2s. 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.web.socket.messaging.StompSubProtocolHandler.java
/** * Handle incoming WebSocket messages from clients. *//*from w ww . jav a 2s .com*/ public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) { List<Message<byte[]>> messages; try { ByteBuffer byteBuffer; if (webSocketMessage instanceof TextMessage) { byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes()); } else if (webSocketMessage instanceof BinaryMessage) { byteBuffer = ((BinaryMessage) webSocketMessage).getPayload(); } else { return; } BufferingStompDecoder decoder = this.decoders.get(session.getId()); if (decoder == null) { throw new IllegalStateException("No decoder for session id '" + session.getId() + "'"); } messages = decoder.decode(byteBuffer); if (messages.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Incomplete STOMP frame content received in session " + session + ", bufferSize=" + decoder.getBufferSize() + ", bufferSizeLimit=" + decoder.getBufferSizeLimit() + "."); } return; } } catch (Throwable ex) { if (logger.isErrorEnabled()) { logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex); } handleError(session, ex, null); return; } for (Message<byte[]> message : messages) { try { StompHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.state(headerAccessor != null, "No StompHeaderAccessor"); headerAccessor.setSessionId(session.getId()); headerAccessor.setSessionAttributes(session.getAttributes()); headerAccessor.setUser(getUser(session)); headerAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, headerAccessor.getHeartbeat()); if (!detectImmutableMessageInterceptor(outputChannel)) { headerAccessor.setImmutable(); } if (logger.isTraceEnabled()) { logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload())); } StompCommand command = headerAccessor.getCommand(); boolean isConnect = StompCommand.CONNECT.equals(command); if (isConnect) { this.stats.incrementConnectCount(); } else if (StompCommand.DISCONNECT.equals(command)) { this.stats.incrementDisconnectCount(); } try { SimpAttributesContextHolder.setAttributesFromMessage(message); boolean sent = outputChannel.send(message); if (sent) { if (isConnect) { Principal user = headerAccessor.getUser(); if (user != null && user != session.getPrincipal()) { this.stompAuthentications.put(session.getId(), user); } } if (this.eventPublisher != null) { Principal user = getUser(session); if (isConnect) { publishEvent(this.eventPublisher, new SessionConnectEvent(this, message, user)); } else if (StompCommand.SUBSCRIBE.equals(command)) { publishEvent(this.eventPublisher, new SessionSubscribeEvent(this, message, user)); } else if (StompCommand.UNSUBSCRIBE.equals(command)) { publishEvent(this.eventPublisher, new SessionUnsubscribeEvent(this, message, user)); } } } } finally { SimpAttributesContextHolder.resetAttributes(); } } catch (Throwable ex) { if (logger.isErrorEnabled()) { logger.error("Failed to send client message to application via MessageChannel" + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex); } handleError(session, ex, message); } } }
From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java
private Message<byte[]> createDisconnectMessage(WebSocketSession session) { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.DISCONNECT); if (getHeaderInitializer() != null) { getHeaderInitializer().initHeaders(headerAccessor); }//from www. ja v a2s . c om headerAccessor.setSessionId(session.getId()); headerAccessor.setSessionAttributes(session.getAttributes()); Principal user = getUser(session); if (user != null) { headerAccessor.setUser(user); } return MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders()); }