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

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

Introduction

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

Prototype

String getId();

Source Link

Document

Return a unique session identifier.

Usage

From source file:org.kurento.tutorial.pointerdetector.PointerDetectorHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {/* w w w.  ja v a2 s. c  om*/
        // Media Logic (Media Pipeline and Elements)
        UserSession user = new UserSession();
        MediaPipeline pipeline = kurento.createMediaPipeline();
        user.setMediaPipeline(pipeline);
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
        user.setWebRtcEndpoint(webRtcEndpoint);
        users.put(session.getId(), user);

        webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

            @Override
            public void onEvent(IceCandidateFoundEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
        });

        pointerDetectorFilter = new PointerDetectorFilter.Builder(pipeline, new WindowParam(5, 5, 30, 30))
                .build();

        pointerDetectorFilter.addWindow(new PointerDetectorWindowMediaParam("window0", 50, 50, 500, 150));

        pointerDetectorFilter.addWindow(new PointerDetectorWindowMediaParam("window1", 50, 50, 500, 250));

        webRtcEndpoint.connect(pointerDetectorFilter);
        pointerDetectorFilter.connect(webRtcEndpoint);

        pointerDetectorFilter.addWindowInListener(new EventListener<WindowInEvent>() {
            @Override
            public void onEvent(WindowInEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "windowIn");
                response.addProperty("roiId", event.getWindowId());
                try {
                    session.sendMessage(new TextMessage(response.toString()));
                } catch (Throwable t) {
                    sendError(session, t.getMessage());
                }
            }
        });

        pointerDetectorFilter.addWindowOutListener(new EventListener<WindowOutEvent>() {

            @Override
            public void onEvent(WindowOutEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "windowOut");
                response.addProperty("roiId", event.getWindowId());
                try {
                    session.sendMessage(new TextMessage(response.toString()));
                } catch (Throwable t) {
                    sendError(session, t.getMessage());
                }
            }
        });

        // SDP negotiation (offer and answer)
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

        // Sending response back to client
        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);
        synchronized (session) {
            session.sendMessage(new TextMessage(response.toString()));
        }

        webRtcEndpoint.gatherCandidates();

    } catch (Throwable t) {
        sendError(session, t.getMessage());
    }
}

From source file:com.github.mrstampy.gameboot.websocket.WebSocketSessionRegistry.java

private void sendBinary(String groupName, WebSocketSession wss, byte[] message) {
    BinaryMessage bm = new BinaryMessage(message);
    try {// www  .j  a va 2  s.c  o  m
        wss.sendMessage(bm);
        log.debug("Sent message to web socket session {} in group {}", wss.getId(), groupName);
    } catch (IOException e) {
        log.error("Unexpected exception sending message to web socket session {}", wss.getId(), e);
    }
}

From source file:org.kurento.tutorial.pointerdetector.PointerDetectorHandler.java

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    log.debug("Incoming message: {}", jsonMessage);

    switch (jsonMessage.get("id").getAsString()) {
    case "start":
        start(session, jsonMessage);/*w  ww  . ja  v  a  2s .com*/
        break;

    case "calibrate":
        calibrate(session, jsonMessage);
        break;

    case "stop": {
        UserSession user = users.remove(session.getId());
        if (user != null) {
            user.release();
        }
        break;
    }

    case "onIceCandidate": {
        JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();

        UserSession user = users.get(session.getId());
        if (user != null) {
            IceCandidate cand = new IceCandidate(candidate.get("candidate").getAsString(),
                    candidate.get("sdpMid").getAsString(), candidate.get("sdpMLineIndex").getAsInt());
            user.addCandidate(cand);
        }
        break;
    }

    default:
        sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString());
        break;
    }
}

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

/**
 * Handle incoming WebSocket messages from clients.
 *//* w w w  .  ja v a  2  s  .  c o  m*/
