Java Code Examples for org.eclipse.jetty.websocket.api.Session#isOpen()

The following examples show how to use org.eclipse.jetty.websocket.api.Session#isOpen() . 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: ThreadedChatWebSocket.java    From flowchat with GNU General Public License v3.0 6 votes vote down vote up
private void sendRecurringPings(Session session) {
  final Timer timer = new Timer();
  final TimerTask tt = new TimerTask() {
    @Override
    public void run() {
      if (session.isOpen()) {
        sendMessage(session, messageWrapper(MessageType.Ping, "{\"ping\":\"ping\"}"));
      } else {
        timer.cancel();
        timer.purge();
      }
    }
  };

  timer.scheduleAtFixedRate(tt, PING_DELAY, PING_DELAY);
}
 
Example 2
Source File: CliControllerTest.java    From reposilite with Apache License 2.0 5 votes vote down vote up
private void freeze(Session session) throws Exception{
    long uptime = System.currentTimeMillis();

    // Don't let JUnit to interrupt this task for up to 2 seconds
    while (session.isOpen() && (System.currentTimeMillis() - uptime) < 2000) {
        //noinspection BusyWait
        Thread.sleep(50);
    }
}
 
Example 3
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public void removeNoteConnection(String noteId) {
  if (StringUtils.isBlank(noteId)) {
    LOG.error("Cannot remove session for empty noteId");
    return;
  }
  if (notesConnection.containsKey(noteId)) {
    Session connection = notesConnection.get(noteId);
    if (connection.isOpen()) {
      connection.close();
    }
    notesConnection.remove(noteId);
  }
  LOG.info("Removed note websocket connection for note {}", noteId);
}
 
Example 4
Source File: JobAnalysisSocket.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * On connect.
 *
 * @param session
 *            the session
 * @throws Exception
 *             the exception
 */
@OnWebSocketConnect
public void onConnect(Session session) {
	LOGGER.debug("Connected to result socket. Executing job: " + jobName);
	SocketPinger socketPinger = null;
	try {
		socketPinger = new SocketPinger(session);
		new Thread(socketPinger).start();
		String result = getReport();
		if (isJobScheduled(jobName)) {
			session.getRemote().sendString(getScheduledTuningJobResult(jobName));
		} else if (result != null) {
			session.getRemote().sendString(result);
		} else {
			HttpReportsBean reports = triggerJumbuneJob();
			asyncPublishResult(reports, session);
		}

	} catch (Exception e) {
		LOGGER.error(JumbuneRuntimeException.throwException(e.getStackTrace()));
	} finally {
		socketPinger.terminate();
		if (session != null && session.isOpen()) {
			session.close();
		}
		LOGGER.debug("Session closed sucessfully");
	}
}
 
Example 5
Source File: MaxWsConnectionsTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {

  List<Session> clients = new ArrayList<>();

  while (true) {

    URI wsUri = new URI("ws", null, "localhost", Integer.parseInt(getPort()), "/jsonrpc", null,
        null);

    WebSocketClient jettyClient = new WebSocketClient(new SslContextFactory(true));
    jettyClient.start();
    Session session = jettyClient
        .connect(new WebSocketClientSocket(), wsUri, new ClientUpgradeRequest()).get();

    clients.add(session);

    log.debug("WebSocket client {} connected", clients.size());

    Thread.sleep(100);

    if (!session.isOpen()) {
      if (clients.size() < MAX_WS_CONNECTIONS) {
        fail("WebSocket num " + clients.size() + " disconnected. MAX_WS_CONNECTION="
            + MAX_WS_CONNECTIONS);
      } else {
        log.debug("WebSocket client {} disconnected from server", clients.size());
        break;
      }
    } else {

      if (clients.size() > MAX_WS_CONNECTIONS) {
        fail("Server should close automatically WebSocket connection above " + MAX_WS_CONNECTIONS
            + " but it has " + clients.size() + " open connections");
      }
    }
  }

}
 
Example 6
Source File: EventClientTest.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void checkClientConnection() throws Exception {
	
       URI uri = URI.create("ws://localhost:8080/event/?path=c%3A/Work/results/Test.txt");

       WebSocketClient client = new WebSocketClient();
       client.start();
       try {
           
       	Session connection = null;
       	try {
           	final EventClientSocket clientSocket = new EventClientSocket();
                // Attempt Connect
               Future<Session> fut = client.connect(clientSocket, uri);
              
               // Wait for Connect
               connection = fut.get();
               
               // Send a message
               connection.getRemote().sendString("Hello World");
               
               // Close session from the server
               while(connection.isOpen()) {
               	Thread.sleep(100);
               }
           } finally {
               if (connection!=null) connection.close();
           }
       } catch (Throwable t) {
           t.printStackTrace(System.err);
           throw t;
       } finally {
       	client.stop();
       }
   }
 
Example 7
Source File: HttpDmClient.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void process( Session session, Message message ) throws IOException {

	if( session.isOpen()) {
		HttpUtils.sendAsynchronously( message, session.getRemote());

	} else {
		this.logger.finer( "Session is not available anymore. No message can be published." );
	}
}
 
