Java Code Examples for org.springframework.messaging.simp.stomp.StompHeaderAccessor#getFirstNativeHeader()

The following examples show how to use org.springframework.messaging.simp.stomp.StompHeaderAccessor#getFirstNativeHeader() . 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: WebSocketTransport.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public String stompSubscribe(TopicContent topic, IWeEventClient.EventListener listener) throws BrokerException {
    WeEventStompCommand stompCommand = new WeEventStompCommand();
    Long asyncSeq = this.sequence.incrementAndGet();
    String req = stompCommand.encodeSubscribe(topic, asyncSeq);
    this.sequence2Id.put(Long.toString(asyncSeq), asyncSeq);

    StompHeaderAccessor stompHeaderAccessor = getStompHeaderAccessor(stompCommand, req, asyncSeq, "subscribe");

    // cache the subscription id and the WeEventTopic,the subscription2EventCache which can use for reconnect
    String subscriptionId = stompHeaderAccessor.getFirstNativeHeader("subscription-id");
    topic.getExtension().put(WeEvent.WeEvent_SubscriptionId, subscriptionId);

    this.subscription2EventCache.put(subscriptionId, Pair.of(topic, listener));
    // map the receipt id and the subscription id
    this.receiptId2SubscriptionId.put(String.valueOf(asyncSeq), subscriptionId);
    this.subscriptionId2ReceiptId.put(subscriptionId, String.valueOf(asyncSeq));
    log.info("subscribe success, topic: {}", topic.getTopicName());

    return subscriptionId;

}
 
Example 2
Source File: WebSocketTransport.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private void handleUnsubscribeMessage(StompHeaderAccessor stompHeaderAccessor, WebSocketSession session) {
    String simpDestination = stompHeaderAccessor.getDestination();
    String headerIdStr = stompHeaderAccessor.getFirstNativeHeader(StompHeaderAccessor.STOMP_ID_HEADER);

    try {
        boolean result = handleUnSubscribe(session, headerIdStr);

        // send response
        StompHeaderAccessor accessor;
        if (result) {
            accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
            accessor.setDestination(simpDestination);
        } else {
            accessor = StompHeaderAccessor.create(StompCommand.ERROR);
        }
        // a unique identifier for that message and a subscription header matching the identifier of the subscription that is receiving the message.
        accessor.setReceiptId(headerIdStr);
        sendSimpleMessage(session, accessor);
    } catch (BrokerException e) {
        handleErrorMessage(session, e, headerIdStr);
    }
}
 
Example 4
Source File: AbstractAuthenticatedController.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
protected void authenticate(StompHeaderAccessor accessor) {
    String authToken = accessor.getFirstNativeHeader(ServerConstants.X_AUTH_TOKEN);

    if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
        log.debug("Header auth token: " + authToken);
    }

    if (StringUtils.isNotBlank(authToken)) {

        // set cached authenticated user back in the spring security context
        Authentication authentication = preAuthAuthenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

        if (log.isDebugEnabled()) {
            log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
        }

        SpringSecurityHelper.setAuthentication(authentication);

    }
}
 
Example 5
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private void handleSendMessage(StompHeaderAccessor stompHeaderAccessor, Message<byte[]> msg, WebSocketSession session) {
    Map<String, String> extensions = this.getWeEventExtend(msg);
    // group id
    String groupId = stompHeaderAccessor.getFirstNativeHeader(WeEventConstants.EVENT_GROUP_ID);
    if (StringUtils.isBlank(groupId)) {
        groupId = "";
    }

    try {
        String destination = stompHeaderAccessor.getDestination();

        // publish event
        SendResult sendResult = this.iproducer.publish(new WeEvent(destination, msg.getPayload(), extensions), groupId, this.fiscoConfig.getWeb3sdkTimeout());

        // send response
        StompHeaderAccessor accessor;
        if (sendResult.getStatus().equals(SendResult.SendResultStatus.SUCCESS)) {
            accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
            accessor.setDestination(destination);
            accessor.setNativeHeader(WeEventConstants.EXTENSIONS_EVENT_ID, sendResult.getEventId());
        } else {
            accessor = StompHeaderAccessor.create(StompCommand.ERROR);
            accessor.setMessage(sendResult.toString());
        }
        accessor.setReceiptId(stompHeaderAccessor.getReceipt());

        sendSimpleMessage(session, accessor);
    } catch (BrokerException e) {
        handleErrorMessage(session, e, stompHeaderAccessor.getReceipt());
    }
}
 
Example 6
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private void handleDefaultMessage(StompHeaderAccessor stompHeaderAccessor, WebSocketSession session) {
    String simpDestination = stompHeaderAccessor.getDestination();
    String headerIdStr = stompHeaderAccessor.getFirstNativeHeader(StompHeaderAccessor.STOMP_ID_HEADER);

    // send response
    StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
    accessor.setDestination(simpDestination);
    accessor.setMessage("NOT SUPPORT COMMAND");
    accessor.setReceiptId(headerIdStr);
    // a unique identifier for that message and a subscription header matching the identifier of the subscription that is receiving the message.
    sendSimpleMessage(session, accessor);

    // follow protocol 1.2 to close connection
    this.closeSession(session);
}
 