@Override
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage,
        MessageChannel outputChannel) {

    Assert.isInstanceOf(TextMessage.class, webSocketMessage);
    WampMessage wampMessage = null;
    try {
        wampMessage = WampMessage.fromJson(session, this.jsonFactory,
                ((TextMessage) webSocketMessage).getPayload());
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ".", ex);
        }
        return;
    }

    try {
        WampSessionContextHolder.setAttributesFromMessage(wampMessage);
        outputChannel.send(wampMessage);
    } catch (Throwable ex) {
        logger.error("Failed to send client message to application via MessageChannel" + " in session "
                + session.getId() + ".", ex);

        if (wampMessage != null && wampMessage instanceof CallMessage) {

            CallErrorMessage callErrorMessage = new CallErrorMessage((CallMessage) wampMessage, "",
                    ex.toString());

            try {
                String json = callErrorMessage.toJson(this.jsonFactory);
                session.sendMessage(new TextMessage(json));
            } catch (Throwable t) {
                // Could be part of normal workflow (e.g. browser tab closed)
                logger.debug("Failed to send error to client.", t);
            }

        }
    } finally {
        WampSessionContextHolder.resetAttributes();
    }
}

From source file:org.kurento.demo.CrowdDetectorHandler.java

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    log.debug("Incoming message: {}", jsonMessage);

    switch (jsonMessage.get("id").getAsString()) {
    case "start":
        try {//w  w  w. j  a  va 2s .  c o m
            start(session, jsonMessage);
        } catch (Throwable t) {
            sendError(session, t.getMessage());
        }
        break;

    case "stop":
        this.pipeline.removeWebRtcEndpoint(session.getId());
        break;

    case "updateFeed":
        updateFeed(jsonMessage);
        break;

    case "changeProcessingWidth":
        changeProcessingWidth(jsonMessage.get("width").getAsInt());
        break;

    case "onIceCandidate": {
        JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();

        IceCandidate cand = new IceCandidate(candidate.get("candidate").getAsString(),
                candidate.get("sdpMid").getAsString(), candidate.get("sdpMLineIndex").getAsInt());
        this.pipeline.addCandidate(cand, session.getId());
        break;
    }

    default:
        sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString());
        break;
    }
}

From source file:com.zb.app.websocket.api.MessagePushAPI.java

