Example usage for javax.websocket CloseReason CloseReason

List of usage examples for javax.websocket CloseReason CloseReason

Introduction

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

Prototype

public CloseReason(CloseReason.CloseCode closeCode, String reasonPhrase) 

Source Link

Usage

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 . c o 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:org.brutusin.rpc.websocket.WebsocketEndpoint.java

/**
 *
 * @param session/*  w w  w  .j  av a 2s .  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:Logica.SesionWeb.java

@Override
public void notificarError(TipoMensaje tipoMensaje, String mensaje) {
    try {/*from  w w  w . ja va  2s  .co m*/
        JSONObject o = new JSONObject();
        o.append("tipo", "" + tipoMensaje);
        o.append("mensaje", mensaje);
        sesion.getBasicRemote().sendText(o.toString());
        sesion.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,
                "Algo salio muy mal... o no tan mal(como login mal viste..)"));
    } catch (IOException ex) {
        Logger.getLogger(ChatEndpoint.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.josue.ws.web.server.MessageDispatcher.java

private void proccessConnectionMessage(MessageRequestWrapper wrapper) throws IOException {
    NetworkConnection connection = wrapper.getResource();

    if (connection.getState() != null) {
        switch (connection.getState()) {
        case AFK:
            break;
        case CONNECTED_PLAYER:
            store.put(wrapper.getMap(), wrapper.getSession(), connection.getPlayer());
            sendAllExceptSender(wrapper);
            sendConnectedUsers(wrapper);
            break;
        case DISCONNECTED:
            wrapper.getSession().close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,
                    "Player " + wrapper.getSession().getId() + " disconnected"));
            sendAllExceptSender(wrapper);
            break;
        default:/*from   w  w  w  . jav a  2s  . c  o  m*/
            logger.log(Level.WARNING, "Invalid connection status: {0}", connection.getState());
            break;
        }
    }

}

From source file:cito.server.AbstractEndpoint.java

@OnError
@Override/*from   w w  w.  ja v a  2s.  com*/
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:hr.ws4is.websocket.WebSocketEndpoint.java

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

    try {/*from  ww w  .j av  a2  s.  c  o m*/
        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:furkan.app.tictactoewebsocket.TicTacToeServer.java

private void handleException(Throwable t, Game game) {
    t.printStackTrace();// ww  w .  j  ava  2  s  .c o  m
    String message = t.toString();
    try {
        game.player1.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, message));
    } catch (IOException ignore) {
    }
    try {
        game.player2.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, message));
    } catch (IOException ignore) {
    }
}

From source file:com.smartling.cms.gateway.client.CmsGatewayClientTest.java

@Test
public void callsCommandHandlerOnDisconnectWhenTransportClosedNormally() throws Exception {
    CloseReason reason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, null);

    getCommandChannelTransportEndpoint().onClose(null, reason);

    verify(handler, only()).onDisconnect();
}

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);/* w ww  .j  ava 2s.  c  om*/
    assertEquals(Bar.DESTROYED.size(), 1);
}

From source file:com.smartling.cms.gateway.client.CmsGatewayClientTest.java

@Test
public void autoReconnectsCommandChannelWhenTransportClosedAbnormally() throws Exception {
    CloseReason reason = new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, null);

    getCommandChannelTransportEndpoint().onClose(null, reason);

    verify(commandChannelTransport, times(2)).connectToServer(anyObject(), eq(STUB_COMMAND_CHANNEL_URI));
    verifyZeroInteractions(handler);//from  ww w  .  j ava2 s .c o  m
}