Example usage for io.vertx.core.http HttpMethod PUT

List of usage examples for io.vertx.core.http HttpMethod PUT

Introduction

In this page you can find the example usage for io.vertx.core.http HttpMethod PUT.

Prototype

HttpMethod PUT

To view the source code for io.vertx.core.http HttpMethod PUT.

Click Source Link

Usage

From source file:org.azrul.langmera.DecisionService.java

@Override
public void start(Future<Void> fut) {

    // Create a router object.
    Router router = Router.router(vertx);

    //enable CORS
    if (config.getProperty("enableCors", Boolean.class)) {
        String allowedAddress = config.getProperty("cors.allowedAddress", String.class);

        CorsHandler c = CorsHandler.create(allowedAddress);

        String allowedHeaders = config.getProperty("cors.allowedHeaders", String.class);
        if (allowedHeaders != null) {
            String[] allowedHeadersArray = allowedHeaders.split(",");
            c.allowedHeaders(new HashSet<String>(Arrays.asList(allowedHeadersArray)));
        }/*  w w w. j a  v a  2 s  .c  o  m*/
        String allowedMethods = config.getProperty("cors.allowedMethods", String.class);
        if (allowedMethods != null) {
            String[] allowedMethodsArray = allowedMethods.split(",");
            for (String m : allowedMethodsArray) {
                if ("POST".equals(m)) {
                    c.allowedMethod(HttpMethod.POST);
                } else if ("PUT".equals(m)) {
                    c.allowedMethod(HttpMethod.PUT);
                } else if ("GET".equals(m)) {
                    c.allowedMethod(HttpMethod.GET);
                } else if ("DELETE".equals(m)) {
                    c.allowedMethod(HttpMethod.DELETE);
                }
            }
        }

        router.route().handler(c);
    }
    //Handle body
    router.route().handler(BodyHandler.create());

    //router.route("/langmera/assets/*").handler(StaticHandler.create("assets"));
    router.post("/langmera/api/makeDecision").handler(this::makeDecision);
    router.post("/langmera/api/acceptFeedback").handler(this::acceptFeedback);
    //router.post("/langmera/api/getHistory").handler(this::getHistory);
    //router.post("/langmera/api/getRequestTemplate").handler(this::getRequestTemplate);
    //router.post("/langmera/api/getResponseTemplate").handler(this::getFeedbackTemplate);

    HttpServerOptions options = new HttpServerOptions();
    options.setReuseAddress(true);

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx.createHttpServer(options).requestHandler(router::accept).listen(
            // Retrieve the port from the configuration,
            // default to 8080.
            config().getInteger("http.port", config.getProperty("http.port", Integer.class)), result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
}

From source file:org.eclipse.hono.adapter.http.vertx.VertxBasedHttpProtocolAdapter.java

License:Open Source License

private void addTelemetryApiRoutes(final Router router, final Handler<RoutingContext> authHandler) {

    // support CORS headers for PUTing telemetry
    router.routeWithRegex("\\/telemetry\\/[^\\/]+\\/.*")
            .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.PUT)
                    .allowedHeader(HttpHeaders.AUTHORIZATION.toString())
                    .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()));

    if (getConfig().isAuthenticationRequired()) {

        // support CORS headers for POSTing telemetry
        router.route("/telemetry")
                .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.POST)
                        .allowedHeader(HttpHeaders.AUTHORIZATION.toString())
                        .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()));

        // require auth for POSTing telemetry
        router.route(HttpMethod.POST, "/telemetry").handler(authHandler);

        // route for posting telemetry data using tenant and device ID determined as part of
        // device authentication
        router.route(HttpMethod.POST, "/telemetry").handler(this::handlePostTelemetry);

        // require auth for PUTing telemetry
        router.route(HttpMethod.PUT, "/telemetry/*").handler(authHandler);
        // assert that authenticated device's tenant matches tenant from path variables
        router.route(HttpMethod.PUT, String.format("/telemetry/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
                .handler(this::assertTenant);
    }// w w  w  .ja va2 s . c  o  m

    // route for uploading telemetry data
    router.route(HttpMethod.PUT, String.format("/telemetry/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
            .handler(ctx -> uploadTelemetryMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx)));
}

From source file:org.eclipse.hono.adapter.http.vertx.VertxBasedHttpProtocolAdapter.java

License:Open Source License

