Example usage for io.vertx.core.http HttpHeaders ORIGIN

List of usage examples for io.vertx.core.http HttpHeaders ORIGIN

Introduction

In this page you can find the example usage for io.vertx.core.http HttpHeaders ORIGIN.

Prototype

CharSequence ORIGIN

To view the source code for io.vertx.core.http HttpHeaders ORIGIN.

Click Source Link

Document

Origin header name

Usage

From source file:de.elsibay.EbbTicketShowcase.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    SessionStore sessionStore = LocalSessionStore.create(vertx);
    Router backendRouter = Router.router(vertx);
    backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));
    CookieHandler cookieHandler = CookieHandler.create();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    // the CORS OPTION request must not set cookies
    backendRouter.get().handler(cookieHandler);
    backendRouter.get().handler(sessionHandler);
    backendRouter.post().handler(cookieHandler);
    backendRouter.post().handler(sessionHandler);

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT)
            .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString())
            .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    // setup event bus bridge
    TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore);
    backendRouter.mountSubRouter("/eventbus", sebb.route(vertx));

    // dummy eventbus services
    vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> {
        msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", "")));
    });/*  ww w  .ja v a2 s . c o m*/

    vertx.setPeriodic(5000, id -> {
        vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime()));
    });

    // session manager for login
    backendRouter.route("/api/*").handler(corsHandler);
    backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create());

    backendRouter.route("/api/session").handler((RoutingContext rc) -> {
        JsonObject user = rc.getBodyAsJson();
        String sessionId = rc.session().id();
        rc.session().put("user", user);
        rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily());
    });

    // dummy ping REST service
    backendRouter.route("/api/ping").handler((RoutingContext rc) -> {
        JsonObject replyMsg = new JsonObject();
        replyMsg.put("timestamp", new Date().getTime());
        Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME);
        if (sessionCookie != null) {
            replyMsg.put("sessionId", sessionCookie.getValue());
        }
        rc.response().end(replyMsg.encode());
    });

    // start backend on one port
    vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT,
            BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> {
                System.out
                        .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED");
            });

    // static files on other port
    Router staticFilesRouter = Router.router(vertx);
    staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false));
    vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST,
            (AsyncResult<HttpServer> async) -> {
                System.out.println(async.succeeded()
                        ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/"
                        : "Web Server start FAILED");
            });
}

From source file:org.eclipse.hono.devices.HonoHttpDevice.java

License:Open Source License

/**
 * Send a message to Hono HTTP adapter. Delay any successful response by 1000 milliseconds.
 *
 * @param payload JSON object that will be sent as UTF-8 encoded String.
 * @param headersToAdd A map that contains all headers to add to the http request.
 * @param asEvent If {@code true}, an event message is sent, otherwise a telemetry message.
 * @return CompletableFuture&lt;MultiMap&gt; A completable future that contains the HTTP response in a MultiMap.
 *//* ww  w  .  j  av  a 2  s .  c  om*/
private CompletableFuture<MultiMap> sendMessage(final JsonObject payload, final MultiMap headersToAdd,
        final boolean asEvent) {
    final CompletableFuture<MultiMap> result = new CompletableFuture<>();

    final Predicate<Integer> successfulStatus = statusCode -> statusCode == HttpURLConnection.HTTP_ACCEPTED;
    final HttpClientRequest req = vertx.createHttpClient()
            .post(HONO_HTTP_ADAPTER_PORT, HONO_HTTP_ADAPTER_HOST, asEvent ? "/event" : "/telemetry")
            .handler(response -> {
                if (successfulStatus.test(response.statusCode())) {
                    vertx.setTimer(1000, l -> result.complete(response.headers()));
                } else {
                    result.completeExceptionally(new ServiceInvocationException(response.statusCode()));
                }
            }).exceptionHandler(t -> result.completeExceptionally(t));

    req.headers().addAll(headersToAdd);
    req.headers()
            .addAll(MultiMap.caseInsensitiveMultiMap()
                    .add(HttpHeaders.AUTHORIZATION, getBasicAuth(TENANT_ID, DEVICE_AUTH_ID, DEVICE_PASSWORD))
                    .add(HttpHeaders.ORIGIN, ORIGIN_URI));

    if (payload == null) {
        req.end();
    } else {
        req.end(payload.encode());
    }
    return result;
}

From source file:org.jadala.pne.Bootstrap.java

@Override
public void start(Future<Void> startFuture) throws Exception {

    final String originPattern = this.config().getString("origin_pattern", ORIGIN_PATTERN);

    final int httpPort = this.config().getInteger("http_port", 8080);
    String cp = this.config().getString("context", "/");
    if (!cp.endsWith("/")) {
        cp = cp + "/";
    }/*  w w w .  j a  va 2 s.  c  o  m*/
    if (!cp.startsWith("/")) {
        cp = "/" + cp;
    }
    final String contextPath = cp;

    Router router = Router.router(vertx);
    router.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create(originPattern).allowCredentials(true)
            .allowedHeader(HttpHeaders.ACCEPT.toString()).allowedHeader(HttpHeaders.ORIGIN.toString())
            .allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    router.route(contextPath + "api/*").handler(corsHandler);
    router.route(contextPath + "api/*").method(HttpMethod.POST).method(HttpMethod.PUT)
            .handler(BodyHandler.create());

    // config jwt service
    JsonWebTokenHandler jwtService = new JsonWebTokenHandler(vertx, config().getJsonObject("keyStore"));
    router.post(contextPath + "api/jwt").handler(jwtService);

    // status page
    String version = config().getString("version", "unknown");
    router.get(contextPath).handler(new StatusPageHandler(version));

    router.post(contextPath + "api/node").handler(new NodeHandler(vertx));
    router.get(contextPath + "api/node").handler(new NodeHandler(vertx));
    //        router.post(contextPath + "api/organisation").handler(new PersonHandler(vertx));
    //        router.get(contextPath + "api/organisation").handler(new PersonHandler(vertx));
    vertx.deployVerticle(ElasticClient.class.getName(), deploymentHandler("ElasticClient"));

    vertx.createHttpServer().requestHandler(router::accept).listen(httpPort,
            (AsyncResult<HttpServer> asyncHttpServer) -> {
                if (asyncHttpServer.succeeded()) {
                    System.out
                            .println("npe server started. listen at http://0.0.0.0:" + httpPort + contextPath);
                    startFuture.complete();
                } else {
                    startFuture.fail(asyncHttpServer.cause());
                }
            });

}