Java Code Examples for org.springframework.messaging.support.MessageHeaderAccessor#getAccessor()

The following examples show how to use org.springframework.messaging.support.MessageHeaderAccessor#getAccessor() . 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: DefaultStompSessionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void ack() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String messageId = "123";
	this.session.acknowledge(messageId, true);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.ACK, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 1, stompHeaders.size());
	assertEquals(messageId, stompHeaders.getId());
}
 
Example 2
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void nack() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String messageId = "123";
	this.session.acknowledge(messageId, false);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.NACK, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 1, stompHeaders.size());
	assertEquals(messageId, stompHeaders.getId());
}
 
Example 3
Source File: WebSocketStompClientTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void handleWebSocketMessageBinary() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(UTF_8)));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), UTF_8));
}
 
Example 4
Source File: DefaultStompSessionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nack() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String messageId = "123";
	this.session.acknowledge(messageId, false);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.NACK, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 1, stompHeaders.size());
	assertEquals(messageId, stompHeaders.getId());
}
 
Example 5
Source File: SimpMessagingTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void processHeadersToSend() {
	Map<String, Object> map = this.messagingTemplate.processHeadersToSend(null);

	assertNotNull(map);
	assertTrue("Actual: " + map.getClass().toString(), MessageHeaders.class.isAssignableFrom(map.getClass()));

	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor((MessageHeaders) map, SimpMessageHeaderAccessor.class);

	assertTrue(headerAccessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType());
}
 
Example 6
Source File: StompSubProtocolErrorHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Message<byte[]> handleErrorMessageToClient(Message<byte[]> errorMessage) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class);
	Assert.notNull(accessor, "Expected STOMP headers");
	if (!accessor.isMutable()) {
		accessor = StompHeaderAccessor.wrap(errorMessage);
	}
	return handleInternal(accessor, errorMessage.getPayload(), null, null);
}
 
Example 7
Source File: WebSocketStompClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 8
Source File: StompBrokerRelayMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public StompHeaderAccessor getSentHeaders(int index) {
	assertTrue("Size: " + getSentMessages().size(), getSentMessages().size() > index);
	Message<byte[]> message = getSentMessages().get(index);
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	return accessor;
}
 
Example 9
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-16844
public void afterConnectedWithSpecificVersion() {
	assertFalse(this.session.isConnected());
	this.connectHeaders.setAcceptVersion(new String[] {"1.1"});

	this.session.afterConnected(this.connection);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.CONNECT, accessor.getCommand());
	assertThat(accessor.getAcceptVersion(), containsInAnyOrder("1.1"));
}
 
Example 10
Source File: StompSubProtocolErrorHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleClientMessageProcessingError() throws Exception {

	Exception ex = new Exception("fake exception");
	Message<byte[]> actual = this.handler.handleClientMessageProcessingError(null, ex);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(actual, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertEquals(StompCommand.ERROR, accessor.getCommand());
	assertEquals(ex.getMessage(), accessor.getMessage());
	assertArrayEquals(new byte[0], actual.getPayload());
}
 
Example 11
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void handleError(WebSocketSession session, Throwable ex, @Nullable Message<byte[]> clientMessage) {
	if (getErrorHandler() == null) {
		sendErrorMessage(session, ex);
		return;
	}

	Message<byte[]> message = getErrorHandler().handleClientMessageProcessingError(clientMessage, ex);
	if (message == null) {
		return;
	}

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	Assert.state(accessor != null, "No StompHeaderAccessor");
	sendToClient(session, accessor, message.getPayload());
}
 
Example 12
Source File: SimpMessagingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void doSendWithStompHeaders() {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	accessor.setDestination("/user/queue/foo");
	Message<?> message = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());

	this.messagingTemplate.doSend("/queue/foo-user123", message);

	List<Message<byte[]>> messages = this.messageChannel.getMessages();
	Message<byte[]> sentMessage = messages.get(0);

	MessageHeaderAccessor sentAccessor = MessageHeaderAccessor.getAccessor(sentMessage, MessageHeaderAccessor.class);
	assertEquals(StompHeaderAccessor.class, sentAccessor.getClass());
	assertEquals("/queue/foo-user123", ((StompHeaderAccessor) sentAccessor).getDestination());
}
 
Example 13
Source File: AuthChannelInterceptorAdapter.java    From joal with Apache License 2.0 5 votes vote down vote up
@Override
public Message<?> preSend(final Message<?> message, final MessageChannel channel) throws AuthenticationException {
    final StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

    if (StompCommand.CONNECT == accessor.getCommand()) {
        final String username = accessor.getFirstNativeHeader(USERNAME_HEADER);
        final String authToken = accessor.getFirstNativeHeader(TOKEN_HEADER);

        final Authentication user = webSocketAuthenticatorService.getAuthenticatedOrFail(username, authToken);

        accessor.setUser(user);
    }

    return message;
}
 