private void addEventApiRoutes(final Router router, final Handler<RoutingContext> authHandler) {

    // support CORS headers for PUTing events
    router.routeWithRegex("\\/event\\/[^\\/]+\\/.*")
            .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.PUT)
                    .allowedHeader(HttpHeaders.AUTHORIZATION.toString())
                    .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()));

    if (getConfig().isAuthenticationRequired()) {

        // support CORS headers for POSTing events
        router.route("/event")
                .handler(CorsHandler.create(getConfig().getCorsAllowedOrigin()).allowedMethod(HttpMethod.POST)
                        .allowedHeader(HttpHeaders.AUTHORIZATION.toString())
                        .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()));

        // require auth for POSTing events
        router.route(HttpMethod.POST, "/event").handler(authHandler);

        // route for posting events using tenant and device ID determined as part of
        // device authentication
        router.route(HttpMethod.POST, "/event").handler(this::handlePostEvent);

        // require auth for PUTing events
        router.route(HttpMethod.PUT, "/event/*").handler(authHandler);
        // route for asserting that authenticated device's tenant matches tenant from path variables
        router.route(HttpMethod.PUT, String.format("/event/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
                .handler(this::assertTenant);
    }//w w  w.  j  a  v  a  2s .  c  om

    // route for sending event messages
    router.route(HttpMethod.PUT, String.format("/event/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
            .handler(ctx -> uploadEventMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx)));
}

From source file:org.eclipse.hono.adapter.rest.VertxBasedRestProtocolAdapter.java

License:Open Source License

private void addTelemetryApiRoutes(final Router router) {

    // route for uploading telemetry data
    router.route(HttpMethod.PUT, String.format("/telemetry/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
            .handler(ctx -> uploadTelemetryMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx)));
}

From source file:org.eclipse.hono.adapter.rest.VertxBasedRestProtocolAdapter.java

License:Open Source License

private void addEventApiRoutes(final Router router) {

    // route for sending event messages
    router.route(HttpMethod.PUT, String.format("/event/:%s/:%s", PARAM_TENANT, PARAM_DEVICE_ID))
            .handler(ctx -> uploadEventMessage(ctx, getTenantParam(ctx), getDeviceIdParam(ctx)));
}

From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java

License:Open Source License

@Override
public void addRoutes(final Router router) {

    final String pathWithTenant = String.format("/%s/:%s", RegistrationConstants.REGISTRATION_ENDPOINT,
            PARAM_TENANT_ID);//from   ww w  .  j a v a 2s.  c  om
    // ADD device registration
    router.route(HttpMethod.POST, pathWithTenant).consumes(HttpEndpointUtils.CONTENT_TYPE_JSON)
            .handler(this::doRegisterDeviceJson);
    router.route(HttpMethod.POST, pathWithTenant)
            .consumes(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED.toString())
            .handler(this::doRegisterDeviceForm);
    router.route(HttpMethod.POST, pathWithTenant).handler(
            ctx -> HttpEndpointUtils.badRequest(ctx.response(), "missing or unsupported content-type"));

    final String pathWithTenantAndDeviceId = String.format("/%s/:%s/:%s",
            RegistrationConstants.REGISTRATION_ENDPOINT, PARAM_TENANT_ID, PARAM_DEVICE_ID);
    // GET device registration
    router.route(HttpMethod.GET, pathWithTenantAndDeviceId).handler(this::doGetDevice);

    // UPDATE existing registration
    router.route(HttpMethod.PUT, pathWithTenantAndDeviceId).consumes(HttpEndpointUtils.CONTENT_TYPE_JSON)
            .handler(this::doUpdateRegistrationJson);
    router.route(HttpMethod.PUT, pathWithTenantAndDeviceId)
            .consumes(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED.toString())
            .handler(this::doUpdateRegistrationForm);
    router.route(HttpMethod.PUT, pathWithTenantAndDeviceId).handler(
            ctx -> HttpEndpointUtils.badRequest(ctx.response(), "missing or unsupported content-type"));

    // REMOVE registration
    router.route(HttpMethod.DELETE, pathWithTenantAndDeviceId).handler(this::doUnregisterDevice);
}

From source file:org.etourdot.vertx.marklogic.http.impl.request.DefaultMarklogicRequest.java

License:Open Source License

@Override
public MarkLogicRequest put(String uri) {
    return method(uri, HttpMethod.PUT);
}

From source file:org.folio.auth.login_module.MainVerticle.java

