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

The following examples show how to use org.eclipse.jetty.websocket.api.Session#close() . 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: NotebookServerTest.java    From submarine with Apache License 2.0 7 votes vote down vote up
@Test
public void testWebsocketConnection() throws Exception{
  URI uri = URI.create(
      AbstractSubmarineServerTest.getWebsocketApiUrlToTest());
  WebSocketClient client = new WebSocketClient();
  try {
    client.start();
    // The socket that receives events
    EventSocket socket = new EventSocket();
    // Attempt Connect
    Future<Session> fut = client.connect(socket, uri);
    // Wait for Connect
    Session session = fut.get();
    // Send a message
    session.getRemote().sendString("Hello");
    // Close session
    //session.close();
    session.close(StatusCode.NORMAL, "I'm done");
  } finally {
    client.stop();
  }
}
 
Example 2
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private Session openNoteSession(String noteId, String principal, String ticket) {
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  request.setHeader(ORIGIN, "*");
  ZeppelinWebsocket socket = new ZeppelinWebsocket(noteId);
  Future<Session> future = null;
  Session session = null;
  try {
    future = wsClient.connect(socket, zeppelinWebsocketUrl, request);
    session = future.get();
  } catch (IOException | InterruptedException | ExecutionException e) {
    LOG.error("Couldn't establish websocket connection to Zeppelin ", e);
    return session;
  }

  if (notesConnection.containsKey(noteId)) {
    session.close();
    session = notesConnection.get(noteId);
  } else {
    String getNote = serialize(zeppelinGetNoteMsg(noteId, principal, ticket));
    session.getRemote().sendStringByFuture(getNote);
    notesConnection.put(noteId, session);
  }
  return session;
}
 
Example 3
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 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: SimpleEchoSocket.java    From java_rosbridge with GNU Lesser General Public License v3.0 5 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session session) {
	System.out.printf("Got connect: %s%n", session);
	this.session = session;
	try {
		Future<Void> fut;
		fut = session.getRemote().sendStringByFuture("Hello");
		fut.get(2, TimeUnit.SECONDS);
		fut = session.getRemote().sendStringByFuture("Thanks for the conversation.");
		fut.get(2, TimeUnit.SECONDS);
		session.close(StatusCode.NORMAL, "I'm done");
	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example 6
Source File: SimpleEchoSocket.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session session) {
  System.out.printf("Got connect: %s%n",session);
  try {
    Future<Void> fut = session.getRemote().sendStringByFuture("{\"field1\" : \"value\"}");
    fut.get(2, TimeUnit.SECONDS); // wait for send to complete.

    session.close(StatusCode.NORMAL,"I'm done");
  } catch (Throwable t) {
    t.printStackTrace();
  }
}
 
Example 7
Source File: WebSocketTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Batch batch) throws StageException {
  Session wsSession = null;
  try {
    WebSocketTargetSocket webSocketTargetSocket = new WebSocketTargetSocket(
        conf,
        generatorFactory,
        errorRecordHandler,
        batch
    );
    webSocketClient.start();
    URI webSocketUri = new URI(conf.resourceUrl);

    ClientUpgradeRequest request = new ClientUpgradeRequest();
    for (HeaderBean header : conf.headers) {
      request.setHeader(header.key, header.value.get());
    }

    Future<Session> connectFuture = webSocketClient.connect(webSocketTargetSocket, webSocketUri, request);
    wsSession = connectFuture.get();
    if (!webSocketTargetSocket.awaitClose(conf.maxRequestCompletionSecs, TimeUnit.SECONDS)) {
      throw new RuntimeException("Failed to send all records in maximum wait time.");
    }
  } catch (Exception ex) {
    LOG.error(Errors.HTTP_50.getMessage(), ex.toString(), ex);
    errorRecordHandler.onError(Lists.newArrayList(batch.getRecords()), throwStageException(ex));
  } finally {
    if (wsSession != null) {
      wsSession.close();
    }
    try {
      webSocketClient.stop();
    } catch (Exception e) {
      LOG.error(Errors.HTTP_50.getMessage(), e.toString(), e);
    }
  }
}
 
Example 8
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private void removeAllConnections() {
  if (watcherSession != null && watcherSession.isOpen()) {
    watcherSession.close();
  }

  Session noteSession = null;
  for (Map.Entry<String, Session> note: notesConnection.entrySet()) {
    noteSession = note.getValue();
    if (isSessionOpen(noteSession)) {
      noteSession.close();
    }
  }
  notesConnection.clear();
}
 
Example 9
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 10
Source File: WebSocketProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/** AMQP frames MUST be sent as binary data payloads of WebSocket messages.*/
@OnWebSocketMessage @SuppressWarnings("unused")
public void onWebSocketText(Session sess, String text)
{
    LOGGER.info("Unexpected websocket text message received, closing connection");
    sess.close();
}
 
