Example usage for javax.websocket Session close

List of usage examples for javax.websocket Session close

Introduction

In this page you can find the example usage for javax.websocket Session close.

Prototype

void close(CloseReason closeReason) throws IOException;

Source Link

Document

Close the connection to the remote end point using the specified code and reason phrase.

Usage

From source file:org.brutusin.rpc.websocket.WebsocketEndpoint.java

/**
 *
 * @param session/*from   w  ww.  j a  v a 2  s  . co m*/
 * @param config
 */
@Override
public void onOpen(Session session, EndpointConfig config) {
    final WebsocketContext websocketContext = contextMap
            .get(session.getRequestParameterMap().get("requestId").get(0));
    if (!allowAccess(session, websocketContext)) {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Authentication required"));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return;
    }
    final SessionImpl sessionImpl = new SessionImpl(session, websocketContext);
    sessionImpl.init();
    wrapperMap.put(session.getId(), sessionImpl);

    session.addMessageHandler(new MessageHandler.Whole<String>() {
        public void onMessage(String message) {
            WebsocketActionSupportImpl.setInstance(new WebsocketActionSupportImpl(sessionImpl));
            try {
                String response = process(message, sessionImpl);
                if (response != null) {
                    sessionImpl.sendToPeerRaw(response);
                }
            } finally {
                WebsocketActionSupportImpl.clear();
            }
        }
    });
}

From source file:io.undertow.js.test.cdi.CDIInjectionProviderDependentTestCase.java

@Test
public void testWebsocketInjection() throws Exception {
    Session session = ContainerProvider.getWebSocketContainer().connectToServer(ClientEndpointImpl.class,
            new URI("ws://" + DefaultServer.getHostAddress("default") + ":"
                    + DefaultServer.getHostPort("default") + "/cdi/websocket"));
    Assert.assertEquals("Barpong", messages.poll(5, TimeUnit.SECONDS));

    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "foo"));
    Thread.sleep(1000);//from   www .j a v  a  2  s .c o m
    assertEquals(Bar.DESTROYED.size(), 1);
}

From source file:furkan.app.tictactoewebsocket.TicTacToeServer.java

@OnOpen
public void onOpen(Session session, @PathParam("gameId") long gameId, @PathParam("username") String username) {
    System.out.println("Inside onOpen");
    try {//from  w  ww . j  av  a  2 s  .  co m
        TicTacToeGame ticTacToeGame = TicTacToeGame.getActiveGame(gameId);
        if (ticTacToeGame != null) {
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION,
                    "This game has already started!"));
        }

        List<String> actions = session.getRequestParameterMap().get("action");
        if (actions != null && actions.size() == 1) {
            String action = actions.get(0);
            if (action.equalsIgnoreCase("start")) {
                Game game = new Game();
                game.gameId = gameId;
                game.player1 = session;
                TicTacToeServer.games.put(gameId, game);
            } else if (action.equalsIgnoreCase("join")) {
                Game game = TicTacToeServer.games.get(gameId);
                game.player2 = session;
                game.ticTacToeGame = TicTacToeGame.startGame(gameId, username);
                this.sendJsonMessage(game.player1, game, new GameStartedMessage(game.ticTacToeGame));
                this.sendJsonMessage(game.player2, game, new GameStartedMessage(game.ticTacToeGame));
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, ioe.toString()));
        } catch (IOException ignore) {
        }
    }
}

From source file:hydrograph.ui.graph.execution.tracking.utils.TrackingDisplayUtils.java

/**
 * /*from   w ww  .jav a 2s.c o m*/
 * Close websocket client connection.
 * @param session
 */
public void closeWebSocketConnection(Session session) {
    try {
        Thread.sleep(DELAY);
    } catch (InterruptedException e1) {
    }
    if (session != null && session.isOpen()) {
        try {
            CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE, "Closed");
            session.close(closeReason);
            logger.info("Session closed");
        } catch (IOException e) {
            logger.error("Fail to close connection ", e);
        }

    }

}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServer.java

private void authenticateUser(Session session, Project project, String user) {
    //returns the user role in project. Null if the user has no role in project
    this.userRole = projectTeamBean.findCurrentRole(project, user);
    LOG.log(Level.FINEST, "User role in this project {0}", this.userRole);
    Users users = userBean.findByEmail(user);
    if (users == null || this.userRole == null) {
        try {//from ww  w. ja v  a2s  . c  o  m
            session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,
                    "You do not have a role in this project."));
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
    this.hdfsUsername = hdfsUsersController.getHdfsUserName(project, users);
}

From source file:cito.server.AbstractEndpoint.java

@OnError
@Override/*w  w w .j  a va2  s.c  o  m*/
public void onError(Session session, Throwable cause) {
    final String errorId = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
    this.log.warn("WebSocket error. [id={},principle={},errorId={}]", session.getId(),
            session.getUserPrincipal(), errorId, cause);
    try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
        this.errorEvent.select(cito.annotation.OnError.Literal.onError()).fire(cause);
        final Frame errorFrame = Frame.error()
                .body(MediaType.TEXT_PLAIN_TYPE, format("%s [errorId=%s]", cause.getMessage(), errorId))
                .build();
        session.getBasicRemote().sendObject(errorFrame);
        session.close(
                new CloseReason(CloseCodes.PROTOCOL_ERROR, format("See server log. [errorId=%s]", errorId)));
    } catch (IOException | EncodeException e) {
        this.log.error("Unable to send error frame! [id={},principle={}]", session.getId(),
                session.getUserPrincipal(), e);
    }
}

