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

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

Introduction

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

Prototype

HttpMethod DELETE

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

Click Source Link

Usage

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   w ww  .ja va 2s . c  o m*/
    // 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 delete(String uri) {
    return method(uri, HttpMethod.DELETE);
}

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;//w w  w.j a va 2  s  .  c  o 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.folio.auth.permissions_module.MainVerticle.java

private void handleUser(RoutingContext context) {
    String tenant = context.request().headers().get(TENANT_HEADER);
    if (context.request().method() == HttpMethod.POST) {
        String username;// www .j a va2s .  c  o  m
        try {
            username = context.getBodyAsString();
        } catch (Exception e) {
            context.response().setStatusCode(400).end("Please provide a username");
            return;
        }
        store.addUser(username, tenant).setHandler(res -> {
            if (res.succeeded()) {
                context.response().setStatusCode(201).end("User added");
            } else {
                context.response().setStatusCode(500).end("Unable to add user");
            }
        });
    } else if (context.request().method() == HttpMethod.DELETE) {
        String username = context.request().getParam("username");
        store.removeUser(username, tenant).setHandler(res -> {
            if (res.succeeded()) {
                context.response().setStatusCode(200).end("User removed");
            } else {
                context.response().setStatusCode(500).end("Unable to remove user");
            }
        });
    } else if (context.request().method() == HttpMethod.GET) {
        String username = context.request().getParam("username");
        if (username == null) {
            context.response().setStatusCode(400).end("Not yet supported");
        } else {
            store.getUser(username, tenant).setHandler(res -> {
                if (res.failed()) {
                    context.response().setStatusCode(500).end("Unable to get user");
                } else {
                    context.response().setStatusCode(200).end(res.result().encode());
                }
            });
        }
    } else {
        context.response().setStatusCode(400).end("Unsupported method");
    }
}

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

private void handlePermission(RoutingContext context) {
    String tenant = context.request().headers().get(TENANT_HEADER);
    String postData = null;/* w  w  w  .  j  a  v a2 s  .c  o  m*/
    if (context.request().method() == HttpMethod.POST) {
        postData = context.getBodyAsString();
    }
    if (context.request().method() == HttpMethod.POST) {
        String permissionName = context.request().getParam("permissionname");
        if (permissionName == null) {
            //Adding new permission
            JsonObject perm;
            String permName;
            JsonArray permSubs;
            try {
                perm = new JsonObject(postData);
            } catch (Exception e) {
                context.response().setStatusCode(400).end("Unable to parse " + postData + " into valid JSON");
                return;
            }
            permName = perm.getString("permission_name");
            if (permName == null) {
                context.response().setStatusCode(400).end("permission_name field is not present");
            }
            permSubs = perm.getJsonArray("sub_permissions");
            store.addPermission(permName, tenant).setHandler(res -> {
                if (res.failed()) {
                    logger.debug("Unable to add permission: " + res.cause().getMessage());
                    context.response().setStatusCode(500).end("Unable to add permission");
                } else {
                    if (permSubs == null) {
                        context.response().setStatusCode(201).end("Permission added");
                    } else {
                        ArrayList<Future> futureList = new ArrayList<>();
                        for (Object o : permSubs) {
                            String sub = (String) o;
                            futureList.add(store.addSubPermission(permName, sub, tenant));
                        }
                        CompositeFuture compFut = CompositeFuture.all(futureList);
                        compFut.setHandler(res2 -> {
                            if (res2.failed()) {
                                logger.debug("Error adding subpermissions: " + res2.cause().getMessage());
                                context.response().setStatusCode(500).end("Error adding sub permission");
                            } else {
                                context.response().setStatusCode(201).end("Permission added");
                            }
                        });
                    }
                }
            });
        } else {
            //Adding new sub-permission
            store.addSubPermission(permissionName, postData, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to add permission");
                    return;
                }
                context.response().setStatusCode(201).end("Sub-Permission added");
            });
        }
    } else if (context.request().method() == HttpMethod.GET) {
        String permissionName = context.request().getParam("permissionname");
        if (permissionName == null) {
            context.response().setStatusCode(400).end("You must specify a permission name");
            return;
        }
        //store.getSubPermissions(permissionName, tenant).setHandler(res -> {
        store.getPermission(permissionName, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                context.response().setStatusCode(500).end("Unable to retrieve permissions");
                return;
            }
            context.response().setStatusCode(200).putHeader("Content-Type", "application/json")
                    .end(res.result().encode());
        });
    } else if (context.request().method() == HttpMethod.DELETE) {
        String permissionName = context.request().getParam("permissionname");
        String subPermissionName = context.request().getParam("subpermissionname");
        if (permissionName == null && subPermissionName == null) {
            context.response().setStatusCode(400).end("Unsupported path");
            return;
        } else if (subPermissionName == null) {
            //remove permission
            store.removePermission(permissionName, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to delete permission");
                    return;
                }
                context.response().setStatusCode(200).end("Permission deleted");
            });
        } else {
            //remove sub permission
            store.removeSubPermission(permissionName, subPermissionName, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to delete subpermission");
                    return;
                }
                context.response().setStatusCode(200).end("Sub permission deleted");
            });
        }
    } else {
        context.response().setStatusCode(400).end("Unsupported method");
    }

}

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

private void handleUserPermission(RoutingContext context) {
    String tenant = context.request().headers().get(TENANT_HEADER);
    String username = context.request().getParam("username");
    String permissionName = context.request().getParam("permissionname");
    String postData = null;//ww  w .j av  a 2  s . c o  m
    if (context.request().method() == HttpMethod.POST) {
        postData = context.getBodyAsString();
    }
    if (username == null) {
        context.response().setStatusCode(400).end("Invalid username specification");
        return;
    }
    /*Add a permission to a user */
    /* format:
    { "permission_name" : "some.new.permission" }
    */
    if (context.request().method() == HttpMethod.POST) {
        JsonObject perm;
        try {
            perm = new JsonObject(postData);
        } catch (Exception e) {
            context.response().setStatusCode(400).end("Unable to parse " + postData + " into valid JSON");
            return;
        }
        String addPermissionName = perm.getString("permission_name");
        store.addPermissionToUser(username, addPermissionName, tenant).setHandler(res -> {
            if (res.failed()) {
                context.response().setStatusCode(500).end("Unable to add permission to user");
            } else {
                context.response().setStatusCode(201).end("Added permission to user");
            }
        });
    } else if (context.request().method() == HttpMethod.GET) {
        store.getPermissionsForUser(username, tenant).setHandler(res -> {
            if (res.failed()) {
                context.response().setStatusCode(500)
                        .end("Unable to retrieve user permissions " + res.cause().getMessage());
            } else {
                context.response().setStatusCode(200).putHeader("Content-Type", "application/json")
                        .end(res.result().encode());
            }
            return;
        });
    } else if (context.request().method() == HttpMethod.DELETE) {
        if (permissionName == null) {
            context.response().setStatusCode(400).end("Invalid permission name specification");
            return;
        }
        store.removePermissionFromUser(username, permissionName, tenant).setHandler(res -> {
            if (res.failed()) {
                context.response().setStatusCode(500).end("Unable to delete permission from user");
            } else {
                context.response().setStatusCode(200).end("Permission removed from user");
            }
        });
    } else {
        context.response().setStatusCode(400).end("Unsupported method");
    }
}

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 + "/";
    }/*from  w w  w .  j  a  v  a 2  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  ww.j  a  va  2s.com

    // 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());
        }
    });
}