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

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

Introduction

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

Prototype

HttpMethod POST

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

Click Source Link

Usage

From source file:com.hubrick.vertx.rest.rx.impl.DefaultRxRestClient.java

License:Apache License

@Override
public <T> Observable<RestClientResponse<T>> post(String uri, Class<T> responseClass,
        Action1<RestClientRequest> requestBuilder) {
    return request(HttpMethod.POST, uri, responseClass, requestBuilder);
}

From source file:com.mycompany.aktakurvanmavenbackend.UserService.java

@Override
public void start() {

    Router router = Router.router(vertx);

    //testa om servicen fungerar
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response.putHeader("content-type", "text/html")
                .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });//from  w  ww .ja va  2 s.  c o  m

    //skapa bodyhandler fr att kunna lsa body i requests
    router.route(HttpMethod.POST, "/*").handler(BodyHandler.create());

    router.post("/api/friends").handler(this::getUsersFriends);
    router.post("/api/login").handler(this::login);
    router.post("/api/updatedevicetoken").handler(this::updateDeviceToken);
    router.post("/api/addfriend").handler(this::addFriend);
    router.post("/api/getpendingfriends").handler(this::getPendingFriends);
    router.post("/api/respondfriendrequest").handler(this::respondFriendRequest);
    router.post("/api/getfriends").handler(this::getFriends);
    router.post("/api/challenge").handler(this::challengeFriend);

    //Initiera firebase
    FileInputStream serviceAccount;
    try {
        serviceAccount = new FileInputStream(
                "D:\\Firebase\\mobilapp-67b55-firebase-adminsdk-ijhds-43eb2c5271.json");
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("https://mobilapp-67b55.firebaseio.com").build();
        firebaseApp = FirebaseApp.initializeApp(options);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Couldnt start User service");
    } catch (IOException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Couldnt start User service");
    }

    vertx.createHttpServer().requestHandler(router::accept).listen(7932);
    System.out.println("User service started");

}

From source file:com.waves_rsp.ikb4stream.communication.web.VertxServer.java

License:Open Source License

/**
 * Server starting behaviour/*w ww  .j  a  va  2s  . com*/
 *
 * @param fut Future that handles the start status
 * @throws NullPointerException if fut is null
 */
@Override
public void start(Future<Void> fut) {
    Objects.requireNonNull(fut);
    Router router = Router.router(vertx);
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("X-PINGARUNER").allowedHeader("Content-Type"));

    router.route("/anomaly*").handler(BodyHandler.create()); // enable reading of request's body
    router.get("/anomaly").handler(this::getAnomalies);
    router.post("/anomaly").handler(this::getAnomalies);
    vertx.createHttpServer().requestHandler(router::accept).listen(config().getInteger("http.port", 8081), // default value: 8081
            result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
    LOGGER.info("VertxServer started");
}

From source file:de.braintags.netrelay.controller.authentication.FormLoginHandlerBt.java

License:Open Source License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {// w  ww . j  a v  a2  s.  c  o  m
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - did you forget to include a BodyHandler?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(usernameParam);
        String password = params.get(passwordParam);
        if (username == null || password == null) {
            LOGGER.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else {
            JsonObject authInfo = new JsonObject().put("username", username).put("password", password);
            authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    User user = res.result();
                    LOGGER.info("Login success, found user " + user);
                    MemberUtil.setContextUser(context, user);
                    if (redirectBySession(context)) {
                        return;
                    }
                    // Either no session or no return url
                    if (!redirectByDirectLoginUrl(context)) {
                        // Just show a basic page
                        req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
                    }
                } else {
                    LOGGER.info("authentication failed: " + res.cause());
                    handleAuthenticationError(context, res.cause());
                }
            });
        }
    }
}

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", "")));
    });/*w  w  w.  j  ava 2 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:es.upv.grycap.opengateway.core.http.BaseRestService.java

License:Apache License

@Override
public void start() throws Exception {
    requireNonNull(serviceConfig, "A valid service configuration expected");
    requireNonNull(loadBalancerClient, "A valid load balancer client expected");
    // set body limit and create router
    final long maxBodySize = context.config().getLong("http-server.max-body-size", MAX_BODY_SIZE_MIB) * 1024l
            * 1024l;//from   w w  w .jav a  2 s.c o  m
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create().setBodyLimit(maxBodySize));
    // enable CORS
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.DELETE).allowedMethod(HttpMethod.OPTIONS)
            .allowedHeader("Content-Type").allowedHeader("Authorization"));
    // configure index page      
    router.route(serviceConfig.getFrontpage().orElse("/")).handler(StaticHandler.create());
    // serve resources
    serviceConfig.getServices().values().stream().forEach(s -> {
        final String path = requireNonNull(s.getPath(), "A valid path required");
        router.get(String.format("%s/:id", path)).produces("application/json").handler(e -> handleGet(s, e));
        router.get(path).produces("application/json").handler(e -> handleList(s, e));
        router.post(path).handler(e -> handleCreate(s, e));
        router.put(String.format("%s/:id", path)).consumes("application/json").handler(e -> handleModify(s, e));
        router.delete(String.format("%s/:id", path)).handler(e -> handleDelete(s, e));
    });
    // start HTTP server
    final int port = context.config().getInteger("http.port", 8080);
    vertx.createHttpServer().requestHandler(router::accept).listen(port);
    logger.trace("New instance created: [id=" + context.deploymentID() + "].");
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example33(Vertx vertx) {
    HttpClient client = vertx.createHttpClient();

    client.request(HttpMethod.GET, "some-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    }).end();/*w w w. jav a  2s .c o m*/

    client.request(HttpMethod.POST, "foo-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    }).end("some-data");
}