Example 8
Source File: ScriptExecWebSocketNotifier.java    From gp2srv with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void send(ScriptExecution execution, String eventType) {
	for (Session session : ScriptExecutionReportingWebSocketServlet.WEB_SOCKET_SESSIONS) {
		try {
			if (session.isOpen()) {
				session.getRemote().sendString(GSON.toJson(toExecutionInfoDTO(execution, "___", eventType, dumpVars.get(), false)));
			} else {
				ScriptExecutionReportingWebSocketServlet.WEB_SOCKET_SESSIONS.remove(session);
			}
		} catch (Exception e) {
			logger.error("WebSocket send failed", e);
		}
	}
}
 
Example 9
Source File: MinicapServerManager.java    From android-uiconductor with Apache License 2.0 4 votes vote down vote up
public void sendImage(MinicapJettyServer server) {
  Integer port = server.getPort();
  BlockingQueue<byte[]> imgdataQueue = portQueueMapping.get(port);
  Thread sendImgThread =
      new Thread() {
        @Override
        public void run() {
          byte[] buffer = {};
          while (!isInterrupted()) {
            try {
              byte[] candidate = {};

              if (imgdataQueue != null) {
                byte[] currentImg =
                    imgdataQueue.poll(IMG_POLL_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
                if (currentImg == null) {
                  candidate = buffer.clone();
                } else {
                  candidate = currentImg;
                  buffer = candidate.clone();
                }
              } else {
                Thread.sleep(WAIT_FOR_IMG_QUEUE.toMillis());
                continue;
              }

              // not ready
              if (port == null) {
                return;
              }

              // Send the new img to all open WebSocket sessions
              ConcurrentSet<Session> sessions = portSessionMapping.get(port);

              if (sessions == null) {
                continue;
              }

              for (Session session : sessions) {
                if (!session.isOpen()) {
                  portSessionMapping.get(port).remove(session);
                } else {
                  session.getRemote().sendBytes(ByteBuffer.wrap(candidate));
                }
              }
            } catch (Throwable e) {
              // Let the owning Thread know it's been interrupted, so it can clean up
              interrupt();
              logger.info("No data from minicap.");
            }
          }

          logger.info(String.format("Thread id(%s) killed.", this.getId()));
        }
      };
  sendImgThread.start();
  portSendImgThreadMapping.put(port, sendImgThread);
}
 
Example 10
Source File: WebSocketServiceImpl.java    From smockin with Apache License 2.0 4 votes vote down vote up
/**
 *
 * Stores all websocket client sessions in the internal map 'sessionMap'.
 *
 * Note sessions are 'internally' identified using the encrypted handshake 'Sec-WebSocket-Accept' value and
 * 'externally' identified using an allocated UUID.
 *
 */
public void registerSession(final Session session, final boolean isMultiUserMode) {
    logger.debug("registerSession called");

    final String wsPath = session.getUpgradeRequest().getRequestURI().getPath();
    final RestfulMock wsMock = (isMultiUserMode)
            ? restfulMockDAO.findActiveByMethodAndPathPatternAndTypesForMultiUser(
                    RestMethodEnum.GET, wsPath, Arrays.asList(RestMockTypeEnum.PROXY_WS, RestMockTypeEnum.RULE_WS))
            : restfulMockDAO.findActiveByMethodAndPathPatternAndTypesForSingleUser(
                    RestMethodEnum.GET, wsPath, Arrays.asList(RestMockTypeEnum.PROXY_WS, RestMockTypeEnum.RULE_WS));

    if (wsMock == null) {
        if (session.isOpen()) {
            try {
                session.getRemote().sendString("No suitable mock found for " + wsPath);
                session.disconnect();
            } catch(IOException e) {
                logger.error("Error closing non mock matching web socket client connection", e);
            }
        }
        return;
    }

    final String path = mockedRestServerEngineUtils.buildUserPath(wsMock);

    session.setIdleTimeout((wsMock.getWebSocketTimeoutInMillis() > 0) ? wsMock.getWebSocketTimeoutInMillis() : MAX_IDLE_TIMEOUT_MILLIS);

    final Set<SessionIdWrapper> sessions = sessionMap.computeIfAbsent(path, k -> new HashSet<>());
    final String assignedId = GeneralUtils.generateUUID();
    final String traceId = session.getUpgradeResponse().getHeader(GeneralUtils.LOG_REQ_ID);

    sessionMap.merge(
            path, 
            sessions, 
            (k, v) -> {
                v.add(new SessionIdWrapper(assignedId, traceId, session, GeneralUtils.getCurrentDate()));
                return v;
            });

    if (wsMock.isProxyPushIdOnConnect()) {
        sendMessage(assignedId, new WebSocketDTO(path, "clientId: " + assignedId));
    }

    if (wsMock.getMockType() == RestMockTypeEnum.RULE_WS && wsMock.getDefinitions().get(0) != null) {
        RestfulMockDefinitionOrder order = wsMock.getDefinitions().get(0);
        if (order.getResponseBody() != null) {
            sendMessage(assignedId, new WebSocketDTO(path, order.getResponseBody()));
        }

    }

    liveLoggingHandler.broadcast(LiveLoggingUtils.buildLiveLogOutboundDTO(traceId, 101, null,
            "Websocket established (clientId: " + assignedId + ")", false, false));

}
 
Example 11
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private boolean isSessionOpen(Session session) {
  return (session != null) && (session.isOpen());
}
 
Example 12
Source File: AriaddnaWebSocket.java    From ariADDna with Apache License 2.0 3 votes vote down vote up
@OnWebSocketMessage
public void onText(Session session, String message) throws IOException {

    if (session.isOpen()) {

        String response = message.toUpperCase();

        session.getRemote().sendString(response);

    }

}