Example 14
Source File: DefaultSubscriptionRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) {
	Object value;
	if (target instanceof Message) {
		value = name.equals("headers") ? ((Message) target).getHeaders() : null;
	}
	else if (target instanceof MessageHeaders) {
		MessageHeaders headers = (MessageHeaders) target;
		SimpMessageHeaderAccessor accessor =
				MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class);
		Assert.state(accessor != null, "No SimpMessageHeaderAccessor");
		if ("destination".equalsIgnoreCase(name)) {
			value = accessor.getDestination();
		}
		else {
			value = accessor.getFirstNativeHeader(name);
			if (value == null) {
				value = headers.get(name);
			}
		}
	}
	else {
		// Should never happen...
		throw new IllegalStateException("Expected Message or MessageHeaders.");
	}
	return new TypedValue(value);
}
 
Example 15
Source File: StompBrokerRelayMessageHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void handleInboundMessage(Message<?> message) {
	if (this.isRemoteClientSession) {
		StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
		accessor.setImmutable();
		StompBrokerRelayMessageHandler.this.getClientOutboundChannel().send(message);
	}
}
 
Example 16
Source File: SimpleBrokerMessageHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void logMessage(Message<?> message) {
	if (logger.isDebugEnabled()) {
		SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
		accessor = (accessor != null ? accessor : SimpMessageHeaderAccessor.wrap(message));
		logger.debug("Processing " + accessor.getShortLogMessage(message.getPayload()));
	}
}
 
Example 17
Source File: StompSubProtocolErrorHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void handleClientMessageProcessingError() throws Exception {

	Exception ex = new Exception("fake exception");
	Message<byte[]> actual = this.handler.handleClientMessageProcessingError(null, ex);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(actual, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertEquals(StompCommand.ERROR, accessor.getCommand());
	assertEquals(ex.getMessage(), accessor.getMessage());
	assertArrayEquals(new byte[0], actual.getPayload());
}
 
Example 18
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private StompHeaderAccessor getStompHeaderAccessor(Message<?> message) {
	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor instanceof StompHeaderAccessor) {
		return (StompHeaderAccessor) accessor;
	}
	else {
		StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(message);
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
		if (SimpMessageType.CONNECT_ACK.equals(messageType)) {
			stompAccessor = convertConnectAcktoStompConnected(stompAccessor);
		}
		else if (SimpMessageType.DISCONNECT_ACK.equals(messageType)) {
			String receipt = getDisconnectReceipt(stompAccessor);
			if (receipt != null) {
				stompAccessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
				stompAccessor.setReceiptId(receipt);
			}
			else {
				stompAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
				stompAccessor.setMessage("Session closed.");
			}
		}
		else if (SimpMessageType.HEARTBEAT.equals(messageType)) {
			stompAccessor = StompHeaderAccessor.createForHeartbeat();
		}
		else if (stompAccessor.getCommand() == null || StompCommand.SEND.equals(stompAccessor.getCommand())) {
			stompAccessor.updateStompCommandAsServerMessage();
		}
		return stompAccessor;
	}
}
 
Example 19
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: JwtWebSocketInterceptorAdapter.java    From spring-boot-start-current with Apache License 2.0 4 votes vote down vote up
@Override
public Message< ? > preSend ( Message< ? > message , MessageChannel channel ) {
    StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor( message , StompHeaderAccessor.class );

    if ( ObjectUtils.notEqual( StompCommand.CONNECT , accessor.getCommand() ) ) {
        return message;
    }

    final String authToken = accessor.getFirstNativeHeader( tokenHeader );

    final String username = jwtTokenUtil.getUsernameFromToken( authToken );

    LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );

    if ( StringUtils.isEmpty( username ) ) {
        throw new AuthenticationCredentialsNotFoundException( "未授权" );
    }

    if ( SecurityContextHolder.getContext().getAuthentication() == null ) {
        // 对于简单的验证,只需检查令牌的完整性即可。 您不必强制调用数据库。 由你自己决定
        // 是否查询数据看情况,目前是查询数据库
        UserDetails userDetails = this.userDetailsService.loadUserByUsername( username );
        if ( jwtTokenUtil.validateToken( authToken , userDetails ) ) {
            UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken( userDetails , null , userDetails.getAuthorities() );

            // authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) );

            LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );

            LogUtils.getLogger().debug( "该 " + username + "用户已认证WebSocket, 设置安全上下文" );

            SecurityContextHolder.getContext().setAuthentication( authentication );
            accessor.setUser( authentication );
        }
    }

    if ( Objects.isNull( accessor.getUser() ) ) {
        throw new AuthenticationCredentialsNotFoundException( "未授权" );
    }

    return message;
}