Example usage for org.springframework.web.socket WebSocketSession getAttributes

List of usage examples for org.springframework.web.socket WebSocketSession getAttributes

Introduction

In this page you can find the example usage for org.springframework.web.socket WebSocketSession getAttributes.

Prototype

Map<String, Object> getAttributes();

Source Link

Document

Return the map with attributes associated with the WebSocket session.

Usage

From source file:io.sevenluck.chat.websocket.ChatWebSocketHandler.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    final String myToken = (String) session.getAttributes().get(HttpAuthTokenHandShakeInterceptor.X_TOKEN);

    logger.info("handleTextMessage with message {} and token {}", message, myToken);
    String payload = message.getPayload();

    try {/*  ww w  . ja v  a  2  s . c  o m*/
        ObjectMapper mapper = new ObjectMapper();
        ChatMessageDTO chatMessage = mapper.readValue(payload, ChatMessageDTO.class);

        final ChatRoom room = findChatRoom(chatMessage);
        if (null == room)
            return;

        chatMessageRepository.save(newInstance(session, room, chatMessage));
        List<ChatChannel> channels = chatChannelRepository.findByChatRoom(room);

        for (ChatChannel channel : channels) {

            List<ChatSession> chatSessions = chatSessionRepository.findByMember(channel.getMember());
            for (ChatSession chatSession : chatSessions) {

                if (!myToken.equals(chatSession.getAuthtoken())
                        && sessionMap.containsKey(chatSession.getAuthtoken())) {
                    WebSocketSession wsSession = sessionMap.get(chatSession.getAuthtoken()).getSession();
                    final String stringifyJSONObject = mapper.writeValueAsString(chatMessage);
                    wsSession.sendMessage(new TextMessage(stringifyJSONObject));
                }
            }
        }

    } catch (Exception e) {
        logger.error("TAG", e);
    }
}

From source file:ch.rasc.wampspring.config.WampSessionScopeTest.java

@Before
public void setUp() {
    this.scope = new WampSessionScope();
    this.objectFactory = Mockito.mock(ObjectFactory.class);
    this.sessionAttributesMap = new HashMap<>();

    @SuppressWarnings("resource")
    WebSocketSession nativeSession = Mockito.mock(WebSocketSession.class);
    Mockito.when(nativeSession.getId()).thenReturn("ws1");
    Mockito.when(nativeSession.getAttributes()).thenReturn(this.sessionAttributesMap);
    this.wampSession = new WampSession(nativeSession);
    WampSessionContextHolder.setAttributes(this.wampSession);
}

From source file:org.kurento.basicroom.RoomHandler.java

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

    RoomParticipant user = (RoomParticipant) session.getAttributes().get(USER);
    if (user != null) {
        updateThreadName(user.getName() + "|wsclosed");
        leaveRoom(user);/*from   ww  w  .  j  a  v a  2 s.co  m*/
        updateThreadName(HANDLER_THREAD_NAME);
    }
}

From source file:org.kurento.basicroom.RoomHandler.java

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    RoomParticipant user = (RoomParticipant) session.getAttributes().get(USER);

    if (user != null && !user.isClosed()) {
        log.warn("Transport error", exception);
    }/*from  w w w. j ava 2s.  c o m*/
}

From source file:io.sevenluck.chat.websocket.ChatWebSocketHandler.java

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    logger.info("afterConnectionEstablished from ip " + session.getRemoteAddress().getAddress());

    final String token = (String) session.getAttributes().get(HttpAuthTokenHandShakeInterceptor.X_TOKEN);
    List<ChatSession> chatSessions = chatSessionRepository.findByAuthtoken(token);
    if (!sessions.isEmpty()) {
        logger.info("chatsession {} assigned to token {}", chatSessions.get(0), token);
        this.sessionMap.put(token, new SessionItem(chatSessions.get(0), session));
    }/*  w  ww  .  j a v  a  2s .co  m*/
}

From source file:com.devicehive.websockets.AbstractWebSocketHandler.java

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    logger.debug("Connection closed: session id {}, close status is {} ", session.getId(), status);

    CopyOnWriteArraySet<String> commandSubscriptions = (CopyOnWriteArraySet) session.getAttributes()
            .get(CommandHandlers.SUBSCSRIPTION_SET_NAME);
    for (String s : commandSubscriptions) {
        commandService.sendUnsubscribeRequest(s, null);
    }/*from  w w  w  .  ja v a 2s  .  c  o m*/

    CopyOnWriteArraySet<String> notificationSubscriptions = (CopyOnWriteArraySet) session.getAttributes()
            .get(NotificationHandlers.SUBSCSRIPTION_SET_NAME);
    for (String s : notificationSubscriptions) {
        notificationService.unsubscribe(s, null);
    }

    sessionMonitor.removeSession(session.getId());
}