Example 7
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 8
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Bean
public ChannelInterceptorAdapter sessionContextChannelInterceptorAdapter() {
    return new ChannelInterceptorAdapter() {
        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            StompCommand command = accessor.getCommand();

            if (log.isDebugEnabled() && command != null) {
                log.debug("StompCommand: " + command.toString());
            }

            String authToken = accessor.getFirstNativeHeader(ServerConstants.X_AUTH_TOKEN);

            if (log.isDebugEnabled() && StringUtils.isNotEmpty(authToken)) {
                log.debug("Header auth token: " + authToken);
            }

            if (StringUtils.isNotBlank(authToken)) {

                // set cached authenticated user back in the spring security context
                Authentication authentication = preAuthAuthenticationManager.authenticate(new PreAuthenticatedAuthenticationToken(authToken, "N/A"));

                if (log.isDebugEnabled()) {
                    log.debug("Adding Authentication to SecurityContext for WebSocket call: " + authentication);
                }
                SpringSecurityHelper.setAuthentication(authentication);

            }
            return super.preSend(message, channel);
        }
    };
}
 
Example 9
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 10
Source File: BrokerStomp.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
private void handleSubscribeMessage(StompHeaderAccessor stompHeaderAccessor, WebSocketSession session) {
    // subscribe command id
    String headerIdStr = stompHeaderAccessor.getFirstNativeHeader(StompHeaderAccessor.STOMP_ID_HEADER);

    // group
    String groupId = stompHeaderAccessor.getFirstNativeHeader(WeEventConstants.EVENT_GROUP_ID);
    if (StringUtils.isBlank(groupId)) {
        groupId = "";
    }

    // check if there hasn't the event, need use the last id
    String subEventId = stompHeaderAccessor.getFirstNativeHeader(WeEventConstants.EXTENSIONS_EVENT_ID);
    if (StringUtils.isBlank(subEventId)) {
        subEventId = WeEvent.OFFSET_LAST;
    }

    // subscription id
    String continueSubscriptionIdStr = stompHeaderAccessor.getFirstNativeHeader(WeEvent.WeEvent_SubscriptionId);
    if (StringUtils.isBlank(continueSubscriptionIdStr)) {
        continueSubscriptionIdStr = "";
    }

    // tag
    String tag = stompHeaderAccessor.getFirstNativeHeader(WeEvent.WeEvent_TAG);
    if (StringUtils.isBlank(tag)) {
        tag = "";
    }

    // is ephemeral
    boolean ephemeral = stompHeaderAccessor.getFirstNativeHeader(WeEvent.WeEvent_EPHEMERAL) != null;

    try {
        String simpDestination = stompHeaderAccessor.getDestination();
        String subscriptionId = handleSubscribe(session,
                simpDestination,
                groupId,
                headerIdStr,
                subEventId,
                continueSubscriptionIdStr,
                tag,
                ephemeral);

        // send response
        StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
        accessor.setDestination(simpDestination);
        // a unique identifier for that message and a subscription header matching the identifier of the subscription that is receiving the message.
        accessor.setReceiptId(headerIdStr);
        accessor.setSubscriptionId(subscriptionId);
        accessor.setNativeHeader("subscription-id", subscriptionId);
        sendSimpleMessage(session, accessor);
    } catch (BrokerException e) {
        handleErrorMessage(session, e, headerIdStr);
    }
}
 
Example 11
Source File: StompSubProtocolHandler.java    From java-technology-stack 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 12
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;
}
 
Example 13
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 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[])) {
		logger.error("Expected byte[] payload. Ignoring " + message + ".");
		return;
	}

	StompHeaderAccessor stompAccessor = getStompHeaderAccessor(message);
	StompCommand command = stompAccessor.getCommand();

	if (StompCommand.MESSAGE.equals(command)) {
		if (stompAccessor.getSubscriptionId() == null) {
			logger.warn("No STOMP \"subscription\" header in " + message);
		}
		String origDestination = stompAccessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
		if (origDestination != null) {
			stompAccessor = toMutableAccessor(stompAccessor, message);
			stompAccessor.removeNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
			stompAccessor.setDestination(origDestination);
		}
	}
	else if (StompCommand.CONNECTED.equals(command)) {
		this.stats.incrementConnectedCount();
		stompAccessor = afterStompSessionConnected(message, stompAccessor, session);
		if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) {
			try {
				SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
				SimpAttributesContextHolder.setAttributes(simpAttributes);
				Principal user = session.getPrincipal();
				publishEvent(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);
		stompAccessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class);
		Assert.notNull(stompAccessor, "Expected STOMP headers");
		payload = errorMessage.getPayload();
	}

	sendToClient(session, stompAccessor, payload);
}