List of usage examples for org.springframework.web.socket WebSocketSession getAttributes
Map<String, Object> getAttributes();
From source file:org.kurento.basicroom.RoomHandler.java
private void joinRoom(JsonObject jsonMessage, final WebSocketSession session) throws IOException, InterruptedException, ExecutionException { final String roomName = jsonMessage.get("room").getAsString(); final String userName = jsonMessage.get("name").getAsString(); updateThreadName(userName);/* w w w . j a v a 2 s . c o m*/ log.info("PARTICIPANT {}: trying to join room {}", userName, roomName); final Room room = roomManager.getRoom(roomName); if (!room.isClosed()) { room.execute(new Runnable() { public void run() { updateThreadName("r>" + userName); final RoomParticipant user = room.join(userName, session); session.getAttributes().put(USER, user); updateThreadName("r>" + HANDLER_THREAD_NAME); } }); } else { log.warn("Trying to join from room {} but it is closed", room.getName()); } }
From source file:virnet.experiment.webSocket.hndler.MainSystemWebSocketHandler.java
@Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("connect to the websocket success......"); //web socket session??? String userName = (String) session.getAttributes().get("WS_USER_Name"); String workgroup = (String) session.getAttributes().get("WS_USER_WorkGroup"); String pageType = (String) session.getAttributes().get("WS_USER_pageType"); if (pageType.equals("experiment")) { expUsers.add(session);/*from w w w. j av a2s.co m*/ userMap.put(session, workgroup); //?map // userNameMap.put(session, userName); } if (pageType.equals("arrange")) { userGroupMapPro.put(session, workgroup); arrangeUsers.add(session); arrangeUserName.put(session, userName); } this.session = session; //webSocketMap.put(this.session,this); //?map //userGroupMap.put(this.session,workgroup); //?map //session.sendMessage(new TextMessage("Server:connected OK!")); }
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandUnsubscribe(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/* ww w . java 2 s . c o m*/ final Optional<String> subscriptionId = Optional.ofNullable(request.get(SUBSCRIPTION_ID)) .map(JsonElement::getAsString); Set<String> guids = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/unsubscribe action. Session {} ", session.getId()); if (!subscriptionId.isPresent() && guids == null) { List<DeviceVO> actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); guids = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); commandService.sendUnsubscribeRequest(null, guids); } else if (subscriptionId.isPresent()) { commandService.sendUnsubscribeRequest(subscriptionId.get(), guids); } else { commandService.sendUnsubscribeRequest(null, guids); } ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).remove(subscriptionId); return new WebSocketResponse(); }
From source file:com.devicehive.websockets.handlers.NotificationHandlers.java
/** * Implementation of the <a href="http://www.devicehive.com/restful#WsReference/Client/notificationunsubscribe"> * WebSocket API: Client: notification/unsubscribe</a> Unsubscribes from device notifications. * * @param session Current session/*w w w . jav a 2s. co m*/ * @return Json object with the following structure <code> { "action": {string}, "status": {string}, "requestId": * {object} } </code> */ @PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_NOTIFICATION')") public WebSocketResponse processNotificationUnsubscribe(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); Optional<String> subId = Optional.ofNullable(request.get(SUBSCRIPTION_ID)).map(s -> { try { return s.getAsString(); } catch (UnsupportedOperationException e) { logger.error("Subscription Id is null"); return StringUtils.EMPTY; } }); Set<String> deviceGuids = gson.fromJson(request.get(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("notification/unsubscribe action. Session {} ", session.getId()); if (!subId.isPresent() && deviceGuids == null) { List<DeviceVO> actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); deviceGuids = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); notificationService.unsubscribe(null, deviceGuids); } else if (subId.isPresent()) { notificationService.unsubscribe(subId.get(), deviceGuids); } else { notificationService.unsubscribe(null, deviceGuids); } logger.debug("notification/unsubscribe completed for session {}", session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).remove(subId); return new WebSocketResponse(); }
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//from www . j a v a 2s . c o m final Date timestamp = gson.fromJson(request.get(TIMESTAMP), Date.class); final String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)) .map(JsonElement::getAsString).orElse(null); final Set<String> names = gson.fromJson(request.getAsJsonArray(NAMES), JsonTypes.STRING_SET_TYPE); Set<String> devices = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session); devices = prepareActualList(devices, deviceId); List<DeviceVO> actualDevices; if (devices != null) { actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal); if (actualDevices.size() != devices.size()) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN); } } else { actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createCommandInsertMessage(command, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService.sendSubscribeRequest(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection .forEach(cmd -> sendMessage(ServerResponsesFactory.createCommandInsertMessage(cmd, pair.getLeft()), session))); logger.debug("command/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft()); WebSocketResponse response = new WebSocketResponse(); response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null); return response; }
From source file:com.devicehive.websockets.handlers.NotificationHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_NOTIFICATION')") public WebSocketResponse processNotificationSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/*from w w w. j av a 2 s . c om*/ Date timestamp = gson.fromJson(request.get(Constants.TIMESTAMP), Date.class); Set<String> devices = gson.fromJson(request.get(Constants.DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); Set<String> names = gson.fromJson(request.get(Constants.NAMES), JsonTypes.STRING_SET_TYPE); String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)).map(JsonElement::getAsString) .orElse(null); logger.debug("notification/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); devices = prepareActualList(devices, deviceId); List<DeviceVO> actualDevices; if (devices != null) { actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal); if (actualDevices.size() != devices.size()) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN); } } else { actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } BiConsumer<DeviceNotification, String> callback = (notification, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceNotification>>> pair = notificationService.subscribe(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection.forEach(notification -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, pair.getLeft()); sendMessage(json, session); })); logger.debug("notification/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft()); WebSocketResponse response = new WebSocketResponse(); response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null); return response; }
From source file:org.springframework.session.web.socket.handler.WebSocketRegistryListener.java
private String getHttpSessionId(WebSocketSession wsSession) { Map<String, Object> attributes = wsSession.getAttributes(); return SessionRepositoryMessageInterceptor.getSessionId(attributes); }
From source file:org.springframework.web.socket.messaging.StompSubProtocolHandler.java
/** * Handle incoming WebSocket messages from clients. *///from ww w . ja va 2 s .co m 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
/** * Handle STOMP messages going back out to WebSocket clients. *//* ww w . j a va2s .c o m*/ @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 && StompCommand.CONNECTED.equals(command)) { 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); }