javax.websocket.OnOpen Java Examples

The following examples show how to use javax.websocket.OnOpen. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocket.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
@OnOpen
  public void onOpen(Session session, @PathParam(value="userId")String userId) {
      try {
	this.session = session;
	webSockets.add(this);
	sessionPool.put(userId, session);
	log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
} catch (Exception e) {
}
  }
 
Example #2
Source File: WebSocket.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
@OnOpen
  public void onOpen(Session session, @PathParam(value="userId")String userId) {
      try {
	this.session = session;
	webSockets.add(this);
	sessionPool.put(userId, session);
	log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
} catch (Exception e) {
}
  }
 
Example #3
Source File: Notification.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Callback executed when the WebSocket is opened.
 * @param session the WebSocket session
 * @param config the EndPoint config
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
    if (session != null) {
        Optional.ofNullable(session.getUserProperties().get("webUserID"))
                .map(webUserID -> (Long) webUserID)
                .ifPresentOrElse(userId -> {
                    LOG.debug(String.format("Hooked a new websocket session [id:%s]", session.getId()));
                    handshakeSession(userId, session);

                    // update the notification counter to the unread messages
                    try {
                        sendMessage(session,
                                String.valueOf(UserNotificationFactory.unreadUserNotificationsSize(userId)));
                    }
                    finally {
                        HibernateFactory.closeSession();
                    }
                },
                ()-> LOG.debug("no authenticated user."));
    }
    else {
        LOG.debug("No web sessionId available. Closing the web socket.");
    }
}
 
Example #4
Source File: ThreadSafetyEndpoint.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@OnOpen
public void onOpen(final Session session) {
    s = session;
    for (int i = 0; i < NUM_THREADS; ++i) {
        final int tnum = i;
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < NUM_MESSAGES; ++j) {
                    session.getAsyncRemote().sendText("t" + tnum + "-m" + j);
                }
            }
        });
        t.start();
    }
}
 
Example #5
Source File: LearningWebsocketServer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Registeres the Learner for processing.
    */
   @OnOpen
   public void registerUser(Session websocket) throws IOException {
Long toolContentID = Long
	.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_CONTENT_ID).get(0));
String login = websocket.getUserPrincipal().getName();
DokumaranUser user = LearningWebsocketServer.getDokumaranService().getUserByLoginAndContent(login,
	toolContentID);
if (user == null) {
    throw new SecurityException("User \"" + login
	    + "\" is not a participant in Dokumaran activity with tool content ID " + toolContentID);
}

Set<Session> toolContentWebsockets = websockets.get(toolContentID);
if (toolContentWebsockets == null) {
    toolContentWebsockets = ConcurrentHashMap.newKeySet();
    websockets.put(toolContentID, toolContentWebsockets);
}
toolContentWebsockets.add(websocket);

if (log.isDebugEnabled()) {
    log.debug("User " + login + " entered Dokumaran with toolContentId: " + toolContentID);
}
   }
 
Example #6
Source File: MessageWebsocket.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 连接建立成功调用的方法
 */
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
    this.session = session;
    this.userId = userId;
    if (webSocketMap.containsKey(userId)) {
        webSocketMap.remove(userId);
        webSocketMap.put(userId, this);
        //加入set中
    } else {
        webSocketMap.put(userId, this);
        //加入set中
        addOnlineCount();
        //在线数加1
    }


    logger.debug("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());

    try {
        sendMessage("连接成功");
    } catch (IOException e) {
        logger.error("用户:" + userId + ",网络异常!!!!!!");
    }
}
 
Example #7
Source File: LibertyWsBrowserEndpoint.java    From rogue-cloud with Apache License 2.0 6 votes vote down vote up
@OnOpen
public void open(Session session) {
	
	// If the client instance is disposed, then immediately close all opened Sessions 
	if(LibertyClientInstance.getInstance().isDisposed()) {
		log.interesting("Ignoring onOpen on an endpoint with a closed LibertyClientInstance", null);
		try { session.close(); } catch (IOException e) {  /*ignore*/ }
		return;
	}

	System.out.println("WebSocket "+session.getId()+" opened for Web browser on client instance "+LibertyClientInstance.getInstance().getUuid());
	ResourceLifecycleUtil.getInstance().addNewSession(
			ClientUtil.convertSessionToManagedResource(session));
	
	LibertyClientInstance.getInstance().add(session);
}
 
