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

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

Introduction

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

Prototype

HttpMethod GET

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

Click Source Link

Usage

From source file:examples.HTTP2Examples.java

License:Open Source License

public void example6(HttpServerRequest request) {

    HttpServerResponse response = request.response();

    // Push main.js to the client
    response.push(HttpMethod.GET, "/main.js", ar -> {

        if (ar.succeeded()) {

            // The server is ready to push the response
            HttpServerResponse pushedResponse = ar.result();

            // Send main.js response
            pushedResponse.putHeader("content-type", "application/json").end("alert(\"Push response hello\")");
        } else {//from   w w w .j  ava2  s .  co m
            System.out.println("Could not push client resource " + ar.cause());
        }
    });

    // Send the requested resource
    response.sendFile("<html><head><script src=\"/main.js\"></script></head><body></body></html>");
}

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();/*from   w ww . jav  a  2 s.  co 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   ww  w .j a  v 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.//from w ww .  j  a va  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 GET method handler of a RestHandler class, appending URL params.
 *//*  www.j  av a 2  s. c om*/
public static String forGet(Class<? extends RouteHandler> handlerClass, Object... urlParams) {
    return Route.forMethod(HttpMethod.GET, handlerClass, (Object[]) urlParams);
}

From source file:info.macias.sse.vertx3.example.chat.ChatVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    broadcaster = new EventBroadcast();

    Router router = Router.router(vertx);

    // Allows getting body in POST methods
    router.route().handler(BodyHandler.create());

    // Subscription request
    router.get("/send").handler(ctx -> {
        try {/*from w w  w .  ja v a 2s .  c o m*/
            broadcaster.addSubscriber(new VertxEventTarget(ctx.request()),
                    new MessageEvent.Builder().setData("*** Welcome to the chat server ***").build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    // Message send request
    router.post("/send").handler(ctx -> {
        Scanner scanner = new Scanner(ctx.getBodyAsString());
        StringBuilder sb = new StringBuilder();
        while (scanner.hasNextLine()) {
            sb.append(scanner.nextLine());
        }
        broadcaster.broadcast("message", dirtyJsonParse(sb.toString()));
    });

    router.route("/*").method(HttpMethod.GET).handler(StaticHandler.create("static"));

    // Instantiate HTTP server
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);

}

From source file:io.flowly.auth.AuthServer.java

License:Open Source License

private Handler<AsyncResult<String>> initServer(Future<Void> startFuture) {
    return h -> {
        if (h.succeeded()) {
            initAuthProvider(config());//from   ww  w  .j  ava  2 s . c o m

            // TODO: URGENT - Make this https.
            HttpServer server = vertx.createHttpServer();
            Router router = Router.router(vertx);
            router.route().handler(BodyHandler.create());

            // TODO: Add patterns from config.
            Set<HttpMethod> allowedMethods = new HashSet<>();
            allowedMethods.add(HttpMethod.GET);
            allowedMethods.add(HttpMethod.POST);

            router.route().handler(CorsHandler.create("http://localhost:.*").allowedHeader("Authorization")
                    .allowedMethods(allowedMethods).allowCredentials(true));

            StaticHandler staticHandler = StaticHandler.create();
            router.routeWithRegex(HttpMethod.GET, STATIC_FILES_PATTERN).handler(staticHandler);

            new UserRouter(vertx, authProvider, router);
            new GroupRouter(vertx, authProvider, router);
            new ResourceRouter(vertx, authProvider, router);

            int port = config().getInteger(ObjectKeys.HTTP_PORT);
            server.requestHandler(router::accept).listen(port);
            logger.info("Auth server running on port: " + port);

            startFuture.complete();
        } else {
            startFuture.fail(h.cause());
        }
    };
}

From source file:io.flowly.auth.router.CrudRouter.java

License:Open Source License

public CrudRouter(Vertx vertx, JWTAuth authProvider, Router router, String basePath) {
    super(router, vertx.eventBus());

    this.authProvider = authProvider;

    router.route(HttpMethod.GET, basePath)
            .handler(JWTAuthHandler.create(authProvider).addAuthority(AUTH_API_READ_ACCESS));
    router.route(HttpMethod.POST, basePath)
            .handler(JWTAuthHandler.create(authProvider).addAuthority(AUTH_API_WRITE_ACCESS));
}

From source file:io.flowly.auth.router.GroupRouter.java

License:Open Source License

public GroupRouter(Vertx vertx, JWTAuth authProvider, Router router) {
    super(vertx, authProvider, router, "/group/*");

    prepareSearchRoute("/group/search", LocalAddresses.SEARCH_GROUP, "Unable to search for groups.");
    prepareRoute(HttpMethod.POST, "/group/create", LocalAddresses.CREATE_GROUP, "Unable to create group.",
            false);//ww  w.ja  v  a 2 s .c o  m
    prepareRoute(HttpMethod.POST, "/group/update", LocalAddresses.UPDATE_GROUP, "Unable to update group.",
            false);
    prepareRoute(HttpMethod.GET, "/group/get", LocalAddresses.GET_GROUP, "Unable to get group.", true);
}

From source file:io.flowly.auth.router.ResourceRouter.java

License:Open Source License

public ResourceRouter(Vertx vertx, JWTAuth authProvider, Router router) {
    super(vertx, authProvider, router, "/resource/*");

    prepareSearchRoute("/resource/search", LocalAddresses.SEARCH_RESOURCE, "Unable to search for resources.");
    prepareRoute(HttpMethod.POST, "/resource/create", LocalAddresses.CREATE_RESOURCE,
            "Unable to create resource.", false);
    prepareRoute(HttpMethod.POST, "/resource/update", LocalAddresses.UPDATE_RESOURCE,
            "Unable to update resource.", false);
    prepareRoute(HttpMethod.GET, "/resource/get", LocalAddresses.GET_RESOURCE, "Unable to get resource.", true);
}