Example usage for javax.websocket Endpoint Endpoint

List of usage examples for javax.websocket Endpoint Endpoint

Introduction

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

Prototype

Endpoint

Source Link

Usage

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

private void connectToWebSocket(UserInfo requesterUserInfo, boolean expectSuccess) {

    try {/*ww  w.  ja v a2  s. c  o m*/

        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:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

private static Endpoint sendAndGetTextEndPoint(final String sendText, final SettableFuture<String> res) {
    return new Endpoint() {
        @Override/*from   ww  w . java 2s.co  m*/
        public void onOpen(final Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String text) {
                    res.set(text);
                }
            });
            try {
                session.getBasicRemote().sendText(sendText);
            } catch (IOException ignored) {
            }
        }
    };
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Create session/*from   w w w.  j a v  a  2 s . c o  m*/
 *
 * @param jsessionid
 * @param userpwd
 * @return
 */
protected Session createAndGetSession(String jsessionid, String userpwd) {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    try {
        StringBuilder sb = new StringBuilder("ws://localhost:");
        sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH)
                .append("ocelot-endpoint");
        URI uri = new URI(sb.toString());
        return container.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {
            }
        }, createClientEndpointConfigWithJsession(jsessionid, userpwd), uri);
    } catch (URISyntaxException | DeploymentException | IOException ex) {
        ex.getCause().printStackTrace();
        fail("CONNEXION FAILED " + ex.getMessage());
    }
    return null;
}