Java Code Examples for org.springframework.messaging.simp.SimpMessageHeaderAccessor#getSessionId()

The following examples show how to use org.springframework.messaging.simp.SimpMessageHeaderAccessor#getSessionId() . 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: WebSocketConnectHandler.java    From bearchoke with Apache License 2.0 7 votes vote down vote up
@Override
    public void onApplicationEvent(SessionConnectEvent event) {
        if (log.isDebugEnabled()) {
            log.debug("Caught Web Socket connect event");
        }

        MessageHeaders headers = event.getMessage().getHeaders();
        Principal user = SimpMessageHeaderAccessor.getUser(headers);

        if(user == null) {
            return;
        }

        String id = SimpMessageHeaderAccessor.getSessionId(headers);

        if (log.isDebugEnabled()) {
            log.debug("Current web socket session id: " + id);
        }

        if (StringUtils.isNotBlank(id)) {
            repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
        }

//        messagingTemplate.convertAndSend("/topic/friends/signin", Arrays.asList(user.getName()));
    }
 
Example 2
Source File: UserDestinationMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public Message<?> preHandle(Message<?> message) throws MessagingException {
	String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
	if (!getBroadcastDestination().equals(destination)) {
		return message;
	}
	SimpMessageHeaderAccessor accessor = getAccessor(message, SimpMessageHeaderAccessor.class);
	if (accessor.getSessionId() == null) {
		// Our own broadcast
		return null;
	}
	destination = accessor.getFirstNativeHeader(ORIGINAL_DESTINATION);
	if (logger.isTraceEnabled()) {
		logger.trace("Checking unresolved user destination: " + destination);
	}
	SimpMessageHeaderAccessor newAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
	for (String name : accessor.toNativeHeaderMap().keySet()) {
		if (NO_COPY_LIST.contains(name)) {
			continue;
		}
		newAccessor.setNativeHeader(name, accessor.getFirstNativeHeader(name));
	}
	newAccessor.setDestination(destination);
	newAccessor.setHeader(SimpMessageHeaderAccessor.IGNORE_ERROR, true); // ensure send doesn't block
	return MessageBuilder.createMessage(message.getPayload(), newAccessor.getMessageHeaders());
}
 
Example 3
Source File: DefaultUserDestinationResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parseSubscriptionMessage(Message<?> message, String sourceDestination) {
	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		logger.error("No session id. Ignoring " + message);
		return null;
	}
	int prefixEnd = this.prefix.length() - 1;
	String actualDestination = sourceDestination.substring(prefixEnd);
	if (isRemoveLeadingSlash()) {
		actualDestination = actualDestination.substring(1);
	}
	Principal principal = SimpMessageHeaderAccessor.getUser(headers);
	String user = (principal != null ? principal.getName() : null);
	Set<String> sessionIds = Collections.singleton(sessionId);
	return new ParseResult(sourceDestination, actualDestination, sourceDestination, sessionIds, user);
}
 
Example 4
Source File: DefaultUserDestinationResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private ParseResult parseMessage(MessageHeaders headers, String sourceDest) {
	int prefixEnd = this.prefix.length();
	int userEnd = sourceDest.indexOf('/', prefixEnd);
	Assert.isTrue(userEnd > 0, "Expected destination pattern \"/user/{userId}/**\"");
	String actualDest = sourceDest.substring(userEnd);
	String subscribeDest = this.prefix.substring(0, prefixEnd - 1) + actualDest;
	String userName = sourceDest.substring(prefixEnd, userEnd);
	userName = StringUtils.replace(userName, "%2F", "/");

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	Set<String> sessionIds;
	if (userName.equals(sessionId)) {
		userName = null;
		sessionIds = Collections.singleton(sessionId);
	}
	else {
		sessionIds = getSessionIdsByUser(userName, sessionId);
	}

	if (isRemoveLeadingSlash()) {
		actualDest = actualDest.substring(1);
	}
	return new ParseResult(sourceDest, actualDest, subscribeDest, sessionIds, userName);
}
 
Example 5
Source File: SubscriptionMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> message) throws Exception {
	if (returnValue == null) {
		return;
	}

	MessageHeaders headers = message.getHeaders();
	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);

	if (subscriptionId == null) {
		throw new IllegalStateException(
				"No subscriptionId in " + message + " returned by: " + returnType.getMethod());
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Reply to @SubscribeMapping: " + returnValue);
	}
	this.messagingTemplate.convertAndSend(
			destination, returnValue, createHeaders(sessionId, subscriptionId, returnType));
}
 
