List of usage examples for org.springframework.web.socket WebSocketSession getId
String getId();
From source file:org.kurento.demo.CrowdDetectorHandler.java
private void start(final WebSocketSession session, JsonObject jsonMessage) throws IOException { updateFeed(jsonMessage);//from w w w.j a v a2 s. c o m if (this.pipeline.getPlayerEndpoint() == null) { try { JsonObject response = new JsonObject(); response.addProperty("id", "noPlayer"); session.sendMessage(new TextMessage(response.toString())); } catch (IOException a) { log.error("Exception sending message", a); } return; } if (!this.pipeline.isPlaying()) { try { JsonObject response = new JsonObject(); response.addProperty("id", "noPlaying"); session.sendMessage(new TextMessage(response.toString())); } catch (IOException a) { log.error("Exception sending message", a); } return; } MediaPipeline mediaPipeline = this.pipeline.getPipeline(); WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build(); 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()); } } }); this.pipeline.setWebRtcEndpoint(session.getId(), webRtcEndpoint); this.pipeline.getCrowdDetectorFilter().connect(webRtcEndpoint); // 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); response.addProperty("feedUrl", this.pipeline.getFeedUrl()); response.addProperty("rois", gson.toJson(this.pipeline.getRois())); synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } webRtcEndpoint.gatherCandidates(); }
From source file:org.kurento.jsonrpc.internal.ws.JsonRpcWebSocketHandler.java
@Override public void handleTextMessage(final WebSocketSession wsSession, TextMessage message) throws Exception { try {/* w ww. j a v a2s . co m*/ String messageJson = message.getPayload(); // TODO Ensure only one register message per websocket session. ServerSessionFactory factory = new ServerSessionFactory() { @Override public ServerSession createSession(String sessionId, Object registerInfo, SessionsManager sessionsManager) { return new WebSocketServerSession(sessionId, registerInfo, sessionsManager, wsSession); } @Override public void updateSessionOnReconnection(ServerSession session) { ((WebSocketServerSession) session).updateWebSocketSession(wsSession); } }; protocolManager.processMessage(messageJson, factory, new ResponseSender() { @Override public void sendResponse(Message message) throws IOException { String jsonMessage = message.toString(); log.debug("{} <-Res {}", label, jsonMessage); sendJsonMessage(jsonMessage); } @Override public void sendPingResponse(Message message) throws IOException { String jsonMessage = message.toString(); log.trace("{} <-Res {}", label, jsonMessage); sendJsonMessage(jsonMessage); } private void sendJsonMessage(String jsonMessage) throws IOException { synchronized (wsSession) { if (wsSession.isOpen()) { wsSession.sendMessage(new TextMessage(jsonMessage)); } else { log.error("Trying to send a message to a closed session"); } } } }, wsSession.getId()); } catch (Exception e) { log.error(label + "Exception processing request", e); } }
From source file:eu.nubomedia.tutorial.repository.UserSession.java
public String playRecording(final WebSocketSession session, String sdpOffer) { // KurentoClient kurentoClient = KurentoClient.create(); log.info("Created kurentoClient (session {})", sessionId); // Media pipeline mediaPipeline = kurentoClient.createMediaPipeline(); log.info("Created Media Pipeline for playing {} (session {})", mediaPipeline.getId(), sessionId); // Repository item (player) RepositoryItemPlayer repositoryItemPlayer = null; try {// ww w. j av a 2s . c o m // Guard time for repository to finish storing media long diff = System.currentTimeMillis() - stopTimestamp; if (diff >= 0 && diff < REPOSITORY_GUARD_TIME_MS) { log.info("Waiting for {}ms before requesting the repository read endpoint " + "(requires {}ms before upload is considered terminated " + "and only {}ms have passed)", REPOSITORY_GUARD_TIME_MS - diff, REPOSITORY_GUARD_TIME_MS, diff); Thread.sleep(REPOSITORY_GUARD_TIME_MS - diff); } repositoryItemPlayer = repositoryClient.getReadEndpoint(repositoryItemRecorder.getId()); } catch (Exception e) { log.warn("Exception creating repositoryItemPlayer", e); // This code allows to run the demo in local without a repository server repositoryItemPlayer = new RepositoryItemPlayer(); repositoryItemPlayer.setId(repositoryItemRecorder.getId()); repositoryItemPlayer.setUrl(repositoryItemRecorder.getUrl()); } // Media elements and connectivity webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build(); playerEndpoint = new PlayerEndpoint.Builder(mediaPipeline, repositoryItemPlayer.getUrl()).build(); playerEndpoint.connect(webRtcEndpoint); playerEndpoint.addErrorListener(new EventListener<ErrorEvent>() { @Override public void onEvent(ErrorEvent event) { log.info("ErrorEvent for session {}: {}", session.getId(), event.getDescription()); handler.sendPlayEnd(session); release(); } }); playerEndpoint.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { log.info("EndOfStreamEvent for session {}", session.getId()); handler.sendPlayEnd(session); release(); } }); // WebRTC negotiation String sdpAnswer = performWebRtcNegotiation(session, sdpOffer); // Start playing playerEndpoint.play(); return sdpAnswer; }
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 .ja va2s .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:org.kurento.tutorial.helloworld.HelloWorldRecHandler.java
private void play(UserSession user, final WebSocketSession session, JsonObject jsonMessage) { try {//from w w w.j a va 2 s. com // 0. Repository logic RepositoryItemPlayer itemPlayer = null; if (repositoryClient != null) { try { Date stopTimestamp = user.getStopTimestamp(); if (stopTimestamp != null) { Date now = new Date(); long diff = now.getTime() - stopTimestamp.getTime(); if (diff >= 0 && diff < REPOSITORY_DISCONNECT_TIMEOUT) { log.info( "Waiting for {}ms before requesting the repository read endpoint " + "(requires {}ms before upload is considered terminated " + "and only {}ms have passed)", REPOSITORY_DISCONNECT_TIMEOUT - diff, REPOSITORY_DISCONNECT_TIMEOUT, diff); Thread.sleep(REPOSITORY_DISCONNECT_TIMEOUT - diff); } } else { log.warn("No stop timeout was found, repository endpoint might not be ready"); } itemPlayer = repositoryClient.getReadEndpoint(user.getRepoItem().getId()); } catch (Exception e) { log.warn("Unable to obtain kurento repository endpoint", e); } } else { itemPlayer = new RepositoryItemPlayer(); itemPlayer.setId(user.getRepoItem().getId()); itemPlayer.setUrl(user.getRepoItem().getUrl()); } log.debug("Playing from {}: id={}, url={}", (repositoryClient == null ? "disk" : "repository"), itemPlayer.getId(), itemPlayer.getUrl()); // 1. Media logic final MediaPipeline pipeline = kurento.createMediaPipeline(); WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build(); PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, itemPlayer.getUrl()).build(); player.connect(webRtcEndpoint); // Player listeners player.addErrorListener(new EventListener<ErrorEvent>() { @Override public void onEvent(ErrorEvent event) { log.info("ErrorEvent for session '{}': {}", session.getId(), event.getDescription()); sendPlayEnd(session, pipeline); } }); player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { log.info("EndOfStreamEvent for session '{}'", session.getId()); sendPlayEnd(session, pipeline); } }); // 2. Store user session user.setMediaPipeline(pipeline); user.setWebRtcEndpoint(webRtcEndpoint); // 3. SDP negotiation String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "playResponse"); response.addProperty("sdpAnswer", sdpAnswer); // 4. Gather ICE candidates 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.error(e.getMessage()); } } }); // 5. Play recorded stream player.play(); synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } webRtcEndpoint.gatherCandidates(); } catch (Throwable t) { log.error("Play error", t); sendError(session, t.getMessage()); } }
From source file:org.springframework.integration.websocket.IntegrationWebSocketContainer.java
@Override public void destroy() throws Exception { try {//from w ww.ja va 2s .co m // Notify sessions to stop flushing messages for (WebSocketSession session : this.sessions.values()) { try { session.close(CloseStatus.GOING_AWAY); } catch (Exception e) { this.logger.error("Failed to close session id '" + session.getId() + "': " + e.getMessage()); } } } finally { this.sessions.clear(); } }
From source file:org.springframework.messaging.handler.websocket.SubProtocolWebSocketHandler.java
@Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { this.sessions.put(session.getId(), session); findProtocolHandler(session).afterSessionStarted(session, this.outputChannel); }
From source file:org.springframework.messaging.handler.websocket.SubProtocolWebSocketHandler.java
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { this.sessions.remove(session.getId()); findProtocolHandler(session).afterSessionEnded(session, closeStatus, this.outputChannel); }
From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java
/** * Handle incoming WebSocket messages from clients. *///from www. j a v a 2 s. c o m public void handleMessageFromClient(WebSocketSession session, WebSocketMessage webSocketMessage, MessageChannel outputChannel) { try { Assert.isInstanceOf(TextMessage.class, webSocketMessage); String payload = ((TextMessage) webSocketMessage).getPayload(); Message<?> message = this.stompMessageConverter.toMessage(payload); // TODO: validate size limits // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits if (logger.isTraceEnabled()) { logger.trace("Processing STOMP message: " + message); } try { StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); headers.setSessionId(session.getId()); headers.setUser(session.getPrincipal()); message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); if (SimpMessageType.CONNECT.equals(headers.getMessageType())) { handleConnect(session, message); } outputChannel.send(message); } catch (Throwable t) { logger.error("Terminating STOMP session due to failure to send message: ", t); sendErrorMessage(session, t); } // TODO: send RECEIPT message if incoming message has "receipt" header // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt } catch (Throwable error) { sendErrorMessage(session, error); } }
From source file:org.springframework.messaging.simp.stomp.StompProtocolHandler.java
protected void handleConnect(WebSocketSession session, Message<?> message) throws IOException { StompHeaderAccessor connectHeaders = StompHeaderAccessor.wrap(message); StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED); Set<String> acceptVersions = connectHeaders.getAcceptVersion(); if (acceptVersions.contains("1.2")) { connectedHeaders.setVersion("1.2"); } else if (acceptVersions.contains("1.1")) { connectedHeaders.setVersion("1.1"); } else if (acceptVersions.isEmpty()) { // 1.0//from ww w .j a v a 2 s.co m } else { throw new StompConversionException("Unsupported version '" + acceptVersions + "'"); } connectedHeaders.setHeartbeat(0, 0); // TODO Principal principal = session.getPrincipal(); if (principal != null) { connectedHeaders.setNativeHeader(CONNECTED_USER_HEADER, principal.getName()); connectedHeaders.setNativeHeader(QUEUE_SUFFIX_HEADER, session.getId()); if (this.queueSuffixResolver != null) { String suffix = session.getId(); this.queueSuffixResolver.addQueueSuffix(principal.getName(), session.getId(), suffix); } } // TODO: security Message<?> connectedMessage = MessageBuilder.withPayloadAndHeaders(new byte[0], connectedHeaders).build(); byte[] bytes = this.stompMessageConverter.fromMessage(connectedMessage); session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); }