Example #8
Source File: OnlineNoticeServer.java    From belling-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 连接建立成功调用的方法-与前端JS代码对应
 * 
 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
	// 单个会话对象保存
	this.session = session;
	webSocketSet.add(this); // 加入set中
	this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	String uId = (String) httpSession.getAttribute("userid"); // 获取当前用户
	String sessionId = httpSession.getId();
	this.userid = uId + "|" + sessionId;
	if (!OnlineUserlist.contains(this.userid)) {
		OnlineUserlist.add(userid); // 将用户名加入在线列表
	}
	routetabMap.put(userid, session); // 将用户名和session绑定到路由表
	System.out.println(userid + " -> 已上线");
	String message = getMessage(userid + " -> 已上线", "notice", OnlineUserlist);
	broadcast(message); // 广播
}
 
Example #9
Source File: KumaliveWebsocketServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@OnOpen
   public void registerUser(Session websocket) throws IOException {
Integer organisationId = Integer
	.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0));
Integer userId = getUser(websocket).getUserId();
if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId,
	new String[] { Role.GROUP_MANAGER, Role.MONITOR, Role.LEARNER }, "register on kumalive", false)) {
    // prevent unauthorised user from accessing Kumalive
    String warning = "User " + userId + " is not a monitor nor a learner of organisation " + organisationId;
    logger.warn(warning);
    websocket.close(new CloseReason(CloseCodes.CANNOT_ACCEPT, warning));
}
   }
 
Example #10
Source File: TomcatWebSocketEndpoint.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(Session session) {
    sessionSet.add(session);
    int cnt = onlineCount.incrementAndGet(); // 在线数加1
    log.info("有连接加入,当前连接数为:{}", cnt);
    sendMessage(session, "连接成功");
}
 
Example #11
Source File: WebSocketClientEndpoint.java    From rogue-cloud with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void open(Session session) {
	System.out.println("open.");
	
	session.setMaxIdleTimeout(2 * TimeUnit.MILLISECONDS.convert(RCSharedConstants.MAX_ROUND_LENGTH_IN_NANOS, TimeUnit.NANOSECONDS));
	
	// Convert the session to a 'managed resource', so that it will automatically be disposed of once it expires.
	ResourceLifecycleUtil.getInstance().addNewSession(ServerWsClientUtil.convertSessionToManagedResource(session));
}
 
Example #12
Source File: GameRoundWebsocket.java    From liberty-bikes with Eclipse Public License 1.0 5 votes vote down vote up
@OnOpen
public void onOpen(@PathParam("roundId") String roundId, Session session) {
    log(roundId, "Opened a session");
    session.setMaxTextMessageBufferSize(1000);
    session.setMaxBinaryMessageBufferSize(1000);
    session.setMaxIdleTimeout(90 * 1000);
    timerContext = GameMetrics.timerStart(GameMetrics.openWebsocketTimerMetadata);
}
 
Example #13
Source File: LearningWebsocketServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Registeres the Learner for processing by SendWorker.
    */
   @OnOpen
   public void registerUser(Session websocket) throws IOException {
Long toolSessionId = Long
	.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
String login = websocket.getUserPrincipal().getName();
MindmapUser user = LearningWebsocketServer.getMindmapService().getUserByLoginAndSessionId(login, toolSessionId);
if (user == null) {
    throw new SecurityException("User \"" + login
	    + "\" is not a participant in Mindmap activity with tool session ID " + toolSessionId);
}

Long lastActionId = Long.valueOf(websocket.getRequestParameterMap().get("lastActionId").get(0));
Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId);
if (sessionWebsockets == null) {
    sessionWebsockets = ConcurrentHashMap.newKeySet();
    LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets);
}
sessionWebsockets.add(websocket);

