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

@Override
void close() throws IOException;

Source Link

Document

Close the connection to the remote end point using the code javax.websocket.CloseReason.CloseCodes#NORMAL_CLOSURE and an empty reason phrase.

Usage

From source file:com.websocket.WebSocketNewAnn.java

/**
 * WebSocket/*  w ww .  ja v  a 2  s  . c  om*/
 * 
 * @param session
 * @throws IOException
 */
@OnClose
public void OnClose(Session session) throws IOException {
    session.close();
}

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

@OnClose
public void onClose(Session session, @PathParam("gameId") long gameId) {
    Game game = TicTacToeServer.games.get(gameId);
    if (game == null)
        return;/* w w  w.ja v  a 2 s . c  o m*/
    boolean isPlayer1 = session == game.player1;
    if (game.ticTacToeGame == null)
        TicTacToeGame.removeQueuedGame(game.gameId);
    else if (!game.ticTacToeGame.isOver()) {
        game.ticTacToeGame.forfeit(isPlayer1 ? TicTacToeGame.Player.PLAYER1 : TicTacToeGame.Player.PLAYER2);
        Session opponent = (isPlayer1 ? game.player2 : game.player1);
        this.sendJsonMessage(opponent, game, new GameForfeitedMessage());
        try {
            opponent.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testWSClient() throws InterruptedException, DeploymentException, IOException {
    System.out.println("WS TEST: Testing WebSocket endpoint...");

    String endpoint = String.format("ws://%s:%d/gcs/ws", InetAddress.getLocalHost().getHostAddress(),
            config.getWSPort());//from   w  ww  .j  a v a 2 s.co m

    System.out.printf("WS TEST: Connecting to %s", endpoint);
    System.out.println();

    ClientManager client = ClientManager.createClient();

    Session session = client.connectToServer(WSClient.class, URI.create(endpoint));

    System.out.printf("WS TEST: Connected to %s", endpoint);
    System.out.println();

    MAVLinkPacket packet = getSamplePacket();
    session.getBasicRemote().sendBinary(ByteBuffer.wrap(packet.encodePacket()));

    Thread.sleep(10000);

    System.out.println("WS TEST: Complete.");

    session.close();
}

From source file:io.kodokojo.bdd.stage.AccessRestWhen.java

private void connectToWebSocket(UserInfo requesterUserInfo, boolean expectSuccess) {

    try {/*from  w ww  .  j  a  v a2s . com*/

        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

        ClientManager client = ClientManager.createClient();
        if (requesterUserInfo != null) {
            client.getProperties().put(ClientProperties.CREDENTIALS,
                    new Credentials(requesterUserInfo.getUsername(), requesterUserInfo.getPassword()));

        }

        String uriStr = "ws://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/event";
        CountDownLatch messageLatch = new CountDownLatch(1);
        Session session = client.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {

                session.addMessageHandler(new MessageHandler.Whole<String>() {
                    @Override
                    public void onMessage(String messsage) {
                        GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(WebSocketMessage.class, new WebSocketMessageGsonAdapter());
                        Gson gson = builder.create();
                        WebSocketMessage response = gson.fromJson(messsage, WebSocketMessage.class);
                        LOGGER.info("Receive WebSocket mesage : {}", response);
                        if ("user".equals(response.getEntity()) && "authentication".equals(response.getAction())
                                && response.getData().has("message") && ((JsonObject) response.getData())
                                        .getAsJsonPrimitive("message").getAsString().equals("success")) {
                            receiveWebSocketWelcome = true;
                            messageLatch.countDown();
                        } else {
                            receiveWebSocketWelcome = false;
                        }
                    }

                });
                if (requesterUserInfo != null) {
                    try {
                        String aggregateCredentials = String.format("%s:%s", requesterUserInfo.getUsername(),
                                requesterUserInfo.getPassword());
                        String encodedCredentials = Base64.getEncoder()
                                .encodeToString(aggregateCredentials.getBytes());
                        session.getBasicRemote()
                                .sendText("{\n" + "  \"entity\": \"user\",\n"
                                        + "  \"action\": \"authentication\",\n" + "  \"data\": {\n"
                                        + "    \"authorization\": \"Basic " + encodedCredentials + "\"\n"
                                        + "  }\n" + "}");
                    } catch (IOException e) {
                        fail(e.getMessage());
                    }
                }
            }

        }, cec, new URI(uriStr));
        messageLatch.await(10, TimeUnit.SECONDS);
        session.close();
    } catch (Exception e) {
        if (expectSuccess) {
            fail(e.getMessage());
        } else {
            receiveWebSocketWelcome = false;
        }
    }
}

From source file:org.axonframework.commandhandling.distributed.websockets.WebsocketCommandBusConnectorClient.java

public WebsocketCommandBusConnectorClient(ClientSessionFactory clientSessionFactory, int sessionCount) {
    //Create the pool. Server side connections are bound to the commands in process. Therefore scaling down the
    //amount of connections results in losing callbacks of pending commands. We will therefore never scale down or
    //invalidate connections.
    GenericObjectPool.Config config = new GenericObjectPool.Config();
    config.maxActive = sessionCount;//from   www . j  a  va  2  s .  c  om
    config.maxIdle = sessionCount;
    config.maxWait = -1;
    config.minEvictableIdleTimeMillis = -1;
    config.minIdle = 0;
    config.numTestsPerEvictionRun = 0;
    config.softMinEvictableIdleTimeMillis = -1;
    config.testOnBorrow = true;
    config.testOnReturn = false;
    config.testWhileIdle = false;
    config.timeBetweenEvictionRunsMillis = -1;
    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;

    sessions = new GenericObjectPoolFactory<>(new PoolableObjectFactory<Session>() {
        @Override
        public Session makeObject() throws Exception {
            return clientSessionFactory.createSession(WebsocketCommandBusConnectorClient.this);
        }

        @Override
        public void destroyObject(Session obj) throws Exception {
            if (obj.isOpen())
                obj.close();
        }

        @Override
        public boolean validateObject(Session obj) {
            return obj.isOpen();
        }

        @Override
        public void activateObject(Session obj) throws Exception {
            //
        }

        @Override
        public void passivateObject(Session obj) throws Exception {
            //
        }
    }, config).createPool();
}

From source file:org.kurento.test.services.KmsService.java

private void waitForKms() {
    long initTime = System.nanoTime();

    @ClientEndpoint//from   w w w  . ja  va2 s  .c  om
    class WebSocketClient extends Endpoint {

        @OnClose
        @Override
        public void onClose(Session session, CloseReason closeReason) {
        }

        @OnOpen
        @Override
        public void onOpen(Session session, EndpointConfig config) {
        }
    }

    if (wsUri != null) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();

        final int retries = 600;
        final int waitTime = 100;

        for (int i = 0; i < retries; i++) {
            try {
                log.debug("({}) Wait for KMS: {}. Container: {}", i, wsUri, container);
                Session wsSession = container.connectToServer(new WebSocketClient(),
                        ClientEndpointConfig.Builder.create().build(), new URI(wsUri));
                wsSession.close();

                double time = (System.nanoTime() - initTime) / (double) 1000000;

                log.debug("Connected to KMS in " + String.format("%3.2f", time) + " milliseconds");
                return;
            } catch (DeploymentException | IOException | URISyntaxException e) {
                try {
                    log.warn("Exception while waiting for KMS: {}. {}", wsUri, e.getMessage());
                    Thread.sleep(waitTime);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

        throw new KurentoException("Timeout of " + retries * waitTime + " millis waiting for KMS " + wsUri);

    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("InterruptedException {}", e.getMessage());
        }
    }
}

From source file:org.springframework.samples.websocket.client.SimpleClientEndpoint.java

@Override
public void onOpen(final Session session, EndpointConfig config) {
    try {//from   w  w  w.ja v a 2s  .c  o  m
        String message = this.greetingService.getGreeting();
        session.getBasicRemote().sendText(message);
    } catch (IOException e) {
        e.printStackTrace();
    }
    session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
            logger.debug("Received message: " + message);
            try {
                session.close();
                logger.debug("Closed session");
            } catch (IOException e) {
                logger.error("Failed to close", e);
            }
        }
    });
}