From source file:com.devicehive.websockets.handlers.CommonHandlers.java

@PreAuthorize("permitAll")
public WebSocketResponse processAuthenticate(JsonObject request, WebSocketSession session) {

    String jwtToken = null;// ww  w  .j  a v  a2  s .  c  o  m
    if (request.get("token") != null) {
        jwtToken = request.get("token").getAsString();
    }

    HiveWebsocketSessionState state = (HiveWebsocketSessionState) session.getAttributes()
            .get(HiveWebsocketSessionState.KEY);
    HiveAuthentication.HiveAuthDetails details = authenticationManager.getDetails(session);

    HiveAuthentication authentication = authenticationManager.authenticateJWT(jwtToken, details);

    HivePrincipal principal = (HivePrincipal) authentication.getPrincipal();

    authentication.setHivePrincipal(principal);

    session.getAttributes().put(WebSocketAuthenticationManager.SESSION_ATTR_AUTHENTICATION, authentication);

    SecurityContextHolder.getContext().setAuthentication(authentication);
    state.setHivePrincipal(principal);

    return new WebSocketResponse();
}

From source file:com.devicehive.websockets.AbstractWebSocketHandler.java

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    logger.debug("Opening session id {} ", session.getId());

    session = new ConcurrentWebSocketSessionDecorator(session, sendTimeLimit, sendBufferSizeLimit);
    HiveWebsocketSessionState state = new HiveWebsocketSessionState();
    session.getAttributes().put(HiveWebsocketSessionState.KEY, state);

    session.getAttributes().put(CommandHandlers.SUBSCSRIPTION_SET_NAME, new CopyOnWriteArraySet<String>());
    session.getAttributes().put(NotificationHandlers.SUBSCSRIPTION_SET_NAME, new CopyOnWriteArraySet<String>());

    sessionMonitor.registerSession(session);
}

From source file:org.opencron.server.websocket.TerminalHandler.java

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    super.afterConnectionEstablished(session);
    String sshSessionId = OpencronTools.getSshSessionId();
    if (sshSessionId != null) {
        final Terminal terminal = TerminalContext.remove(sshSessionId);
        if (terminal != null) {
            try {
                session.sendMessage(new TextMessage("Welcome to Opencron Terminal! Connect Starting."));
                getClient(session, terminal);
                int cols = Integer.parseInt(session.getAttributes().get("cols").toString());
                int rows = Integer.parseInt(session.getAttributes().get("rows").toString());
                int width = Integer.parseInt(session.getAttributes().get("width").toString());
                int height = Integer.parseInt(session.getAttributes().get("height").toString());
                terminalClient.openTerminal(cols, rows, width, height);
                terminalService.login(terminal);
            } catch (Exception e) {
                if (e.getLocalizedMessage().replaceAll("\\s+", "").contentEquals("Operationtimedout")) {
                    session.sendMessage(new TextMessage("Sorry! Connect timed out, please try again. "));
                } else {
                    session.sendMessage(new TextMessage("Sorry! Operation error, please try again. "));
                }//  w  w  w.j ava  2  s  . c  o  m
                terminalClient.disconnect();
                session.close();
            }
        } else {
            this.terminalClient.disconnect();
            session.sendMessage(new TextMessage("Sorry! Connect failed, please try again. "));
            session.close();
        }
    }
}

From source file:org.kurento.basicroom.RoomHandler.java

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    final JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    // FIXME: Hack to ignore real userName sent by browser
    // if (jsonMessage.get("id").getAsString().equals("joinRoom")) {
    // jsonMessage.add("name", new JsonPrimitive(UUID.randomUUID()
    // .toString()));
    // }/*from   www. j a  va 2s.  c o  m*/

    final RoomParticipant user = (RoomParticipant) session.getAttributes().get(USER);

    if (user != null) {
        log.debug("Incoming message from user '{}': {}", user.getName(), jsonMessage);
    } else {
        log.debug("Incoming message from new user: {}", jsonMessage);
    }

    switch (jsonMessage.get("id").getAsString()) {
    case "receiveVideoFrom":
        executor.submit(new Runnable() {
            @Override
            public void run() {
                updateThreadName("rv:" + user.getName());
                receiveVideoFrom(user, jsonMessage);
                updateThreadName(HANDLER_THREAD_NAME);
            }
        });
        break;
    case "joinRoom":
        joinRoom(jsonMessage, session);
        break;
    case "leaveRoom":
        leaveRoom(user);
        break;
    default:
        break;
    }

    updateThreadName(HANDLER_THREAD_NAME);
}