Example 6
Source File: DefaultUserDestinationResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parseSubscriptionMessage(Message<?> message, String sourceDestination) {
	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		logger.error("No session id. Ignoring " + message);
		return null;
	}
	int prefixEnd = this.prefix.length() - 1;
	String actualDestination = sourceDestination.substring(prefixEnd);
	if (isRemoveLeadingSlash()) {
		actualDestination = actualDestination.substring(1);
	}
	Principal principal = SimpMessageHeaderAccessor.getUser(headers);
	String user = (principal != null ? principal.getName() : null);
	Set<String> sessionIds = Collections.singleton(sessionId);
	return new ParseResult(sourceDestination, actualDestination, sourceDestination, sessionIds, user);
}
 
Example 7
Source File: DefaultUserDestinationResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
private ParseResult parseMessage(MessageHeaders headers, String sourceDest) {
	int prefixEnd = this.prefix.length();
	int userEnd = sourceDest.indexOf('/', prefixEnd);
	Assert.isTrue(userEnd > 0, "Expected destination pattern \"/user/{userId}/**\"");
	String actualDest = sourceDest.substring(userEnd);
	String subscribeDest = this.prefix.substring(0, prefixEnd - 1) + actualDest;
	String userName = sourceDest.substring(prefixEnd, userEnd);
	userName = StringUtils.replace(userName, "%2F", "/");

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	Set<String> sessionIds;
	if (userName.equals(sessionId)) {
		userName = null;
		sessionIds = Collections.singleton(sessionId);
	}
	else {
		sessionIds = getSessionIdsByUser(userName, sessionId);
	}

	if (isRemoveLeadingSlash()) {
		actualDest = actualDest.substring(1);
	}
	return new ParseResult(sourceDest, actualDest, subscribeDest, sessionIds, userName);
}
 
Example 8
Source File: UserDestinationMessageHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
public Message<?> preHandle(Message<?> message) throws MessagingException {
	String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
	if (!getBroadcastDestination().equals(destination)) {
		return message;
	}
	SimpMessageHeaderAccessor accessor =
			SimpMessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
	Assert.state(accessor != null, "No SimpMessageHeaderAccessor");
	if (accessor.getSessionId() == null) {
		// Our own broadcast
		return null;
	}
	destination = accessor.getFirstNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION);
	if (logger.isTraceEnabled()) {
		logger.trace("Checking unresolved user destination: " + destination);
	}
	SimpMessageHeaderAccessor newAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
	for (String name : accessor.toNativeHeaderMap().keySet()) {
		if (NO_COPY_LIST.contains(name)) {
			continue;
		}
		newAccessor.setNativeHeader(name, accessor.getFirstNativeHeader(name));
	}
	if (destination != null) {
		newAccessor.setDestination(destination);
	}
	newAccessor.setHeader(SimpMessageHeaderAccessor.IGNORE_ERROR, true); // ensure send doesn't block
	return MessageBuilder.createMessage(message.getPayload(), newAccessor.getMessageHeaders());
}
 
Example 9
Source File: StreamController.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * Serves web socket requests, requesting to resume a consumer.
 */
@MessageMapping("/resume/{viewId}")
@Transactional(readOnly = true)
public String resumeConsumer(
    @DestinationVariable final Long viewId,
    final SimpMessageHeaderAccessor headerAccessor) {

    // Request Resume
    final long userId = getLoggedInUserId(headerAccessor);
    final String sessionId = headerAccessor.getSessionId();
    webSocketConsumersManager.resumeConsumer(viewId, SessionIdentifier.newStreamIdentifier(userId, sessionId));
    return "{success: true}";
}
 
Example 10
Source File: StreamController.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * Serves web socket requests, requesting to pause a consumer.
 */
@MessageMapping("/pause/{viewId}")
@Transactional(readOnly = true)
public String pauseConsumer(
    @DestinationVariable final Long viewId,
    final SimpMessageHeaderAccessor headerAccessor) {

    // Request a pause
    final long userId = getLoggedInUserId(headerAccessor);
    final String sessionId = headerAccessor.getSessionId();
    webSocketConsumersManager.pauseConsumer(viewId, SessionIdentifier.newStreamIdentifier(userId, sessionId));
    return "{success: true}";
}
 
Example 11
Source File: StreamController.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * Serves websocket requests, requesting to start a stream on the given view.
 */
@MessageMapping("/consume/{viewId}")
@Transactional(readOnly = true)
public String newConsumer(
    @DestinationVariable final Long viewId,
    final ConsumeRequest consumeRequest,
    final SimpMessageHeaderAccessor headerAccessor) {

    // Retrieve view
    final Optional<View> viewOptional = viewRepository.findById(viewId);
    if (!viewOptional.isPresent()) {
        return "{success: false}";
    }
    final View view = viewOptional.get();

    // Build a session identifier
    final long userId = getLoggedInUserId(headerAccessor);
    final String sessionId = headerAccessor.getSessionId();
    final SessionIdentifier sessionIdentifier = SessionIdentifier.newStreamIdentifier(userId, sessionId);

    // Override settings
    // TODO View gets flushed and changes are persisted.
    final ViewCustomizer viewCustomizer = new ViewCustomizer(view, consumeRequest);
    viewCustomizer.overrideViewSettings();
    final List<FilterDefinition> configuredFilters = viewCustomizer.getFilterDefinitions();

    // Configure where to start from
    final StartingPosition startingPosition = viewCustomizer.getStartingPosition();

    webSocketConsumersManager.addNewConsumer(view, configuredFilters, startingPosition, sessionIdentifier);
    return "{success: true}";
}
 