From source file:org.wso2.carbon.event.input.adapter.websocket.internal.WebsocketClient.java

@Override
public void onClose(Session session, javax.websocket.CloseReason closeReason) {
    if (log.isDebugEnabled()) {
        log.debug("Input ws-adaptor: WebsocketClient Endpoint closed: " + closeReason.toString()
                + "for request URI - " + session.getRequestURI());
    }//from  www . j  a va2  s  .  c o  m
    try {
        session.close();
    } catch (IOException e) {
        log.error("Error occurred during closing session. Session ID:" + session.getId()
                + ", for request URI - " + session.getRequestURI() + ", Reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.event.input.adapter.websocket.internal.WebsocketClient.java

@Override
public void onError(Session session, Throwable thr) {
    log.error("Error occurred during session ID:" + session.getId() + ", for request URI - "
            + session.getRequestURI() + ", Reason: " + thr, thr);
    try {/*from   w w  w  .  ja v  a2  s  . co  m*/
        session.close();
    } catch (IOException e) {
        log.error("Error occurred during closing session. Session ID:" + session.getId()
                + ", for request URI - " + session.getRequestURI() + ", Reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.event.output.adaptor.websocket.WebsocketEventAdaptor.java

@Override
protected void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {
    String topic = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
            .get(WebsocketEventAdaptorConstants.ADAPTER_TOPIC);
    String socketServerUrl = outputEventAdaptorConfiguration.getOutputProperties()
            .get(WebsocketEventAdaptorConstants.ADAPTER_SERVER_URL);
    if (!socketServerUrl.startsWith("ws://")) {
        throw new OutputEventAdaptorEventProcessingException(
                "Provided websocket URL - " + socketServerUrl + " is invalid.");
    }/*  w w w . j  a v  a  2 s .  c o  m*/
    if (topic != null) {
        socketServerUrl = socketServerUrl + "/" + topic;
    }
    ConcurrentHashMap<String, Session> urlSessionMap = outputEventAdaptorSessionMap.get(tenantId);
    if (urlSessionMap == null) {
        urlSessionMap = new ConcurrentHashMap<String, Session>();
        if (null != outputEventAdaptorSessionMap.putIfAbsent(tenantId, urlSessionMap)) {
            urlSessionMap = outputEventAdaptorSessionMap.get(tenantId);
        }
    }
    Session session = urlSessionMap.get(socketServerUrl);
    if (session == null) { //TODO: Handle reconnecting, in case server disconnects. Suggestion: Create a scheduler.
        ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
        ClientManager client = ClientManager.createClient();
        try {
            session = client.connectToServer(new WebsocketClient(), cec, new URI(socketServerUrl));
            if (null != urlSessionMap.putIfAbsent(socketServerUrl, session)) {
                session.close();
                session = urlSessionMap.get(socketServerUrl);
            }
        } catch (DeploymentException e) {
            throw new OutputEventAdaptorEventProcessingException(e);
        } catch (IOException e) {
            throw new OutputEventAdaptorEventProcessingException(e);
        } catch (URISyntaxException e) {
            throw new OutputEventAdaptorEventProcessingException(e);
        }
    }
    session.getAsyncRemote().sendText(message.toString());
}