if (LearningWebsocketServer.log.isDebugEnabled()) {
    LearningWebsocketServer.log.debug("User " + login + " entered Mindmap with toolSessionId: " + toolSessionId
	    + " lastActionId: " + lastActionId);
}

new Thread(() -> {
    try {
	HibernateSessionManager.openSession();
	SendWorker.send(toolSessionId, websocket, lastActionId);
    } catch (Exception e) {
	log.error("Error while sending messages", e);
    } finally {
	HibernateSessionManager.closeSession();
    }
}).start();
   }
 
Example #14
Source File: TestPojoEndpointBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(@SuppressWarnings("unused") Session session,
        EndpointConfig config) {
    if (config == null) {
        throw new RuntimeException();
    }
}
 
Example #15
Source File: WebSocket.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
@OnOpen
  public void onOpen(Session session, @PathParam(value="userId")String userId) {
      try {
	this.session = session;
	webSockets.add(this);
	sessionPool.put(userId, session);
	log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
} catch (Exception e) {
}
  }
 
Example #16
Source File: ConvertingResultSocketServer.java    From synchronizing-doc-convert-results with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen (Session session, @PathParam(value = "convertId") Integer convertId) {
    this.session = session;
    this.convertId = convertId;
    convertHashMap.put(convertId, this);
    sessionPool.put(convertId.toString(), session);
    logger.info("new  convert job in , the convertId is :" + convertId.toString());
}
 
Example #17
Source File: ZydWebsocketServer.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 连接建立成功调用的方法
 */
@OnOpen
public void onOpen(Session session) {
    webSocketSet.add(session);
    int count = onlineCount.incrementAndGet();
    log.info("[Socket] 有链接加入,当前在线人数为: {}", count);

    WebSocketUtil.sendOnlineMsg(Integer.toString(count), webSocketSet);
}
 
Example #18
Source File: CommandWebsocketServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Registeres the Learner for processing by SendWorker.
    */
   @OnOpen
   public void registerUser(Session websocket) throws IOException {
Long lessonId = Long.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0));
Map<String, Session> sessionWebsockets = CommandWebsocketServer.websockets.get(lessonId);
if (sessionWebsockets == null) {
    sessionWebsockets = new ConcurrentHashMap<>();
    CommandWebsocketServer.websockets.put(lessonId, sessionWebsockets);
}

String login = websocket.getUserPrincipal().getName();
sessionWebsockets.put(login, websocket);
   }
 
Example #19
Source File: JavametricsWebSocket.java    From javametrics with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void open(Session session) {
    try {
        session.getBasicRemote().sendText(
                "{\"topic\": \"title\", \"payload\": {\"title\":\"Application Metrics for Java\", \"docs\": \"http://github.com/RuntimeTools/javametrics\"}}");
    } catch (IOException e) {
        e.printStackTrace();
    }
    openSessions.add(session);
    DataHandler.registerEmitter(this);
}
 
Example #20
Source File: WebSocketServer.java    From grain with MIT License 5 votes vote down vote up
@OnOpen
public void onOpen(Session session) {

	try {
		MsgManager.dispatchMsg(WSMsg.WEBSOCKET_CLIENT_CREATE_CONNECT, null, session);
	} catch (Exception e) {
		if (WSManager.log != null) {
			WSManager.log.error("MsgManager.dispatchMsg error", e);
		}
	}
}
 
Example #21
Source File: LearningWebsocketServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Registers the Learner for processing by SendWorker.
    */
   @OnOpen
   public void registerUser(Session websocket) throws IOException {
Long toolSessionId = Long
	.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
String login = websocket.getUserPrincipal().getName();
ScribeUser user = LearningWebsocketServer.getScribeService().getUserByLoginNameAndSessionId(login,
	toolSessionId);
if (user == null) {
    throw new SecurityException("User \"" + login
	    + "\" is not a participant in Scribe activity with tool session ID " + toolSessionId);
}

Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId);
if (sessionWebsockets == null) {
    sessionWebsockets = ConcurrentHashMap.newKeySet();
    LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets);
}
sessionWebsockets.add(websocket);

