@OnMessage public void onMessage(Session session, String message, @PathParam("id") Long id, @PathParam("nickname") String nickname) { LOGGER.info("Received message: " + message + " from " + nickname + " and channel n°" + id); JsonObject json = GsonSingleton.getInstance().fromJson(message, JsonObject.class); if (json != null) { String content = json.get(JSON_KEY_CONTENT).getAsString(); Long channelId = json.get(JSON_KEY_CHANNEL_ID).getAsLong(); Long userId = json.get(JSON_KEY_USER_ID).getAsLong(); Message mess = new Message.Builder() .setContent(content) .setChannelId(channelId) .setNickname(nickname) .setUserId(userId) .build(); try (Connection c = DatabaseManager.getConnection()) { MessageDAO messageDAO = new MessageDAO(c); if (messageDAO.create(mess)) manager.broadcast(id, mess, From.Type.CLIENT); } catch (SQLException | InsertionException e) { e.printStackTrace(); } } }
/** * Close the connection and decrement the number of writers and send a * message to notify all others writers. * * @param session * peer session * @param adocId * unique id for this asciidoc file */ @OnClose public void closedConnection(Session session, @PathParam("projectId") String adocId) { if (session.getUserProperties().containsKey("writer")) { handleWriters(adocId, false, (String) session.getUserProperties() .get("writer")); } else { handleReaders(adocId, false); } peers.remove(session); logger.log(Level.INFO, "Connection closed for " + session.getId()); // send a message to all peers to inform that someone is disonnected sendNotificationMessage(createNotification(adocId), adocId); }
@OnOpen public void onOpen(Session session, @PathParam("uuid") String uuid) { UUID key = UUID.fromString(uuid); peers.put(key, session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusEventType statusEventType : StatusEventType.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusEventType.name(), statusEventType.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@OnOpen public void open(@PathParam("gametype") String gameID, Session session) throws IOException { type = GameType.getGameType(gameID); if(type == null) { session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Invalid game type")); return; } Basic sender = session.getBasicRemote(); viewer = data -> { synchronized(session) { if(session.isOpen()) try { sender.sendBinary(data); } catch (IOException e) {} } }; DisplayHandler.addGlobalViewer(viewer); }
@OnOpen public void userConnectedCallback(@PathParam("user") String user, Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendText("Username " + user + " has been taken. Retry with a different name"); s.close(); return; } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } } this.s = s; s.getUserProperties().put("user", user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
@OnOpen public void userConnectedCallback(@PathParam("user") String user, Session s) { if (USERS.contains(user)) { try { dupUserDetected = true; s.getBasicRemote().sendObject(new DuplicateUserNotification(user)); s.close(); return; } catch (Exception ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } } this.s = s; SESSIONS.add(s); s.getUserProperties().put("user", user); this.user = user; USERS.add(user); welcomeNewJoinee(); announceNewJoinee(); }
@OnMessage public void onWebSocketText(final Session sess, final JSONRPC2Message msg, @PathParam(CCOWContextListener.PATH_NAME) final String applicationName) { if (msg instanceof JSONRPC2Request) { //All operations that are invokable on ContextManager that does not return void logger.debug("The message is a Request"); } else if (msg instanceof JSONRPC2Notification) { //All operations that are invokable on ContextManager that does return void logger.debug("The message is a Notification"); } else if (msg instanceof JSONRPC2Response) { //All operations that are invokable from ContextManager that does not return void and are initially called from ContextManager participant.onMessage((JSONRPC2Response) msg); logger.debug("The message is a Response"); } }
@OnMessage public void requestEventTracking(@PathParam("trackingPin") String trackingPin, String message, Session session) { myLog.debug("requestEventTracking: " + trackingPin); try { if (session.isOpen()) { SecqMeEventVO eventVO = eventManager.getEventByTrackingPin(trackingPin); FullEventInfoVO eventInfoVO = eventManager.getFullEventInfoOfContact(eventVO.getId()); session.getBasicRemote().sendText(eventInfoVO.toJSON().toString()); } } catch (IOException ex) { myLog.error("Tracking event web socket error: " + trackingPin, ex); try { session.close(); } catch (IOException ex1) { // Ignore } } }
/** * Open a socket connection to a client from the web server * * @param session The session that just opened */ @OnOpen public void openSocket(@PathParam(RT_COMPUTE_ENDPOINT_PARAM) ConnectionType type, Session session) { session.setMaxIdleTimeout(0); String sessionId = session.getId(); if (type == ConnectionType.SUBSCRIBER) { LOG.info("Got a new subscriber connection request with ID {}. Saving session", sessionId); // cleanup sessions Set<Session> closedSessions = Sets.newHashSet(); for (Session existingSession : sessions) { if (!existingSession.isOpen()) { closedSessions.add(existingSession); } } sessions.removeAll(closedSessions); sessions.add(session); LOG.info("Active sessions {}. Collecting {} sessions", sessions.size(), closedSessions.size()); } else { LOG.info("Got a new publisher connection request with ID {}", sessionId); } }
@OnOpen public void onOpen(Session session,@PathParam("username") String username) { try{ client.add(session); user.put(URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(username, "UTF-8")); JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); //获得在线用户列表 Set<String> key = user.keySet(); for (String u : key) { ja.add(u); } jo.put("onlineUser", ja); session.getBasicRemote().sendText(jo.toString()); }catch(Exception e){ //do nothing } }
@OnOpen public void onOpen(Session session, @PathParam("uuid") String uuid) { UUID key = UUID.fromString(uuid); peers.put(key, session); JsonArrayBuilder builder = Json.createArrayBuilder(); for (StatusMessage statusMessage : StatusMessage.values()) { JsonObjectBuilder object = Json.createObjectBuilder(); builder.add(object.add(statusMessage.name(), statusMessage.getMessage()).build()); } RemoteEndpoint.Async asyncRemote = session.getAsyncRemote(); asyncRemote.sendText(builder.build().toString()); // Send pending messages List<String> messages = messageBuffer.remove(key); if (messages != null) { messages.forEach(asyncRemote::sendText); } }
@OnMessage public void message(final Session session, BetMessage msg, @PathParam("match-id") String matchId) { logger.log(Level.INFO, "Received: Bet Match Winner - {0}", msg.getWinner()); //check if the user had already bet and save this bet boolean hasAlreadyBet = session.getUserProperties().containsKey("bet"); session.getUserProperties().put("bet", msg.getWinner()); //Send betMsg with bet count if (!nbBetsByMatch.containsKey(matchId)){ nbBetsByMatch.put(matchId, new AtomicInteger()); } if (!hasAlreadyBet){ nbBetsByMatch.get(matchId).incrementAndGet(); } sendBetMessages(null, matchId, false); }
private boolean validateOnOpenMethod(Object webSocketEndpoint) throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException { EndpointDispatcher dispatcher = new EndpointDispatcher(); Method method; if (dispatcher.getOnOpenMethod(webSocketEndpoint).isPresent()) { method = dispatcher.getOnOpenMethod(webSocketEndpoint).get(); } else { return true; } validateReturnType(method); for (Parameter parameter: method.getParameters()) { Class<?> paraType = parameter.getType(); if (paraType == String.class) { if (parameter.getAnnotation(PathParam.class) == null) { throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " + "string parameter without " + "@PathParam annotation."); } } else if (paraType != Session.class) { throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " + paraType); } } return true; }
private boolean validateOnCloseMethod(Object webSocketEndpoint) throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException { EndpointDispatcher dispatcher = new EndpointDispatcher(); Method method; if (dispatcher.getOnCloseMethod(webSocketEndpoint).isPresent()) { method = dispatcher.getOnCloseMethod(webSocketEndpoint).get(); } else { return true; } validateReturnType(method); for (Parameter parameter: method.getParameters()) { Class<?> paraType = parameter.getType(); if (paraType == String.class) { if (parameter.getAnnotation(PathParam.class) == null) { throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " + "string parameter without " + "@PathParam annotation."); } } else if (paraType != CloseReason.class && paraType != Session.class) { throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " + paraType); } } return true; }
/** * Extract OnMessage method for String from the endpoint if exists. * * @param webSocketEndpoint Endpoint to extract method. * @return method optional to handle String messages. */ public Optional<Method> getOnStringMessageMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); Method returnMethod = null; for (Method method : methods) { if (method.isAnnotationPresent(OnMessage.class)) { Parameter[] parameters = method.getParameters(); for (Parameter parameter: parameters) { if (!parameter.isAnnotationPresent(PathParam.class) && parameter.getType() == String.class) { returnMethod = method; } } } } return Optional.ofNullable(returnMethod); }
private void handleError(Throwable throwable, PatternPathRouter.RoutableDestination<Object> routableEndpoint, Session session) { Object webSocketEndpoint = routableEndpoint.getDestination(); Map<String, String> paramValues = routableEndpoint.getGroupNameValues(); Optional<Method> methodOptional = new EndpointDispatcher().getOnErrorMethod(webSocketEndpoint); methodOptional.ifPresent(method -> { List<Object> parameterList = new LinkedList<>(); Arrays.stream(method.getParameters()).forEach(parameter -> { if (parameter.getType() == Throwable.class) { parameterList.add(throwable); } else if (parameter.getType() == Session.class) { parameterList.add(session); } else if (parameter.getType() == String.class) { PathParam pathParam = parameter.getAnnotation(PathParam.class); if (pathParam != null) { parameterList.add(paramValues.get(pathParam.value())); } } else { parameterList.add(null); } }); executeMethod(method, webSocketEndpoint, parameterList, session); }); }
/** * Message is received from the JS client * * @param message * @param session * @throws IOException */ @OnMessage public void onMessage(@PathParam("userId") String userId, RoutedMessage message, Session session) throws IOException { Log.log(Level.FINEST, this, "C -> M R : {0}", message); try { if (message.getFlowTarget() == FlowTarget.ready) { // wait to process the ready message until we've validated the JWT (see onOpen) mediatorCheck.await(); clientMediator.ready(message); goodToGo = true; // eventually all threads will see that we're happy } else if (goodToGo || mediatorCheck.getCount() == 0) { // we will eventually see the goodToGo check, which will bypass having to look @ the latch clientMediator.handleMessage(message); } else { Log.log(Level.FINEST, session, "no session, dropping message from client {0}: {1}", userId, message); return; } } catch (Exception e) { Log.log(Level.WARNING, session, "Uncaught exception handling room-bound message", e); } }
@OnMessage public void handleSubscribeMessage(Session session, String msg, @PathParam("topic") String topic) { { if (session.isOpen()) { if(topic!=null && !topic.trim().isEmpty()){ System.out.println("We have a clinet for: " + topic); PublicationsManager.getInstance().onSubscribe(session,topic.trim()); } else{ try { session.getBasicRemote().sendText("Please use a valid topic name to subscribe"); } catch (IOException e) { //Ignore topic was null anyways cannot do much about this client } } } } }
@OnMessage public void onMessage(String message, Session session, @PathParam("user") String user) { switch (session.getNegotiatedSubprotocol()) { case "text": getTextMessageHandler().onMessage(message, session, user); break; case "json": try { getJsonMessageHandler().onMessage(JacksonSupport.objectMapper.readTree(message), session, user); } catch (Exception e) { logger.error("process message:[{}] due to error:[{}]", message, ExceptionUtils.getStackTrace(e)); } break; case "echo": session.getAsyncRemote().sendText(String.format("reply from server:[%s]", message)); break; } }
/** * Callback when receiving opened connection from client side * * @param session the client {@link Session} * @param config the associated {@link EndpointConfig} to the new connection * @param executionId the execution identifier from the {@link ServerEndpoint} path */ @OnOpen public void openConnection(Session session, EndpointConfig config, @PathParam("execution-id") long executionId) { if (LOG.isDebugEnabled()) { LOG.debug("Session " + session.getId() + " opened connection to execution " + executionId); } mainLock.lock(); try { sessions.put(session.getId(), session); Set<String> registeredSessions = executions.get(executionId); if (registeredSessions == null) { registeredSessions = new HashSet<>(); } registeredSessions.add(session.getId()); executions.put(executionId, registeredSessions); } finally { mainLock.unlock(); } }
/** * Callback when receiving closed connection from client side * * @param session the client {@link Session} * @param executionId the execution identifier from the {@link ServerEndpoint} path */ @OnClose public void closedConnection(Session session, @PathParam("execution-id") long executionId) { if (LOG.isDebugEnabled()) { LOG.debug("Session " + session.getId() + " closed connection to execution " + executionId); } mainLock.lock(); try { sessions.remove(session.getId()); Set<String> registeredSessions = executions.get(executionId); if (registeredSessions != null) { registeredSessions.remove(session.getId()); } } finally { mainLock.unlock(); } }
@OnOpen public void onOpen(Session session, EndpointConfig config, @PathParam("id") Long id, @PathParam("nickname") String nickname) throws IOException { LOGGER.info("onOpen " + id + ": " + session.toString()); manager.add(session, id); Message message = new Message.Builder() .setContent("Welcom " + nickname + "!") .setNickname(nickname) .build(); manager.broadcast(id, message, From.Type.SERVER); }
@OnClose public void onClose(Session session, CloseReason reason, @PathParam("id") Long id, @PathParam("nickname") String nickname) throws IOException { //prepare the endpoint for closing. LOGGER.info("onClose: " + session.toString()); manager.remove(session, id); Message json = new Message.Builder() .setContent("Bye bye " + nickname + "...") .setNickname(nickname) .build(); manager.broadcast(id, json, From.Type.SERVER); }
@OnMessage public void onMessage(@PathParam("ws") String ws, @PathParam("lang") String lang, String message, Session session) { if ( message.length() == 0 ) return; // This is just ping! IdleTimeHolder.getInstance().registerUserActivity(); LOG.info("LSP: onMessage is invoked: \n" + message); LOG.info(String.format("LSP: get Head Process for wsKey %s lang %s session %s", ws, lang, session.getId())); LSPProcess lspProc = procManager.getProcess(LSPProcessManager.processKey(ws, lang)); lspProc.enqueueCall(message); }
@OnClose public void onClose(@PathParam("ws") String ws, @PathParam("lang") String lang, Session session, CloseReason reason ) { Map<String,List<String>> reqParam = session.getRequestParameterMap(); if ( reqParam != null && reqParam.containsKey("local") ) { return; } LOG.info("LSP: OnClose is invoked"); LSPProcess process = procManager.getProcess(LSPProcessManager.processKey(ws, lang)); if (process != null) { registerWSSyncListener(LSPProcessManager.processKey(process.getProjPath(), lang), "/" + ws + "/" + lang, false); procManager.cleanProcess(ws, lang, session.getId()); } }
@OnOpen public void onOpen(final Session session, @PathParam("id") String id) { session.setMaxIdleTimeout(0); SimulationModel model = simStore.get(UUID.fromString(id)); Simulation sim = model.getSimulation(); SimulationWrapper wrapper = (SimulationWrapper) model.getWrapper(sim); Runnable sendConfigurationUpdate = () -> { if(sim.getController().isPaused() || !sim.getController().isActive()) { return; } sim.getController().doActionNow(() -> { Boundary[] boundaries = new Boundary[sim.getBoxCount()]; for (int i = 0; i < sim.getBoxCount(); i++) { boundaries[i] = sim.getBox(i).getBoundary(); } ConfigurationUpdate update = new ConfigurationUpdate( wrapper.getAllCoordinates(), boundaries ); session.getAsyncRemote().sendObject(update); }); }; ScheduledFuture<?> task = executor.scheduleWithFixedDelay(sendConfigurationUpdate, 0, 33, TimeUnit.MILLISECONDS); session.getUserProperties().put("task", task); }
@OnOpen public void onOpen(final Session session, @PathParam("simId") String simId, @PathParam("dataId") String dataId) { session.setMaxIdleTimeout(0); session.getUserProperties().put("mapper", mapper); SimulationModel model = simStore.get(UUID.fromString(simId)); Simulation sim = model.getSimulation(); DataStreamStore.DataPlumbing dataPlumbing = dataStore.get(UUID.fromString(dataId)); DataDump dump = dataPlumbing.getDump(); final DataAndInfo dataAndInfo = new DataAndInfo(); Runnable sendData = () -> { if(sim.getController().isPaused() || !sim.getController().isActive()) { return; } sim.getController().doActionNow(() -> { IData data = dump.getData(); dataAndInfo.setData(dump.getData()); dataAndInfo.setDataInfo(dump.getDataInfo()); if(data != null) { session.getAsyncRemote().sendObject(dataAndInfo); } }); }; ScheduledFuture<?> task = executor.scheduleWithFixedDelay(sendData, 0, 333, TimeUnit.MILLISECONDS); session.getUserProperties().put("task", task); // add on construction // model.getSimulation().getIntegrator().getEventManager().addListener(dataPlumbing.getPump()); }
@OnOpen public void open(Session session, @PathParam(value = "user")String user) { Session session1 = sessionMap.get(user); if (null != session1) { try { session1.close(); } catch (IOException e) { e.printStackTrace(); } } sessionMap.put(user, session); log.info("*** WebSocket opened from sessionId " + session.getId()); }
@OnOpen public void opened(@PathParam("user") String user, Session session, EndpointConfig config) throws IOException{ System.out.println("opened() Current thread "+ Thread.currentThread().getName()); this.httpSession = (HttpSession) config.getUserProperties().get(user); System.out.println("User joined "+ user + " with http session id "+ httpSession.getId()); String response = "User " + user + " | WebSocket session ID "+ session.getId() +" | HTTP session ID " + httpSession.getId(); System.out.println(response); session.getBasicRemote().sendText(response); }
/** * Heartbeat endpoint. * Registers that the client is still there and updates configuration * if changed. * * @param clientId The client id * @param applicationConfig The updated configuration */ @OnMessage public void onMessage(@PathParam("clientId") String clientId, String applicationConfig) { LOGGER.config(() -> "Client: " + clientId + ", status: " + applicationConfig); if (applicationConfig != null && !applicationConfig.isEmpty()) { clients.register(fromJSON(applicationConfig)); } else { clients.deRegister(clientId); } }
@OnMessage public void onMessage(String message, Session session,@PathParam("username") String username) { try{ JSONObject jo = new JSONObject(); JSONObject inner = new JSONObject(); inner.put("message", message); inner.put("username", username); jo.put("onlineMessage", inner); for (Session c : client) { c.getBasicRemote().sendText(jo.toString()); } }catch(Exception e){ //do nothing } }
@OnClose public void onClose(Session session,@PathParam("username") String username) { try{ client.remove(session); user.remove(URLEncoder.encode(username, "UTF-8")); session.close(); }catch(Exception e){ //do nothing } }
@OnOpen public void onOpen(Session session, @PathParam("sensor") String sensor) { if ("ALL".equals(sensor)) { sensor = null; } send(sensor, session); sessions.add(sensor, session); }
@OnOpen public void openConnection(Session session, @PathParam("projectId") String adocId) { logger.log(Level.INFO, "Session ID : " + session.getId() + " - Connection opened for doc : " + adocId); session.getUserProperties().put(adocId, true); peers.add(session); // send a message to all peers to inform that someone is connected handleReaders(adocId, true); if (!writersByAdoc.containsKey(adocId)) { writersByAdoc.put(adocId, new HashSet<String>()); } sendNotificationMessage(createNotification(adocId), adocId); }
@OnOpen public void openConnection(Session session, @PathParam("match-id") String matchId) { logger.log(Level.INFO, "Session ID : " + session.getId() +" - Connection opened for match : " + matchId); session.getUserProperties().put(matchId, true); peers.add(session); //Send live result for this match try { send(new MatchMessage(ejbService.getMatchFromCache(new Long(matchId))), matchId); } catch (Exception e){ logger.severe("Error to get match from cache." + e.getCause()); } }
@OnClose public void closedConnection(Session session, @PathParam("match-id") String matchId) { if (session.getUserProperties().containsKey("bet")){ /* Remove bet */ nbBetsByMatch.get(matchId).decrementAndGet(); sendBetMessages(null, matchId, false); } /* Remove this connection from the queue */ peers.remove(session); logger.log(Level.INFO, "Connection closed."); }
@OnOpen public void open(Session conn, EndpointConfig config, @PathParam("projectID") String projectId) throws AppException { try { this.session = conn; this.sender = (String) config.getUserProperties().get("user"); this.project = getProject(projectId); authenticateUser(conn, this.project, this.sender); if (this.userRole == null) { LOG.log(Level.INFO, "User not authorized for Zeppelin Access: {0}", this.sender); return; } if (project.getPaymentType().equals(PaymentType.PREPAID)) { YarnProjectsQuota projectQuota = yarnProjectsQuotaFacade.findByProjectName(project.getName()); if (projectQuota == null || projectQuota.getQuotaRemaining() < 0) { session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "This project is out of credits.")); return; } } this.impl = notebookServerImplFactory.getNotebookServerImps(project.getName(), conn); if (impl.getConf() == null) { impl.removeConnectedSockets(conn, notebookServerImplFactory); LOG.log(Level.INFO, "Could not create Zeppelin config for user: {0}, project: {1}", new Object[]{this.sender, project.getName()}); return; } addUserConnection(this.hdfsUsername, conn); addUserConnection(project.getProjectGenericUser(), conn); this.session.getUserProperties().put("projectID", this.project.getId()); String httpHeader = (String) config.getUserProperties().get(WatcherSecurityKey.HTTP_HEADER); this.session.getUserProperties().put(WatcherSecurityKey.HTTP_HEADER, httpHeader); impl.unicast(new Message(OP.CREATED_SOCKET), conn); } catch (IOException | RepositoryException | TaskRunnerException ex) { throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ex.getMessage()); } }
/** * Invoked when a client connects to the server * @param session * @param clientType - type of the client */ @OnOpen public void onOpen(Session session, EndpointConfig endConfig, @PathParam("clientType") String clientType) { logger.log(Level.INFO,"Connection has been established."); consumer = context.createConsumer(topic); consumer.setMessageListener(null); producer = context.createProducer(); producer.send(topic,"Hello World!"); }