Example 12
Source File: AbstractSubscriptionRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final void registerSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.SUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected SUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in  " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId in " + message);
		}
		return;
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No destination in " + message);
		}
		return;
	}

	addSubscriptionInternal(sessionId, subscriptionId, destination, message);
}
 
Example 13
Source File: SubscriptionMethodReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, Message<?> message)
		throws Exception {

	if (returnValue == null) {
		return;
	}

	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	String destination = SimpMessageHeaderAccessor.getDestination(headers);

	if (subscriptionId == null) {
		throw new IllegalStateException("No simpSubscriptionId in " + message +
				" returned by: " + returnType.getMethod());
	}
	if (destination == null) {
		throw new IllegalStateException("No simpDestination in " + message +
				" returned by: " + returnType.getMethod());
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Reply to @SubscribeMapping: " + returnValue);
	}
	MessageHeaders headersToSend = createHeaders(sessionId, subscriptionId, returnType);
	this.messagingTemplate.convertAndSend(destination, returnValue, headersToSend);
}
 
Example 14
Source File: AbstractSubscriptionRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public final void unregisterSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected UNSUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId " + message);
		}
		return;
	}

	removeSubscriptionInternal(sessionId, subscriptionId, message);
}
 
Example 15
Source File: AbstractSubscriptionRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public final void registerSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.SUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected SUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in  " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId in " + message);
		}
		return;
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No destination in " + message);
		}
		return;
	}

	addSubscriptionInternal(sessionId, subscriptionId, destination, message);
}
 
Example 16
Source File: SubscriptionMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, Message<?> message)
		throws Exception {

	if (returnValue == null) {
		return;
	}

	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	String destination = SimpMessageHeaderAccessor.getDestination(headers);

	if (subscriptionId == null) {
		throw new IllegalStateException("No simpSubscriptionId in " + message +
				" returned by: " + returnType.getMethod());
	}
	if (destination == null) {
		throw new IllegalStateException("No simpDestination in " + message +
				" returned by: " + returnType.getMethod());
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Reply to @SubscribeMapping: " + returnValue);
	}
	MessageHeaders headersToSend = createHeaders(sessionId, subscriptionId, returnType);
	this.messagingTemplate.convertAndSend(destination, returnValue, headersToSend);
}
 
Example 17
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public String resolveSessionId(Message<?> message) {
	return SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
}
 
Example 18
Source File: StompSubProtocolHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public String resolveSessionId(Message<?> message) {
	return SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
}
 
Example 19
Source File: StompSubProtocolHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public String resolveSessionId(Message<?> message) {
	return SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
}
 
Example 20
Source File: SimpleBrokerMessageHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleMessageInternal(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	Principal user = SimpMessageHeaderAccessor.getUser(headers);

	updateSessionReadTime(sessionId);

	if (!checkDestinationPrefix(destination)) {
		return;
	}

	SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
	if (accessor == null) {
		throw new IllegalStateException(
				"No header accessor (not using the SimpMessagingTemplate?): " + message);
	}

	if (SimpMessageType.MESSAGE.equals(messageType)) {
		logMessage(message);
		sendMessageToSubscribers(destination, message);
	}
	else if (SimpMessageType.CONNECT.equals(messageType)) {
		logMessage(message);
		long[] clientHeartbeat = SimpMessageHeaderAccessor.getHeartbeat(headers);
		long[] serverHeartbeat = getHeartbeatValue();
		this.sessions.put(sessionId, new SessionInfo(sessionId, user, clientHeartbeat, serverHeartbeat));
		SimpMessageHeaderAccessor connectAck = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
		initHeaders(connectAck);
		connectAck.setSessionId(sessionId);
		connectAck.setUser(SimpMessageHeaderAccessor.getUser(headers));
		connectAck.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
		connectAck.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, serverHeartbeat);
		Message<byte[]> messageOut = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAck.getMessageHeaders());
		getClientOutboundChannel().send(messageOut);
	}
	else if (SimpMessageType.DISCONNECT.equals(messageType)) {
		logMessage(message);
		handleDisconnect(sessionId, user);
	}
	else if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
		logMessage(message);
		this.subscriptionRegistry.registerSubscription(message);
	}
	else if (SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
		logMessage(message);
		this.subscriptionRegistry.unregisterSubscription(message);
	}
}