if (LearningWebsocketServer.log.isDebugEnabled()) {
    LearningWebsocketServer.log.debug("User " + login + " entered Scribe with toolSessionId: " + toolSessionId);
}

new Thread(() -> {
    try {
	HibernateSessionManager.openSession();
	SendWorker.send(toolSessionId, websocket);
    } catch (Exception e) {
	log.error("Error while sending messages", e);
    } finally {
	HibernateSessionManager.closeSession();
    }
}).start();
   }
 
Example #22
Source File: CodingClient.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(Session session) {
    sessions.add(session);

    Dto data = new Dto();
    data.setContent("initial data");
    session.getAsyncRemote().sendObject(data);
}
 
Example #23
Source File: EventEndpoint.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@OnOpen
public void onOpen(final Session session) {
	if (!registered) {
		EventCollector eventCollector = (EventCollector) Context.get().getBean(EventCollector.class);
		eventCollector.addListener(this);
		registered = true;
	}

	log.debug("onOpen({})", session.getId());
	peers.add(session);
}
 
Example #24
Source File: ChatAnnotation.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@OnOpen
public void start(Session session) {
    this.session = session;
    connections.add(this);
    String message = String.format("* %s %s", nickname, "has joined.");
    broadcast(message);
}
 
Example #25
Source File: WSSHWebSocket.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
	HttpSession httpSession = (HttpSession) config.getUserProperties()
	           .get(HttpSession.class.getName());
    logger.debug("一个WSSH用户连接,httpSessionId:{}, webSocketSessionId:{}", httpSession.getId(), session.getId());
    httpSessionId = httpSession.getId();
    WebSSHService webSSHService= SpringContextHelper.getSpringBean(WebSSHService.class);
    webSSHService.initConnection(session, httpSession.getId());
}
 
Example #26
Source File: ChatTestCase.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void open(Session session) {
    MESSAGES.add("CONNECT");
    // Send a message to indicate that we are ready,
    // as the message handler may not be registered immediately after this callback.
    session.getAsyncRemote().sendText("_ready_");
}
 
Example #27
Source File: webServer.java    From webChat with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void open(Session session, @PathParam("uid") int uid) {
    SocketUser user = new SocketUser();
    user.setSession(session);
    user.setUserId(uid);

    // 保存在线列表
    WebChatFactory.createManager().addUser(user);
    userLogService.insertLog(user, UserLogType.LOGIN);
    print("当前在线用户:" + WebChatFactory.createManager().getOnlineCount());
    print("缓存中的用户个数:" + new OnLineUserManager().getOnLineUsers().size());
    //通知所有人
    String message = MessageParse.ServiceOnlineStatus(uid, OnlineStatus.ONLINE);
    WebChatFactory.createManager().notifyOthers(user, message);
}
 
Example #28
Source File: WebSocketController.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 连接建立成功调用的方法
 *
 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
 */
@OnOpen
public void onOpen(Session session) {
  this.session = session;
  webSocketSet.add(this);     //加入set中
  addOnlineCount();           //在线数加1
  log.debug("有新连接加入!当前在线人数为" + getOnlineCount());
}
 
Example #29
Source File: RemoteMinionCommands.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Callback executed when the websocket is opened.
 * @param session the websocket session
 * @param config the endpoint config
 */
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
    this.sessionId = LocalizedEnvironmentFilter.getCurrentSessionId();
    if (this.sessionId == null) {
        try {
            LOG.debug("No web sessionId available. Closing the web socket.");
            session.close();
        }
        catch (IOException e) {
            LOG.debug("Error closing web socket session", e);
        }
    }
}
 
Example #30
Source File: OnlineNumberSocketServer.java    From synchronizing-doc-convert-results with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen (Session session) {
    this.session = session;
    clientWebSet.add(this);
    addOnlineNumber();
    logger.info("new man in , now has :" + getOnlineNumber());
    this.infoAllClient();
}