private void doSend(Long cId, Long mId, String msg) {
    Collection<WebSocketSession> set = sessionHandler.getSession(mId);
    if (Argument.isEmpty(set)) {
        logger.error(// w w  w .  j av  a2s  . c  om
                "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{}is offLine!webSocketSession set is null!",
                msg, cId, mId);
    }
    for (WebSocketSession session : set) {
        if (session == null) {
            logger.error(
                    "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{}is offLine!session is null!",
                    msg, cId, mId);
        }
        try {
            session.sendMessage(new TextMessage(msg));
            logger.debug(
                    "MessagePushAPI:sendPushMsg msg success:?{},cid:?{},mid:?{},sessionId:?{}",
                    msg, cId, mId, session.getId());
        } catch (Exception e) {
            logger.error(
                    "MessagePushAPI:sendPushMsg msg error:?{},cid:?{},mid:?{},sessionId:?{}",
                    msg, cId, mId, session.getId());
        }
    }
}

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();/*from  ww w.j  a v a  2s  .c  om*/
    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:org.kurento.tutorial.crowddetector.CrowdDetectorHandler.java

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {//from w w  w  . j  a  v a2  s  .c  o m
        // Media Logic (Media Pipeline and Elements)
        UserSession user = new UserSession();
        MediaPipeline pipeline = kurento.createMediaPipeline();
        user.setMediaPipeline(pipeline);
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
        user.setWebRtcEndpoint(webRtcEndpoint);
        users.put(session.getId(), user);

        webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {

            @Override
            public void onEvent(OnIceCandidateEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
        });

        List<RegionOfInterest> rois = new ArrayList<>();
        List<RelativePoint> points = new ArrayList<RelativePoint>();

        points.add(new RelativePoint(0, 0));
        points.add(new RelativePoint(0.5F, 0));
        points.add(new RelativePoint(0.5F, 0.5F));
        points.add(new RelativePoint(0, 0.5F));

        RegionOfInterestConfig config = new RegionOfInterestConfig();

        config.setFluidityLevelMin(10);
        config.setFluidityLevelMed(35);
        config.setFluidityLevelMax(65);
        config.setFluidityNumFramesToEvent(5);
        config.setOccupancyLevelMin(10);
        config.setOccupancyLevelMed(35);
        config.setOccupancyLevelMax(65);
        config.setOccupancyNumFramesToEvent(5);
        config.setSendOpticalFlowEvent(false);
        config.setOpticalFlowNumFramesToEvent(3);
        config.setOpticalFlowNumFramesToReset(3);
        config.setOpticalFlowAngleOffset(0);

        rois.add(new RegionOfInterest(points, config, "roi0"));

        CrowdDetectorFilter crowdDetectorFilter = new CrowdDetectorFilter.Builder(pipeline, rois).build();

        webRtcEndpoint.connect(crowdDetectorFilter);
        crowdDetectorFilter.connect(webRtcEndpoint);

        // addEventListener to crowddetector
        crowdDetectorFilter.addCrowdDetectorDirectionListener(new EventListener<CrowdDetectorDirectionEvent>() {
            @Override
            public void onEvent(CrowdDetectorDirectionEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "directionEvent");
                response.addProperty("roiId", event.getRoiID());
                response.addProperty("angle", event.getDirectionAngle());
                try {
                    session.sendMessage(new TextMessage(response.toString()));
                } catch (Throwable t) {
                    sendError(session, t.getMessage());
                }
            }
        });

        crowdDetectorFilter.addCrowdDetectorFluidityListener(new EventListener<CrowdDetectorFluidityEvent>() {
            @Override
            public void onEvent(CrowdDetectorFluidityEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "fluidityEvent");
                response.addProperty("roiId", event.getRoiID());
                response.addProperty("level", event.getFluidityLevel());
                response.addProperty("percentage", event.getFluidityPercentage());
                try {
                    session.sendMessage(new TextMessage(response.toString()));
                } catch (Throwable t) {
                    sendError(session, t.getMessage());
                }
            }
        });

        crowdDetectorFilter.addCrowdDetectorOccupancyListener(new EventListener<CrowdDetectorOccupancyEvent>() {
            @Override
            public void onEvent(CrowdDetectorOccupancyEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "occupancyEvent");
                response.addProperty("roiId", event.getRoiID());
                response.addProperty("level", event.getOccupancyLevel());
                response.addProperty("percentage", event.getOccupancyPercentage());
                try {
                    session.sendMessage(new TextMessage(response.toString()));
                } catch (Throwable t) {
                    sendError(session, t.getMessage());
                }
            }
        });

        // SDP negotiation (offer and answer)
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

        // Sending response back to client
        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);

        synchronized (session) {
            session.sendMessage(new TextMessage(response.toString()));
        }

        webRtcEndpoint.gatherCandidates();

    } catch (Throwable t) {
        sendError(session, t.getMessage());
    }
}

From source file:com.music.websocket.GameTest.java

private WebSocketSession getSession(final String id) {
    messages.put(id, new LinkedList<WebSocketMessage<?>>());
    WebSocketSession session = mock(WebSocketSession.class);
    try {/* w  w  w.  j a  v  a 2s . c o m*/
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                messages.get(id).offer((WebSocketMessage<?>) invocation.getArguments()[0]);
                return null;
            }
        }).when(session).sendMessage(Mockito.<WebSocketMessage<?>>any());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    when(session.getId()).thenReturn(id);
    return session;
}

From source file:com.kurento.kmf.jsonrpcconnector.internal.ws.JsonRpcWebSocketHandler.java

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

    String messageJson = message.getPayload();

    log.info("--> {}", messageJson);

    // TODO Ensure only one register message per websocket session.
    ServerSessionFactory factory = new ServerSessionFactory() {
        @Override//from  www  . j  ava2 s .c  o  m
        public ServerSession createSession(String sessionId, Object registerInfo,
                SessionsManager sessionsManager) {
            return new WebSocketServerSession(sessionId, registerInfo, sessionsManager, wsSession);
        }
    };

    protocolManager.processMessage(messageJson, factory, new WebSocketResponseSender(wsSession),
            wsSession.getId());

}