private void handleUser(RoutingContext ctx) {
    String tenant = ctx.request().headers().get("X-Okapi-Tenant");
    String requestBody = null;// ww w  .j  a  v a 2s. co  m
    if (ctx.request().method() == HttpMethod.POST || ctx.request().method() == HttpMethod.PUT) {
        requestBody = ctx.getBodyAsString();
    }
    if (ctx.request().method() == HttpMethod.POST) {
        JsonObject postData = new JsonObject(requestBody);
        JsonObject credentials = postData.getJsonObject("credentials");
        JsonObject metadata = postData.getJsonObject("metadata");
        authSource.addAuth(credentials, metadata, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to add user");
            } else {
                ctx.response().setStatusCode(201).end("Added user");
            }
        });

    } else if (ctx.request().method() == HttpMethod.PUT) {
        String username = ctx.request().getParam("username");
        JsonObject postData = new JsonObject(requestBody);
        JsonObject credentials = postData.getJsonObject("credentials");
        JsonObject metadata = postData.getJsonObject("metadata");
        if (!credentials.getString("username").equals(username)) {
            ctx.response().setStatusCode(400).end("Invalid user");
            return;
        }
        authSource.updateAuth(credentials, metadata, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to update user");
            } else {
                ctx.response().setStatusCode(200).end("Updated user");
            }
        });
    } else if (ctx.request().method() == HttpMethod.DELETE) {
        String username = ctx.request().getParam("username");
        authSource.deleteAuth(username, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to remove user");
            } else {
                ctx.response().setStatusCode(200).end("Deleted user");
            }
        });
    } else {
        ctx.response().setStatusCode(400).end("Unsupported operation");
        return;
    }
}

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 va2 s  .com*/
    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());
                }
            });

}

From source file:spring.vertxtest.verticle.MyTestVerticle.java

@Override
public void start(Future<Void> fut) throws Exception {
    log.info("start() -- starting Vertx Verticle with eventbus, API handler, and static file handler");

    // grab the router
    router = getRouter();/*from   w w w. j  a  v  a 2 s  . c  o  m*/

    // enable CORS for the router 
    CorsHandler corsHandler = CorsHandler.create("*"); //Wildcard(*) not allowed if allowCredentials is true
    corsHandler.allowedMethod(HttpMethod.OPTIONS);
    corsHandler.allowedMethod(HttpMethod.GET);
    corsHandler.allowedMethod(HttpMethod.POST);
    corsHandler.allowedMethod(HttpMethod.PUT);
    corsHandler.allowedMethod(HttpMethod.DELETE);
    corsHandler.allowCredentials(false);
    corsHandler.allowedHeader("Access-Control-Request-Method");
    corsHandler.allowedHeader("Access-Control-Allow-Method");
    corsHandler.allowedHeader("Access-Control-Allow-Credentials");
    corsHandler.allowedHeader("Access-Control-Allow-Origin");
    corsHandler.allowedHeader("Access-Control-Allow-Headers");
    corsHandler.allowedHeader("Content-Type");

    // enable handling of body
    router.route().handler(BodyHandler.create());
    router.route().handler(corsHandler);
    router.route().handler(this::handleAccessLogging);

    // publish a payload to provided eventbus destination
    router.post("/api/eventbus/publish/:destination").handler(this::publish);

    // open up all for outbound and inbound traffic
    bridgeOptions = new BridgeOptions();
    bridgeOptions.addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
    bridgeOptions.addInboundPermitted(new PermittedOptions().setAddressRegex(".*"));
    //        sockJsHandler = SockJSHandler.create(vertx).bridge(bridgeOptions);   
    sockJsHandler = SockJSHandler.create(vertx);
    sockJsHandler.bridge(bridgeOptions, be -> {
        try {
            if (be.type() == BridgeEventType.SOCKET_CREATED) {
                handleSocketOpenEvent(be);
            } else if (be.type() == BridgeEventType.REGISTER) {
                handleRegisterEvent(be);
            } else if (be.type() == BridgeEventType.UNREGISTER) {
                handleUnregisterEvent(be);
            } else if (be.type() == BridgeEventType.SOCKET_CLOSED) {
                handleSocketCloseEvent(be);
            }
        } catch (Exception e) {

        } finally {
            be.complete(true);
        }
    });
    router.route("/eventbus/*").handler(sockJsHandler);

    if (testPathEnabled) {
        router.route("/" + testUrlPath + "/*")
                .handler(StaticHandler.create(testFilePath).setCachingEnabled(cachingEnabled));
    }

    // create periodic task, pushing all current EventBusRegistrations
    vertx.setPeriodic(1000, handler -> {
        JsonObject obj = new JsonObject();
        obj.put("testMessage", "Periodic test message from server...");
        vertx.eventBus().publish("heartbeat-test", Json.encodePrettily(obj));
    });

    EventBus eb = vertx.eventBus();
    eb.consumer("client-test", message -> {
        log.info("Received message from client: " + Json.encodePrettily(message.body()) + " at "
                + System.currentTimeMillis());
    });

    HttpServerOptions httpOptions = new HttpServerOptions();
    if (sslEnabled) {
        httpOptions.setSsl(true);
        httpOptions.setKeyStoreOptions(sslKeyStoreOptions);
    }

    log.info("starting web server on port: " + port);
    vertx.createHttpServer(httpOptions).requestHandler(router::accept).listen(port, result -> {
        if (result.succeeded()) {
            setStarted(true);
            log.info("Server started and ready to accept requests");
            fut.complete();
        } else {
            setStarted(false);
            fut.fail(result.cause());
        }
    });
}