From source file:gribbit.route.Route.java

License:Open Source License

/**
 * Call the get() or post() method for the Route corresponding to the request URI.
 * //from  w w w  .  j  av  a2 s  .c o  m
 * @param reqURL
 */
public Response callHandler(RoutingContext routingContext, ParsedURL reqURL) throws ResponseException {
    Response response;
    // Determine param vals for method
    HttpServerRequest request = routingContext.request();
    HttpMethod reqMethod = request.method();

    if (reqMethod == HttpMethod.GET) {
        // Bind URI params
        Object[] getParamVals = bindGetParamsFromURI(reqURL);

        // Invoke the get() method with URI params
        response = invokeMethod(routingContext, getMethod, getParamVals, getRoles, /* checkAuthorized = */ true,
                /* checkCSRFTok = */ false);

    } else if (reqMethod == HttpMethod.POST) {
        // Bind the post() method's single parameter (if it has one) from the POST data in the request
        Object[] postParamVal = bindPostParamFromPOSTData(request, reqURL);

        // Invoke the post() method
        response = invokeMethod(routingContext, postMethod, postParamVal, postRoles,
                /* checkAuthorized = */ true, /* checkCSRFTok = */ true);

    } else {
        // Method not allowed
        response = new ErrorResponse(HttpResponseStatus.METHOD_NOT_ALLOWED, "HTTP method not allowed");
    }

    if (response == null) {
        // Should not happen
        throw new InternalServerErrorException("Didn't generate a response");
    }

    return response;
}

From source file:gribbit.route.Route.java

License:Open Source License

/**
 * Get the route annotated with the given HTTP method on the given RestHandler, substituting the key/value pairs
 * into the params in the URL template.// w  ww . jav  a 2  s  .c  o m
 * 
 * Can call this method with no urlParams if the handler takes no params for this httpMethod, otherwise list URL
 * params in the varargs. URL params can be any type, and their toString() method will be called. Param values
 * will be URL-escaped (turned into UTF-8, then byte-escaped if the bytes are not safe).
 */
private static String forMethod(HttpMethod httpMethod, Class<? extends RouteHandler> handlerClass,
        Object... urlParams) {
    Route handler = GribbitServer.siteResources.routeForClass(handlerClass);

    if (httpMethod == HttpMethod.GET) {
        if (handler.getMethod == null) {
            throw new RuntimeException("Handler " + handlerClass.getName() + " does not have a get() method");
        }

        for (Object param : urlParams) {
            if (param == null) {
                throw new RuntimeException("null values are not allowed in URL params");
            }
        }
        if (urlParams.length != handler.getParamTypes.length) {
            throw new RuntimeException(
                    "Wrong number of URL params for method " + handlerClass.getName() + ".get()");
        }
        // Build new fully-specified route from route stem and URL params 
        StringBuilder buf = new StringBuilder(handler.routePath.getNormalizedPath());
        for (int i = 0; i < urlParams.length; i++) {
            buf.append('/');
            URLUtils.escapeURLSegment(urlParams[i].toString(), buf);
        }
        return buf.toString();

    } else if (httpMethod == HttpMethod.POST) {
        if (handler.postMethod == null) {
            throw new RuntimeException("Handler " + handlerClass.getName() + " does not have a post() method");
        }
        if (urlParams.length != 0) {
            throw new RuntimeException(
                    "Tried to pass URL params to a POST method, " + handlerClass.getName() + ".post()");
        }
        return handler.routePath.getNormalizedPath();

    } else {
        throw new RuntimeException("Bad HTTP method: " + httpMethod);
    }
}

From source file:gribbit.route.Route.java

License:Open Source License

/**
 * Return the route path for the POST method handler of a RestHandler class.
 */// w w w.j av a 2s  . co m
public static String forPost(Class<? extends RouteHandler> handlerClass) {
    return Route.forMethod(HttpMethod.POST, handlerClass);
}