List of usage examples for org.springframework.web.socket WebSocketSession getId
String getId();
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'CREATE_DEVICE_COMMAND')") public WebSocketResponse processCommandInsert(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//w w w . ja va 2 s . c o m final String deviceGuid = Optional.ofNullable(request.get(Constants.DEVICE_GUID)) .map(JsonElement::getAsString).orElse(null); final DeviceCommandWrapper deviceCommand = gson.fromJson(request.getAsJsonObject(COMMAND), DeviceCommandWrapper.class); logger.debug("command/insert action for {}, Session ", deviceGuid, session.getId()); Set<DeviceVO> devices = new HashSet<>(); if (deviceGuid == null) { for (String guid : principal.getDeviceGuids()) { devices.add(deviceService.findByGuidWithPermissionsCheck(guid, principal)); } } else { devices.add(deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal)); } if (devices.isEmpty()) { throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceGuid), SC_NOT_FOUND); } if (deviceCommand == null) { throw new HiveException(Messages.EMPTY_COMMAND, SC_BAD_REQUEST); } final UserVO user = principal.getUser(); WebSocketResponse response = new WebSocketResponse(); for (DeviceVO device : devices) { commandService.insert(deviceCommand, device, user).thenApply(cmd -> { commandUpdateSubscribeAction(cmd.getId(), device.getGuid(), session); response.addValue(COMMAND, new InsertCommand(cmd.getId(), cmd.getTimestamp(), cmd.getUserId()), COMMAND_TO_CLIENT); return response; }).exceptionally(ex -> { logger.warn("Unable to insert notification.", ex); throw new HiveException(Messages.INTERNAL_SERVER_ERROR, SC_INTERNAL_SERVER_ERROR); }).join(); } return response; }
From source file:org.kurento.tutorial.one2manycall.CallHandler.java
private synchronized void viewer(final WebSocketSession session, JsonObject jsonMessage) throws IOException { if (presenterUserSession == null || presenterUserSession.getWebRtcEndpoint() == null) { JsonObject response = new JsonObject(); response.addProperty("id", "viewerResponse"); response.addProperty("response", "rejected"); response.addProperty("message", "No active sender now. Become sender or . Try again later ..."); session.sendMessage(new TextMessage(response.toString())); } else {// www . j ava 2 s .c om if (viewers.containsKey(session.getId())) { JsonObject response = new JsonObject(); response.addProperty("id", "viewerResponse"); response.addProperty("response", "rejected"); response.addProperty("message", "You are already viewing in this session. " + "Use a different browser to add additional viewers."); session.sendMessage(new TextMessage(response.toString())); return; } UserSession viewer = new UserSession(session); viewers.put(session.getId(), viewer); WebRtcEndpoint nextWebRtc = new WebRtcEndpoint.Builder(pipeline).build(); nextWebRtc.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()); } } }); viewer.setWebRtcEndpoint(nextWebRtc); presenterUserSession.getWebRtcEndpoint().connect(nextWebRtc); String sdpOffer = jsonMessage.getAsJsonPrimitive("sdpOffer").getAsString(); String sdpAnswer = nextWebRtc.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "viewerResponse"); response.addProperty("response", "accepted"); response.addProperty("sdpAnswer", sdpAnswer); synchronized (session) { viewer.sendMessage(response); } nextWebRtc.gatherCandidates(); } }
From source file:dk.apaq.orderly.CallHandler.java
private synchronized void viewer(final WebSocketSession session, BroadcastMessage message) throws IOException { if (presenterUserSession == null || presenterUserSession.getWebRtcEndpoint() == null) { BroadcastMessageResponse response = new BroadcastMessageResponse(BroadcastMessageType.ViewerResponse, BroadcastMessageResponseType.Rejected, "No active sender now. Become sender or . Try again later ..."); session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response))); } else {/*from w w w . j a v a 2 s . c o m*/ if (viewers.containsKey(session.getId())) { BroadcastMessageResponse response = new BroadcastMessageResponse( BroadcastMessageType.ViewerResponse, BroadcastMessageResponseType.Rejected, "You are already viewing in this session."); session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response))); return; } UserSession viewer = new UserSession(session, objectMapper); viewers.put(session.getId(), viewer); WebRtcEndpoint nextWebRtc = new WebRtcEndpoint.Builder(pipeline).build(); nextWebRtc.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() { @Override public void onEvent(OnIceCandidateEvent event) { BroadcastMessageResponse response = new BroadcastMessageResponse( BroadcastMessageType.IceCandidate, dk.apaq.orderly.model.IceCandidate.fromOrg(event.getCandidate())); try { synchronized (session) { session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response))); } } catch (IOException e) { log.debug(e.getMessage()); } } }); viewer.setWebRtcEndpoint(nextWebRtc); presenterUserSession.getWebRtcEndpoint().connect(nextWebRtc); String sdpOffer = message.getSdpOffer(); String sdpAnswer = nextWebRtc.processOffer(sdpOffer); BroadcastMessageResponse response = new BroadcastMessageResponse(BroadcastMessageType.ViewerResponse, BroadcastMessageResponseType.Accepted); response.setSdpAnswer(sdpAnswer); synchronized (session) { viewer.sendMessage(response); } nextWebRtc.gatherCandidates(); } }
From source file:org.kurento.tutorial.senddatachannel.SendDataChannelHandler.java
private void start(final WebSocketSession session, JsonObject jsonMessage) { try {/* w w w . j a v a 2 s. co m*/ // User session UserSession user = new UserSession(); MediaPipeline pipeline = kurento.createMediaPipeline(); user.setMediaPipeline(pipeline); WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).useDataChannels().build(); user.setWebRtcEndpoint(webRtcEndpoint); PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, "http://files.kurento.org/video/filter/barcodes.webm").build(); user.setPlayer(player); users.put(session.getId(), user); player.addErrorListener(new EventListener<ErrorEvent>() { @Override public void onEvent(ErrorEvent event) { log.info("ErrorEvent: {}", event.getDescription()); sendPlayEnd(session); } }); player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { log.info("EndOfStreamEvent: {}", event.getTimestamp()); sendPlayEnd(session); } }); // ICE candidates 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()); } } }); // Media logic KmsSendData kmsSendData = new KmsSendData.Builder(pipeline).build(); player.connect(kmsSendData); kmsSendData.connect(webRtcEndpoint); // SDP negotiation (offer and answer) String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "startResponse"); response.addProperty("sdpAnswer", sdpAnswer); synchronized (session) { session.sendMessage(new TextMessage(response.toString())); } webRtcEndpoint.gatherCandidates(); player.play(); } catch (Throwable t) { sendError(session, t.getMessage()); } }
From source file:org.metis.push.PusherBean.java
/** * This method is called by the web socket container after an existing * session has been closed./*from w ww .j a va 2 s . c om*/ */ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { super.afterConnectionClosed(session, status); LOG.debug(getBeanName() + ": afterConnectionClosed, session id = " + session.getId() + ", status = " + status.toString()); // remove the session from the session registry WdsSocketSession wdsSession = getWdsSessions().remove(session.getId()); if (wdsSession == null) { LOG.warn(getBeanName() + ":afterConnectionClosed - this session did not exist in registry: " + session.getId()); return; } // get the sql job that the session had been subsribed to and remove the // session from that job SqlJob job = wdsSession.getMyJob(); if (job != null) { job.removeSession(session.getId()); } }
From source file:com.pubkit.platform.messaging.protocol.pkmp.PKMPInBoundEventHandler.java
private void handleConnect(PKMPConnect connect, WebSocketSession session) { boolean valid = validateApplication(connect, session); if (!valid) { sendPayload(new PKMPConnAck(connect.getClientId(), PKMPConnAck.APPLICATION_INVALID), session); return;// w w w . ja v a2s.com } LOG.debug("Connecting client {" + connect.getClientId() + "}"); PKMPConnection existingConnection = messageStoreService.getConnection(connect.getClientId()); if (existingConnection != null) { existingConnection.setSessionId(session.getId()); messageStoreService.addConnection(connect.getClientId(), existingConnection); } else { PKMPConnection newConnection = new PKMPConnection(connect.getClientId(), connect.getSourceUserId(), session.getId(), connect.getApplicationId(), connect.getApiVersion()); // add new connection messageStoreService.addConnection(connect.getClientId(), newConnection); } String accessToken = keyGenerator.getSecureSessionId(); boolean success = messageStoreService.saveAccessToken(session.getId(), accessToken); if (success) { // set active session messageStoreService.addSession(session); LOG.debug("Connected client {" + connect.getClientId() + "}"); sendPayload(new PKMPConnAck(connect.getClientId(), session.getId(), accessToken), session); } else { LOG.debug("PKMPConnection failed for client {" + connect.getClientId() + "}"); sendPayload(new PKMPConnAck(connect.getClientId(), PKMPConnAck.CONNECTION_FAILED), session); } }
From source file:ch.rasc.wampspring.config.WampSubProtocolHandler.java
/** * Handle WAMP messages going back out to WebSocket clients. *//*from w ww. java 2 s . c om*/ @Override public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message instanceof WampMessage)) { logger.error("Expected WampMessage. Ignoring " + message + "."); return; } boolean closeWebSocketSession = false; try { String json = ((WampMessage) message).toJson(this.jsonFactory); session.sendMessage(new TextMessage(json)); } catch (SessionLimitExceededException ex) { // Bad session, just get out throw ex; } catch (Throwable ex) { // Could be part of normal workflow (e.g. browser tab closed) logger.debug("Failed to send WebSocket message to client in session " + session.getId() + ".", ex); closeWebSocketSession = true; } finally { if (closeWebSocketSession) { try { session.close(CloseStatus.PROTOCOL_ERROR); } catch (IOException ex) { // Ignore } } } }
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 .j a v a 2 s. 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:org.metis.push.PusherBean.java
/** * This method is called by the web socket container after a new * connection/session has been established with this server endpoint. This * method will attempt to subscribe the client based on any query params and * if no params were provide, will use the URL's extra path info. *//*from w ww . j a v a 2s. c om*/ public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); LOG.debug(getBeanName() + ":afterConnectionEstablished - session id = " + session.getId()); // place the session in the global session registry. it will be removed // from the registry when it is closed WdsSocketSession wds = new WdsSocketSession(session); getWdsSessions().put(session.getId(), wds); // based on the query string (if any), attempt to find a SqlStmnt for // this session Map<String, String> map = Utils.getQueryMap(session.getUri().getQuery()); SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null) : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement was not found and query params were provided, then // close connection because search for statement had to take place based // on query params provided. in other words, if client provides query // params then it is requesting a subscrption via those params. if (sqlStmnt == null && (map != null && !map.isEmpty())) { LOG.error(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement with this incoming param set: " + map.toString()); session.close(POLICY_VIOLATION); return; } // if statement was not found and params were not provided, then attempt // to find statement based on the url's "extra path" info if (sqlStmnt == null) { LOG.trace(getBeanName() + ":afterConnectionEstablished - unable to find sql " + "statement on first pass, will attempt to use extra path info"); String[] xtraPathInfo = Utils.getExtraPathInfo(session.getUri().toString()); if (xtraPathInfo != null && xtraPathInfo.length >= 2) { LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]); // put the xtra path info in the bucket and try again map = (map == null) ? new HashMap<String, String>() : map; map.clear(); map.put(xtraPathInfo[0], xtraPathInfo[1]); // try again with the extra path info sqlStmnt = SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if statement could not be found, then simply return - client // may later subscribe with valid params if (sqlStmnt == null) { LOG.debug(getBeanName() + ":findStmnt - unable to find sql " + "statement with this xtra path info: " + map.toString()); return; } } else { // there was no extra path info, so simply return return; } } mainLock.lock(); try { // if we've gotten this far, a SqlStmnt was found based on query or // extra path info, now see if SqlStmnt already has a job with the // same param set (map). if no job was found, then create and start // one if (sqlStmnt.findSqlJob(map, wds) == null) { sqlStmnt.createSqlJob(map, wds); } } finally { mainLock.unlock(); } }
From source file:org.kurento.tutorial.player.PlayerHandler.java
private void start(final WebSocketSession session, JsonObject jsonMessage) { // 1. Media pipeline final UserSession user = new UserSession(); MediaPipeline pipeline = kurento.createMediaPipeline(); user.setMediaPipeline(pipeline);//from w w w .j a va 2 s. c om WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build(); user.setWebRtcEndpoint(webRtcEndpoint); String videourl = jsonMessage.get("videourl").getAsString(); final PlayerEndpoint playerEndpoint = new PlayerEndpoint.Builder(pipeline, videourl).build(); user.setPlayerEndpoint(playerEndpoint); users.put(session.getId(), user); playerEndpoint.connect(webRtcEndpoint); // 2. WebRtcEndpoint // 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.debug(e.getMessage()); } } }); String sdpOffer = jsonMessage.get("sdpOffer").getAsString(); String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer); JsonObject response = new JsonObject(); response.addProperty("id", "startResponse"); response.addProperty("sdpAnswer", sdpAnswer); sendMessage(session, response.toString()); webRtcEndpoint.addMediaStateChangedListener(new EventListener<MediaStateChangedEvent>() { @Override public void onEvent(MediaStateChangedEvent event) { if (event.getNewState() == MediaState.CONNECTED) { VideoInfo videoInfo = playerEndpoint.getVideoInfo(); JsonObject response = new JsonObject(); response.addProperty("id", "videoInfo"); response.addProperty("isSeekable", videoInfo.getIsSeekable()); response.addProperty("initSeekable", videoInfo.getSeekableInit()); response.addProperty("endSeekable", videoInfo.getSeekableEnd()); response.addProperty("videoDuration", videoInfo.getDuration()); sendMessage(session, response.toString()); } } }); webRtcEndpoint.gatherCandidates(); // 3. PlayEndpoint playerEndpoint.addErrorListener(new EventListener<ErrorEvent>() { @Override public void onEvent(ErrorEvent event) { log.info("ErrorEvent: {}", event.getDescription()); sendPlayEnd(session); } }); playerEndpoint.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { log.info("EndOfStreamEvent: {}", event.getTimestamp()); sendPlayEnd(session); } }); playerEndpoint.play(); }