javax.websocket.CloseReason Java Examples
The following examples show how to use
javax.websocket.CloseReason.
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: Client.java From aesh-readline with Apache License 2.0 | 6 votes |
public static Client initializeDefault() { Client client = new Client(); Consumer<Session> onOpen = (session) -> { LOGGER.info("Client connection opened."); }; Consumer<CloseReason> onClose = (closeReason) -> { LOGGER.info("Client connection closed. " + closeReason); }; client.onOpen(onOpen); client.onClose(onClose); return client; }
Example #2
Source File: WsWebSocketContainer.java From tomcatsrc with Apache License 2.0 | 6 votes |
/** * Cleans up the resources still in use by WebSocket sessions created from * this container. This includes closing sessions and cancelling * {@link Future}s associated with blocking read/writes. */ public void destroy() { CloseReason cr = new CloseReason( CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown")); for (WsSession session : sessions.keySet()) { try { session.close(cr); } catch (IOException ioe) { log.debug(sm.getString( "wsWebSocketContainer.sessionCloseFail", session.getId()), ioe); } } // Only unregister with AsyncChannelGroupUtil if this instance // registered with it if (asynchronousChannelGroup != null) { synchronized (asynchronousChannelGroupLock) { if (asynchronousChannelGroup != null) { AsyncChannelGroupUtil.unregister(); asynchronousChannelGroup = null; } } } }
Example #3
Source File: ChatAppEndpoint.java From msf4j with Apache License 2.0 | 6 votes |
@OnClose public void onClose(@PathParam("name") String name, CloseReason closeReason, WebSocketConnection webSocketConnection) { LOGGER.info("Connection is closed with status code : " + closeReason.getCloseCode().getCode() + " On reason " + closeReason.getReasonPhrase()); webSocketConnections.remove(webSocketConnection); String msg = name + " left the chat"; sendMessageToAll(msg); }
Example #4
Source File: PojoEndpointBase.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public final void onClose(Session session, CloseReason closeReason) { if (methodMapping.getOnClose() != null) { try { methodMapping.getOnClose().invoke(pojo, methodMapping.getOnCloseArgs(pathParameters, session, closeReason)); } catch (Throwable t) { log.error(sm.getString("pojoEndpointBase.onCloseFail", pojo.getClass().getName()), t); handleOnOpenOrCloseError(session, t); } } // Trigger the destroy method for any associated decoders Set<MessageHandler> messageHandlers = session.getMessageHandlers(); for (MessageHandler messageHandler : messageHandlers) { if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) { ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose(); } } }
Example #5
Source File: ChattersTest.java From triplea with GNU General Public License v3.0 | 6 votes |
@Test @DisplayName("Players can have multiple sessions, verify they are all closed") void allSameNamePlayersAreDisconnected() throws Exception { when(session.getId()).thenReturn("1"); when(session2.getId()).thenReturn("2"); chatters.connectPlayer(buildChatterSession(session)); chatters.connectPlayer(buildChatterSession(session2)); final boolean result = chatters.disconnectPlayerByName(CHAT_PARTICIPANT.getUserName(), "disconnect message"); assertThat(result, is(true)); verify(session).close(any(CloseReason.class)); verify(session2).close(any(CloseReason.class)); }
Example #6
Source File: AnnotatedEndpointTest.java From quarkus-http with Apache License 2.0 | 6 votes |
@Test public void testCloseReason() throws Exception { AnnotatedClientEndpoint.reset(); MessageEndpoint.reset(); Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/chat/Bob")); Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message()); session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Foo!")); Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message()); CloseReason cr = MessageEndpoint.getReason(); Assert.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY.getCode(), cr.getCloseCode().getCode()); Assert.assertEquals("Foo!", cr.getReasonPhrase()); }
Example #7
Source File: JsrWebSocketFilter.java From quarkus-http with Apache License 2.0 | 6 votes |
@Override public void sessionDestroyed(HttpSessionEvent se) { HttpSessionImpl session = (HttpSessionImpl) se.getSession(); final Session underlying; if (System.getSecurityManager() == null) { underlying = session.getSession(); } else { underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session)); } List<UndertowSession> connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE); if (connections != null) { synchronized (underlying) { for (UndertowSession c : connections) { try { c.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "")); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); } } } } }
Example #8
Source File: WsWebSocketContainer.java From Tomcat8-Source-Read with MIT License | 6 votes |
/** * Cleans up the resources still in use by WebSocket sessions created from * this container. This includes closing sessions and cancelling * {@link Future}s associated with blocking read/writes. */ public void destroy() { CloseReason cr = new CloseReason( CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown")); for (WsSession session : sessions.keySet()) { try { session.close(cr); } catch (IOException ioe) { log.debug(sm.getString( "wsWebSocketContainer.sessionCloseFail", session.getId()), ioe); } } // Only unregister with AsyncChannelGroupUtil if this instance // registered with it if (asynchronousChannelGroup != null) { synchronized (asynchronousChannelGroupLock) { if (asynchronousChannelGroup != null) { AsyncChannelGroupUtil.unregister(); asynchronousChannelGroup = null; } } } }
Example #9
Source File: Client.java From termd with Apache License 2.0 | 6 votes |
public static Client initializeDefault() { Client client = new Client(); Consumer<Session> onOpen = (session) -> { log.info("Client connection opened."); }; Consumer<CloseReason> onClose = (closeReason) -> { log.info("Client connection closed. " + closeReason); }; client.onOpen(onOpen); client.onClose(onClose); return client; }
Example #10
Source File: WsSession.java From tomcatsrc with Apache License 2.0 | 6 votes |
/** * Called when a close message is received. Should only ever happen once. * Also called after a protocol error when the ProtocolHandler needs to * force the closing of the connection. */ public void onClose(CloseReason closeReason) { synchronized (stateLock) { if (state != State.CLOSED) { try { wsRemoteEndpoint.setBatchingAllowed(false); } catch (IOException e) { log.warn(sm.getString("wsSession.flushFailOnClose"), e); fireEndpointOnError(e); } if (state == State.OPEN) { state = State.OUTPUT_CLOSED; sendCloseMessage(closeReason); fireEndpointOnClose(closeReason); } state = State.CLOSED; // Close the socket wsRemoteEndpoint.close(); } } }
Example #11
Source File: WebsocketClientEndpoint.java From ZStreamingQuote with MIT License | 6 votes |
/** * Callback hook for Connection close events. * * @param userSession * the userSession which is getting closed. * @param reason * the reason for connection close */ @OnClose public void onClose(Session userSession, CloseReason reason) { System.out.println( "WebsocketClientEndpoint.onClose(): Closing Websocket.... Reason[" + reason.getReasonPhrase() + "]"); try { this.userSession.close(); } catch (IOException e) { System.out.println("WebsocketClientEndpoint.onClose(): ERROR: IOException on userSession close!!!"); e.printStackTrace(); } this.userSession = null; // stop timer if running if (hbTimer != null) { hbTimer.cancel(); hbTimer = null; } // Notify session closed sessionNotifier.notifyWsSessionClosed(terminate); }
Example #12
Source File: DrawboardEndpoint.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public void onClose(Session session, CloseReason closeReason) { Room room = getRoom(false); if (room != null) { room.invokeAndWait(new Runnable() { @Override public void run() { try { // Player can be null if it couldn't enter the room if (player != null) { // Remove this player from the room. player.removeFromRoom(); // Set player to null to prevent NPEs when onMessage events // are processed (from other threads) after onClose has been // called from different thread which closed the Websocket session. player = null; } } catch (RuntimeException ex) { log.error("Unexpected exception: " + ex.toString(), ex); } } }); } }
Example #13
Source File: KumaliveWebsocketServer.java From lams with GNU General Public License v2.0 | 6 votes |
@OnClose public void unregisterUser(Session websocket, CloseReason reason) throws IOException { String login = websocket.getUserPrincipal().getName(); if (login == null) { return; } Integer organisationId = Integer .valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0)); KumaliveDTO kumalive = kumalives.get(organisationId); if (kumalive == null) { return; } KumaliveWebsocketServer.unregisterUser(kumalive, login); KumaliveWebsocketServer.sendRefresh(kumalive); }
Example #14
Source File: RoomEndpoint.java From sample-room-java with Apache License 2.0 | 6 votes |
/** * Try sending the {@link Message} using * {@link Session#getBasicRemote()}, {@link Basic#sendObject(Object)}. * * @param session Session to send the message on * @param message Message to send * @return true if send was successful, or false if it failed */ private boolean sendMessageToSession(Session session, Message message) { if (session.isOpen()) { try { session.getBasicRemote().sendObject(message); return true; } catch (EncodeException e) { // Something was wrong encoding this message, but the connection // is likely just fine. Log.log(Level.FINE, this, "Unexpected condition writing message", e); } catch (IOException ioe) { // An IOException, on the other hand, suggests the connection is // in a bad state. Log.log(Level.FINE, this, "Unexpected condition writing message", ioe); tryToClose(session, new CloseReason(CloseCodes.UNEXPECTED_CONDITION, trimReason(ioe.toString()))); } } return false; }
Example #15
Source File: ChatAppEndpoint.java From msf4j with Apache License 2.0 | 6 votes |
@OnClose public void onClose(@PathParam("name") String name, CloseReason closeReason, WebSocketConnection webSocketConnection) { LOGGER.info("Connection is closed with status code : " + closeReason.getCloseCode().getCode() + " On reason " + closeReason.getReasonPhrase()); webSocketConnections.remove(webSocketConnection); String msg = name + " left the chat"; sendMessageToAll(msg); }
Example #16
Source File: WSQueryEndpoint.java From ksql-fork-with-deep-learning-function with Apache License 2.0 | 5 votes |
@OnClose public void onClose(Session session, CloseReason closeReason) { log.debug( "Closing websocket session {} ({}): {}", session.getId(), closeReason.getCloseCode(), closeReason.getReasonPhrase() ); if (future != null) { future.cancel(true); } }
Example #17
Source File: Utility.java From mercury with Apache License 2.0 | 5 votes |
public void closeConnection(String txPath, CloseReason.CloseCodes status, String message) throws IOException { if (txPath != null && status != null && message != null) { EventEnvelope error = new EventEnvelope(); error.setTo(txPath); error.setHeader(WsTransmitter.STATUS, String.valueOf(status.getCode())); error.setHeader(WsTransmitter.MESSAGE, message); error.setHeader(WsEnvelope.TYPE, WsEnvelope.CLOSE); PostOffice.getInstance().send(error); } }
Example #18
Source File: TestEndpointWithOnCloseError.java From msf4j with Apache License 2.0 | 5 votes |
@OnClose public void onClose(@PathParam("name") String name, CloseReason closeReason, WebSocketConnection webSocketConnection, String errorValue) { webSocketConnections.remove(webSocketConnection); String msg = name + errorValue; sendMessageToAll(msg); }
Example #19
Source File: FHIRNotificationServiceEndpoint.java From FHIR with Apache License 2.0 | 5 votes |
/** * process message which is trying to disconnect * * @param session * @param closeReason */ public void onClose(Session session, CloseReason closeReason) { log.entering(this.getClass().getName(), "onClose"); try { FHIRNotificationSubscriber subscriber = subscribers.remove(session); if (subscriber != null) { notificationService.unsubscribe(subscriber); } log.info(String.format("Notification client [sessionId=%s] has disconnected, reason: %s", session.getId(), closeReason)); cleanup(); } finally { log.exiting(this.getClass().getName(), "onClose"); } }
Example #20
Source File: MonitorService.java From mercury with Apache License 2.0 | 5 votes |
public static void closeAllConnections() { Utility util = Utility.getInstance(); Set<String> connections = token2txPath.keySet(); if (!connections.isEmpty()) { for (String token : connections) { String txPath = token2txPath.get(token); try { util.closeConnection(txPath, CloseReason.CloseCodes.TRY_AGAIN_LATER, "Starting up"); } catch (IOException e) { log.warn("Unable to close connection {}", txPath); } } } }
Example #21
Source File: WebSocketServiceImpl.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
private void onClose(Session session, CloseReason closeReason) { LOGGER.info( "Web socket connection closed {}, {}", closeReason.getCloseCode(), closeReason.getReasonPhrase()); if (isTyrusBufferOverflowCloseReason(closeReason)) { LOGGER.error( "Web socket connection closed due to BufferOverflow raised by Tyrus client. This indicates the message " + "about to be received is larger than the incoming buffer in Tyrus client. " + "See DefaultWebSocketContainerFactory class source on how to increase the incoming buffer size in Tyrus or visit https://github.com/kklisura/chrome-devtools-java-client/blob/master/cdt-examples/src/main/java/com/github/kklisura/cdt/examples/IncreasedIncomingBufferInTyrusExample.java"); } }
Example #22
Source File: WebsocketTtyTestBase.java From termd with Apache License 2.0 | 5 votes |
@Override protected void assertConnect(String term) throws Exception { if (endpoint != null) { throw failure("Already a session"); } final CountDownLatch latch = new CountDownLatch(1); final PipedWriter out = new PipedWriter(); in = new PipedReader(out); endpoint = new Endpoint() { @Override public void onOpen(Session session, EndpointConfig endpointConfig) { session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { try { out.write(message); } catch (IOException e) { e.printStackTrace(); } } }); latch.countDown(); } @Override public void onClose(Session sess, CloseReason closeReason) { session = null; endpoint = null; in = null; } @Override public void onError(Session session, Throwable thr) { } }; ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); session = webSocketContainer.connectToServer(endpoint, clientEndpointConfig, new URI("http://localhost:8080/ws")); latch.await(); }
Example #23
Source File: ChattersTest.java From triplea with GNU General Public License v3.0 | 5 votes |
@Test void singleSessionDisconnected() throws Exception { when(session.getId()).thenReturn("100"); chatters.connectPlayer(buildChatterSession(session)); final boolean result = chatters.disconnectPlayerByName(CHAT_PARTICIPANT.getUserName(), "disconnect message"); assertThat(result, is(true)); verify(session).close(any(CloseReason.class)); }
Example #24
Source File: ServerWebSocketContainer.java From quarkus-http with Apache License 2.0 | 5 votes |
private void doClose() { closed = true; for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) { for (Session session : endpoint.getOpenSessions()) { try { session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "")); } catch (Exception e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotCloseOnUndeploy(e); } } } }
Example #25
Source File: WsGateway.java From mercury with Apache License 2.0 | 5 votes |
private void handleMessage(Map<String, String> headers, Object body) throws IOException { Utility util = Utility.getInstance(); if (!forwardEvent(headers, body)) { WsInfo service = route2WsInfo.get(headers.get(ROUTE)); if (service != null) { util.closeConnection(headers.get(TX_PATH), CloseReason.CloseCodes.GOING_AWAY, service.userService+" offline"); } } }
Example #26
Source File: PersistentWsClient.java From mercury with Apache License 2.0 | 5 votes |
@Override public void run() { Runtime.getRuntime().addShutdownHook(new Thread(this::close)); log.info("Started"); long idleSeconds = WsConfigurator.getInstance().getIdleTimeout() - IDLE_THRESHOLD; long idleTimeout = (idleSeconds < IDLE_THRESHOLD? IDLE_THRESHOLD : idleSeconds) * 1000; /* * Immediate connect when running for the first time. * Thereafter, wait for 5 seconds and try again until it is connected. */ log.info("Connection list {}", urls); while (normal) { try { manageConnection(idleTimeout / 2); } catch (Exception e) { log.error("Unexpected connectivity issue - {}", e.getMessage()); // guaranteed persistent connection if (client != null && client.isConnected()) { try { client.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, e.getMessage())); } catch (IOException ex) { // ok to ignore } } client = null; } try { Thread.sleep(1000); } catch (InterruptedException e1) { // ok to ignore } } log.info("Stopped"); }
Example #27
Source File: StandardWebSocketSession.java From spring-analysis-note with MIT License | 5 votes |
@Override public Mono<Void> close(CloseStatus status) { try { CloseReason.CloseCode code = CloseCodes.getCloseCode(status.getCode()); getDelegate().close(new CloseReason(code, status.getReason())); } catch (IOException ex) { return Mono.error(ex); } return Mono.empty(); }
Example #28
Source File: WsHttpUpgradeHandler.java From tomcatsrc with Apache License 2.0 | 5 votes |
private void close(CloseReason cr) { /* * Any call to this method is a result of a problem reading from the * client. At this point that state of the connection is unknown. * Attempt to send a close frame to the client and then close the socket * immediately. There is no point in waiting for a close frame from the * client because there is no guarantee that we can recover from * whatever messed up state the client put the connection into. */ wsSession.onClose(cr); }
Example #29
Source File: WsHttpUpgradeHandler.java From tomcatsrc with Apache License 2.0 | 5 votes |
private void onError(Throwable throwable) { wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, throwable.getMessage()), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, throwable.getMessage())); // Need to call onError using the web application's class loader Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); t.setContextClassLoader(applicationClassLoader); try { ep.onError(wsSession, throwable); } finally { t.setContextClassLoader(cl); } }
Example #30
Source File: NodeCommunication.java From TMChat with MIT License | 5 votes |
@Override public void wasClosed(CloseReason cr) { if (!"Manual Close".equals(cr.getReasonPhrase())) { System.out.println("Websocket closed... reconnecting"); reconnectWS(); } }