From source file:hydrograph.ui.graph.utility.JobScpAndProcessUtility.java

/**
 * Close Websocket connection Connection
 * @param session/*from  ww w  .  jav a 2  s .  co  m*/
 */
private void closeWebSocketConnection(final Session session) {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
    }

    if (session != null && session.isOpen()) {
        try {
            CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE, "Session Closed");
            session.close(closeReason);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:hr.ws4is.websocket.WebSocketEndpoint.java

public final void onOpen(final Session session, final EndpointConfig config) {

    try {/*from w w  w  .ja va  2  s .  c  om*/
        final HttpSession httpSession = (HttpSession) config.getUserProperties()
                .get(HttpSession.class.getName());
        final WebSocketSession wsession = new WebSocketSession(session, httpSession);

        session.getUserProperties().put(WS4ISConstants.WEBSOCKET_PATH,
                config.getUserProperties().get(WS4ISConstants.WEBSOCKET_PATH));

        websocketContextThreadLocal.set(wsession);
        webSocketEvent.fire(new WebsocketEvent(wsession, WebSocketEventStatus.START));

        if (!wsession.isValidHttpSession()) {
            LOGGER.error(WS4ISConstants.HTTP_SEESION_REQUIRED);
            final IllegalStateException ise = new IllegalStateException(WS4ISConstants.HTTP_SEESION_REQUIRED);
            final WebSocketResponse wsResponse = getErrorResponse(ise);
            final String responseString = JsonDecoder.getJSONEngine().writeValueAsString(wsResponse);
            session.close(new CloseReason(CloseCodes.VIOLATED_POLICY, responseString));
        }

    } catch (IOException exception) {
        LOGGER.error(exception.getMessage(), exception);
    } finally {
        websocketContextThreadLocal.remove();
    }

}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

public void closeConnection(Session session, String hdfsUsername,
        NotebookServerImplFactory notebookServerImplFactory) {
    try {/*from  w  w w.j a v  a 2  s . com*/
        if (session.isOpen()) {
            session.getBasicRemote().sendText("Restarting zeppelin.");
            session.close(new CloseReason(CloseReason.CloseCodes.SERVICE_RESTART, "Restarting zeppelin."));
        }
        removeConnectionFromAllNote(session);
        removeConnectedSockets(session, notebookServerImplFactory);
        removeUserConnection(hdfsUsername, session);
        removeUserConnection(project.getProjectGenericUser(), session);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java

/**
 * Called when a web socket connection is made.  The format for the web socket URL endpoint is:
 * //from  ww w.  j  a  v  a  2s  . com
 *   /designs/{designId}?uuid={uuid}&user={user}&secret={secret}
 *   
 * The uuid, user, and secret query parameters must be present for a connection to be 
 * successfully made.
 * 
 * @param session
 */
@OnOpen
public void onOpenSession(Session session) {
    String designId = session.getPathParameters().get("designId");
    logger.debug("WebSocket opened: {}", session.getId());
    logger.debug("\tdesignId: {}", designId);

    String queryString = session.getQueryString();
    Map<String, String> queryParams = parseQueryString(queryString);
    String uuid = queryParams.get("uuid");
    String userId = queryParams.get("user");
    String secret = queryParams.get("secret");

    this.metrics.socketConnected(designId, userId);

    logger.debug("\tuuid: {}", uuid);
    logger.debug("\tuser: {}", userId);

    ApiDesignEditingSession editingSession = null;

    try {
        long contentVersion = editingSessionManager.validateSessionUuid(uuid, designId, userId, secret);

        // Join the editing session (or create a new one) for the API Design
        editingSession = this.editingSessionManager.getOrCreateEditingSession(designId);
        Set<Session> otherSessions = editingSession.getSessions();
        if (editingSession.isEmpty()) {
            this.metrics.editingSessionCreated(designId);
        }
        editingSession.join(session, userId);

        // Send "join" messages for each user already in the session
        for (Session otherSession : otherSessions) {
            String otherUser = editingSession.getUser(otherSession);
            editingSession.sendJoinTo(session, otherUser, otherSession.getId());
        }

        // Send any commands that have been created since the user asked to join the editing session.
        List<ApiDesignCommand> commands = this.storage.listContentCommands(userId, designId, contentVersion);
        for (ApiDesignCommand command : commands) {
            String cmdData = command.getCommand();

            StringBuilder builder = new StringBuilder();
            builder.append("{");
            builder.append("\"contentVersion\": ");
            builder.append(command.getContentVersion());
            builder.append(", ");
            builder.append("\"type\": \"command\", ");
            builder.append("\"command\": ");
            builder.append(cmdData);
            builder.append("}");

            logger.debug("Sending command to client (onOpenSession): {}", builder.toString());

            session.getBasicRemote().sendText(builder.toString());
        }

        editingSession.sendJoinToOthers(session, userId);
    } catch (ServerError | StorageException | IOException e) {
        if (editingSession != null) {
            editingSession.leave(session);
        }
        logger.error("Error validating editing session UUID for API Design ID: " + designId, e);
        try {
            session.close(new CloseReason(CloseCodes.CANNOT_ACCEPT,
                    "Error opening editing session: " + e.getMessage()));
        } catch (IOException e1) {
            logger.error(
                    "Error closing web socket session (attempted to close due to error validating editing session UUID).",
                    e1);
        }
    }
}