Example 11
Source File: KlinesStreamTest.java    From java-binance-api with MIT License 5 votes vote down vote up
@Test
public void testKlinesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketKlines(symbol, BinanceInterval.ONE_MIN, new BinanceWebSocketAdapterKline() {
        @Override
        public void onMessage(BinanceEventKline message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
Example 12
Source File: AggTradesStreamTest.java    From java-binance-api with MIT License 5 votes vote down vote up
@Test
public void testTradesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketTrades(symbol, new BinanceWebSocketAdapterAggTrades() {
        @Override
        public void onMessage(BinanceEventAggTrade message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(5000);
    session.close();
}
 
Example 13
Source File: DepthStreamTest.java    From java-binance-api with MIT License 5 votes vote down vote up
@Test
public void testDepth5StreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketDepth5(symbol, new BinanceWebSocketAdapterDepthLevel() {
        @Override
        public void onMessage(BinanceEventDepthLevelUpdate message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
Example 14
Source File: DepthStreamTest.java    From java-binance-api with MIT License 5 votes vote down vote up
@Test
public void testDepthStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketDepth(symbol, new BinanceWebSocketAdapterDepth() {
        @Override
        public void onMessage(BinanceEventDepthUpdate message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
Example 15
Source File: SocketServer.java    From Much-Assembly-Required with GNU General Public License v3.0 4 votes vote down vote up
private void kickOnlineUser(Session session) {
    sendString(session, FORBIDDEN_MESSAGE);
    session.close();
}
 
Example 16
Source File: ObservableSocket.java    From jobson with Apache License 2.0 4 votes vote down vote up
@OnWebSocketClose
public void onWebSocketClose(Session session, int closeCode, String closeReason) {
    log.debug("Closing websocket");
    this.eventsSubscription.dispose();
    session.close(closeCode, closeReason);
}
 
Example 17
Source File: WebSocketClient.java    From icure-backend with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
{
	URI uri = URI.create("ws://127.0.0.1:16043/ws/be_kmehr/generateSumehr");

	org.eclipse.jetty.websocket.client.WebSocketClient client = new org.eclipse.jetty.websocket.client.WebSocketClient();
	try
	{
		try
		{
			client.start();
			// The socket that receives events
			WebSocketClient socket = new WebSocketClient();
			// Attempt Connect
			ClientUpgradeRequest request = new ClientUpgradeRequest();
			request.setSubProtocols("xsCrossfire");
			String basicAuthHeader = org.apache.commons.codec.binary.Base64.encodeBase64String("abaudoux:lambda".getBytes("UTF8"));
			request.setHeader("Authorization", "Basic " + basicAuthHeader);

			Future<Session> fut = client.connect(socket,uri,request);
			// Wait for Connect
			Session session = fut.get();
			// Send a message

			System.out.println(">>> Sending message: Hello");
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);

			Thread.sleep(10000);

			session.close();

		}
		finally
		{
			client.stop();
		}
	}
	catch (Throwable t)
	{
		t.printStackTrace(System.err);
	}
}
 
Example 18
Source File: GuacamoleWebSocketTunnelListener.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sends the given numeric Guacamole and WebSocket status
 * codes on the given WebSocket connection and closes the
 * connection.
 *
 * @param session
 *     The outbound WebSocket connection to close.
 *
 * @param guacamoleStatusCode
 *     The numeric Guacamole status code to send.
 *
 * @param webSocketCode
 *     The numeric WebSocket status code to send.
 */
private void closeConnection(Session session, int guacamoleStatusCode,
        int webSocketCode) {

    try {
        String message = Integer.toString(guacamoleStatusCode);
        session.close(new CloseStatus(webSocketCode, message));
    }
    catch (IOException e) {
        logger.debug("Unable to close WebSocket connection.", e);
    }

}
 
Example 19
Source File: GuacamoleWebSocketTunnelListener.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up
/**
 * Sends the given numeric Guacamole and WebSocket status
 * codes on the given WebSocket connection and closes the
 * connection.
 *
 * @param session
 *     The outbound WebSocket connection to close.
 *
 * @param guacamoleStatusCode
 *     The numeric Guacamole status code to send.
 *
 * @param webSocketCode
 *     The numeric WebSocket status code to send.
 */
private void closeConnection(Session session, int guacamoleStatusCode,
        int webSocketCode) {

    try {
        String message = Integer.toString(guacamoleStatusCode);
        session.close(new CloseStatus(webSocketCode, message));
    }
    catch (IOException e) {
        logger.debug("Unable to close WebSocket connection.", e);
    }

}