Example usage for javax.websocket Session getBasicRemote

List of usage examples for javax.websocket Session getBasicRemote

Introduction

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

Prototype

RemoteEndpoint.Basic getBasicRemote();

Source Link

Usage

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

private void connectToWebSocket(UserInfo requesterUserInfo, boolean expectSuccess) {

    try {/*from   w  w w  . j  av  a2s  .c  om*/

        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:io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

public void closeConnection(Session session, String hdfsUsername,
        NotebookServerImplFactory notebookServerImplFactory) {
    try {//from  w w w .ja va 2 s  . c  o  m
        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.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

public void sendMsg(Session conn, String msg) throws IOException {
    if (conn == null || !conn.isOpen()) {
        LOG.log(Level.SEVERE, "Can't handle message. The connection has been closed.");
        return;// w ww  .java  2s  .  c  o  m
    }
    conn.getBasicRemote().sendText(msg);
}

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   w ww. ja v a2 s. c  o m*/
 *   /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);
        }
    }
}

From source file:org.apache.hadoop.gateway.websockets.WebsocketEchoTest.java

/**
 * Test direct connection to websocket server without gateway
 * // w  ww.  jav  a  2 s.c o  m
 * @throws Exception
 */
@Test
public void testDirectEcho() throws Exception {

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    WebsocketClient client = new WebsocketClient();

    Session session = container.connectToServer(client, backendServerUri);

    session.getBasicRemote().sendText("Echo");
    client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);

}

From source file:org.apache.hadoop.gateway.websockets.WebsocketEchoTest.java

/**
 * Test websocket proxying through gateway.
 * //from   ww  w.j  av  a 2  s  .  c o m
 * @throws Exception
 */
@Test
public void testGatewayEcho() throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    WebsocketClient client = new WebsocketClient();
    Session session = container.connectToServer(client, new URI(serverUri.toString() + "gateway/websocket/ws"));

    session.getBasicRemote().sendText("Echo");
    client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);

    assertThat(client.messageQueue.get(0), is("Echo"));

}

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

/**
 * Sends a command to the servewr//from  w w  w.  j a  va2s. co  m
 * @param command The command to send
 * @param callback The callback to send Command results to. May be null if no callback is required
 * @param <C> The type of the Command
 * @param <R> The type of the Command result.
 */
public <C, R> void send(CommandMessage<C> command, CommandCallback<? super C, R> callback) {
    ByteBuffer data = ByteBuffer.wrap(serializer
            .serialize(new WebsocketCommandMessage<>(command, callback != null), byte[].class).getData());

    try {
        Session session = sessions.borrowObject();
        try {
            LOGGER.debug("Using session " + session.getId() + " to send " + command.getCommandName());
            if (callback != null) {
                repository.store(command.getIdentifier(),
                        new CommandCallbackWrapper<>(session.getId(), command, callback));
            }
            session.getBasicRemote().sendBinary(data);
        } finally {
            sessions.returnObject(session);
        }
    } catch (Exception e) {
        LOGGER.error("Error sending command", e);
        if (callback != null) {
            callback.onFailure(command, new CommandBusConnectorCommunicationException(
                    "Failed to send command of type " + command.getCommandName() + " to remote", e));
        }
    }
}

From source file:org.ballerinalang.composer.service.ballerina.launcher.service.LaunchManager.java

/**
 * Push message to client.//from   w ww  . j av  a  2s. c o m
 *
 * @param session the debug session
 * @param status  the status
 */
public void pushMessageToClient(Session session, MessageDTO status) {
    Gson gson = new Gson();
    String json = gson.toJson(status);
    try {
        session.getBasicRemote().sendText(json);
    } catch (IOException e) {
        logger.error("Error while pushing messages to client.", e);
    }
}

From source file:org.damcode.web.c4webserver.Server.java

@OnOpen
public void onOpen(Session session, @PathParam("id") String gameId) throws IOException {
    printSysOut("new session: " + session.getId() + ", game id: " + gameId + "from ip: ");
    session.getUserProperties().put("gameid", gameId);
    session.getUserProperties().put("lobby", true);

    String connectedPlayers = "";
    int pCount = 0;
    for (Session s : session.getOpenSessions()) {
        if (!s.equals(session)) {
            String name = (String) s.getUserProperties().get("name");
            connectedPlayers += name + ", ";
            pCount++;// w  w  w  .j a  va 2  s. c  o  m
        }
    }
    if (pCount > 0) {
        printSysOut("Connected Players: " + connectedPlayers);
        session.getBasicRemote()
                .sendText(Utils.assembleChatMessage("Server", connectedPlayers, "other players"));
    }

    for (GameController gc : waitingGames) {
        sendGameAvailMessage(session, gc.getId().toString(), gc.players.get(0));
    }
}

From source file:org.damcode.web.c4webserver.Server.java

public void sendGameAvailMessage(Session s, String gameId, Player host) {
    try {/*  ww w.  j  a v  a  2s . c  om*/
        JSONObject obj = new JSONObject().put("cmd", MessageBean.MSG_GAME_AVAILABLE).put("data",
                new JSONObject().put("id", gameId).put("host", host.getName()));

        s.getBasicRemote().sendText(obj.toString());
    } catch (IOException ex) {
        Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
    }

}