Example usage for io.vertx.core.http ServerWebSocket path

List of usage examples for io.vertx.core.http ServerWebSocket path

Introduction

In this page you can find the example usage for io.vertx.core.http ServerWebSocket path.

Prototype

String path();

Source Link

Usage

From source file:org.atmosphere.vertx.AtmosphereCoordinator.java

License:Apache License

/**
 * Route the {@link ServerWebSocket} into the {@link AtmosphereFramework}
 *
 * @param webSocket the {@link ServerWebSocket}
 *///ww w .  j ava  2  s . c  o m
public AtmosphereCoordinator route(ServerWebSocket webSocket) {
    Map<String, List<String>> paramMap = new QueryStringDecoder("?" + webSocket.query()).parameters();
    Map<String, String[]> params = new LinkedHashMap<String, String[]>(paramMap.size());
    for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
        params.put(entry.getKey(), entry.getValue().toArray(new String[] {}));
    }

    String contentType = "application/json";
    if (params.size() == 0) {
        // TODO: vert.x trim the query string, unfortunately.
        params.put(X_ATMO_PROTOCOL, new String[] { "true" });
        params.put(X_ATMOSPHERE_FRAMEWORK, new String[] { "2.1" });
        params.put(X_ATMOSPHERE_TRACKING_ID, new String[] { "0" });
        params.put(X_ATMOSPHERE_TRANSPORT, new String[] { "websocket" });
        params.put("Content-Type", new String[] { contentType });
    } else if (params.containsKey("Content-Type") && params.get("Content-Type").length > 0) {
        contentType = params.get("Content-Type")[0];
    }

    AtmosphereRequest.Builder requestBuilder = new AtmosphereRequest.Builder();
    AtmosphereRequest r = requestBuilder.requestURI(webSocket.path())
            .requestURL("http://0.0.0.0" + webSocket.path()).contentType(contentType).pathInfo(webSocket.path())
            .queryStrings(params).build();

    final WebSocket w = new VertxWebSocket(framework.getAtmosphereConfig(), webSocket);
    try {
        webSocketProcessor.open(w, r, AtmosphereResponse.newInstance(framework.getAtmosphereConfig(), r, w));
    } catch (IOException e) {
        logger.debug("", e);
    }

    webSocket.handler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer data) {
            webSocketProcessor.invokeWebSocketProtocol(w, data.toString());
        }
    });
    webSocket.exceptionHandler(new Handler<Throwable>() {
        @Override
        public void handle(Throwable event) {
            w.close();
            logger.debug("", event);
            webSocketProcessor.close(w, 1006);
        }
    });
    webSocket.closeHandler(new VoidHandler() {
        @Override
        protected void handle() {
            w.close();
            webSocketProcessor.close(w, 1005);
        }
    });
    return this;
}

From source file:org.atmosphere.vertx.WebsocketSessionHandler.java

License:Open Source License

@Override
public void handle(ServerWebSocket serverWebSocket) {
    String basePath = Optional.ofNullable(mountPoint).map(m -> m.substring(0, m.lastIndexOf('/'))).orElse("");

    if (!serverWebSocket.path().startsWith(basePath + "/PUSH")) {
        serverWebSocket.reject();//from  w w  w . j a va2s . co m
    }
    String cookieHeader = serverWebSocket.headers().get(COOKIE);

    if (cookieHeader != null) {
        Optional<String> sessionId = ServerCookieDecoder.STRICT.decode(cookieHeader).stream()
                .filter(cookie -> cookieName.equals(cookie.name())).findFirst().map(Cookie::value);
        if (sessionId.isPresent()) {
            sessionId.ifPresent(sid -> sessionStore.get(sid, event -> {
                Session session = null;
                if (event.succeeded()) {
                    session = event.result();
                }
                next.accept(serverWebSocket, session);
            }));
            return;
        }
    }
    next.accept(serverWebSocket, null);
}

From source file:org.entcore.workspace.controllers.AudioRecorderHandler.java

License:Open Source License

@Override
public void handle(final ServerWebSocket ws) {
    ws.pause();//from  w ww.j  av  a  2s. co m
    String sessionId = CookieHelper.getInstance().getSigned(SESSION_ID, ws);
    UserUtils.getSession(Server.getEventBus(vertx), sessionId, new Handler<JsonObject>() {
        public void handle(final JsonObject infos) {
            if (infos == null) {
                ws.reject();
                return;
            }
            final String id = ws.path().replaceFirst("/audio/", "");
            eb.send(AudioRecorderWorker.class.getSimpleName(),
                    new JsonObject().put("action", "open").put("id", id),
                    handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> m) {
                            if ("ok".equals(m.body().getString("status"))) {
                                ws.frameHandler(new Handler<WebSocketFrame>() {
                                    @Override
                                    public void handle(WebSocketFrame frame) {
                                        if (frame.isBinary()) {
                                            log.debug("frame handler");
                                            eb.send(AudioRecorderWorker.class.getSimpleName() + id,
                                                    frame.binaryData().getBytes(),
                                                    new DeliveryOptions().setSendTimeout(TIMEOUT),
                                                    new Handler<AsyncResult<Message<JsonObject>>>() {
                                                        @Override
                                                        public void handle(
                                                                AsyncResult<Message<JsonObject>> ar) {
                                                            if (ar.failed() || !"ok".equals(
                                                                    ar.result().body().getString("status"))) {
                                                                ws.writeTextMessage("audio.chunk.error");
                                                            }
                                                        }
                                                    });
                                        } else {
                                            final String command = frame.textData();
                                            if (command != null && command.startsWith("save-")) {
                                                save(id, command.substring(5), infos, ws);
                                            } else if ("cancel".equals(command)) {
                                                cancel(id, ws);
                                            } else if ("rawdata".equals(command)) {
                                                disableCompression(id, ws);
                                            }
                                        }
                                    }
                                });
                                ws.closeHandler(new Handler<Void>() {
                                    @Override
                                    public void handle(Void event) {
                                        cancel(id, null);
                                    }
                                });
                                ws.resume();
                            } else {
                                ws.writeTextMessage(m.body().getString("message"));
                            }
                        }
                    }));
        }
    });
}

From source file:org.wisdom.framework.vertx.WebSocketHandler.java

License:Apache License

/**
 * Handles a web socket connection.//w  ww  . j a va 2  s. co m
 *
 * @param socket the opening socket.
 */
@Override
public void handle(final ServerWebSocket socket) {
    LOGGER.info("New web socket connection {}, {}", socket, socket.uri());

    if (!configuration.accept(socket.uri())) {
        LOGGER.warn("Web Socket connection denied on {} by {}", socket.uri(), configuration.name());
        return;
    }

    final Socket sock = new Socket(socket);
    accessor.getDispatcher().addSocket(socket.path(), sock);

    socket.closeHandler(event -> {
        LOGGER.info("Web Socket closed {}, {}", socket, socket.uri());
        accessor.getDispatcher().removeSocket(socket.path(), sock);
    });

    socket.handler(event -> accessor.getDispatcher().received(socket.path(), event.getBytes(), sock));

}