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:Console.java

@Override
public void start(Future<Void> fut) {
    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);
    //        router.route("/static/*").handler(StaticHandler.
    //                create()
    //                .setWebRoot("C:/Users/User/Documents/bekUP/ArduinoOnlineIDE/resources")
    //                .setCachingEnabled(false)
    //                .setAllowRootFileSystemAccess(true)
    //                .setDirectoryListing(true)
    //                .setMaxAgeSeconds(1000)
    //        );/*w  w  w  . j ava  2 s .  co m*/
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("X-PINGARUNER").allowedHeader("Content-Type"));

    DbHelper.getInstance().init(vertx);
    FileAccess.getInstance().init(vertx);

    router.get("/project/openProject/:projectId").handler(this::handleOpenProject);
    router.get("/project/loadFile/:projectId/:fileId").handler(this::handleLoadFile);

    router.post("/project/create").handler(this::handleCreateProject);
    router.post("/project/saveFile/:projectId/:fileId").handler(this::handleSaveFile);
    router.get("/project/getListProject").handler(this::handleGetListProject);
    router.post("/project/updateProjectConfig/:fileId").handler(this::testing);
    router.get("/project/downloadHex/:projectId").handler(this::testing);

    router.get("/project/createFile/:projectId/:directory/:fileName").handler(this::handleCreateFile);
    router.get("/project/createFolder/:projectId/:directory/:folderName").handler(this::handleCreateFolder);

    server.requestHandler(router::accept).listen(8080);

}

From source file:binders.BaseTestBinder.java

License:Apache License

protected void assertBinder(boolean isPost, Type binderType, BindingInfo bindingInfo,
        Map<String, Collection<String>> values, Object[] expectedResults) throws Exception {
    router.clear();//w  w  w  .  ja  va 2  s .co m
    router.route().handler(context -> {
        if (isPost) {
            context.request().setExpectMultipart(true);
            for (Map.Entry<String, Collection<String>> entry : values.entrySet()) {
                context.request().formAttributes().add(entry.getKey(), entry.getValue());
            }
        } else {
            for (Map.Entry<String, Collection<String>> entry : values.entrySet()) {
                context.request().params().add(entry.getKey(), entry.getValue());
            }
        }
        Binder<?> binder = Binders.instance.getBinderByType(binderType);
        assertTrue(binder != null);
        Object result = binder.bindFromContext(bindingInfo, context);
        if (bindingInfo.defaultValueType() == DefaultValueType.VALUE) {
            assertTrue(result != null);
            assertResult(result, expectedResults);
        } else if (bindingInfo.defaultValueType() == DefaultValueType.NULL) {
            if (expectedResults != null) {
                assertResult(result, expectedResults);
            } else {
                assertTrue(result == null);
            }
        } else if (bindingInfo.defaultValueType() == DefaultValueType.NEW) {
            assertTrue(result != null);
            if (expectedResults != null) {
                assertResult(result, expectedResults);
            }
        }
        context.response().end();
        testComplete();
    });
    if (isPost) {
        testRequest(HttpMethod.POST, "/fake", rc -> {
            rc.putHeader("content-type", "application/x-www-form-urlencoded");
        }, null, 200, "OK", null);
    } else {
        testRequest(HttpMethod.GET, "/fake", 200, "OK");
    }
}

From source file:com.company.vertxstarter.MainVerticle.java

@Override
public void start(Future<Void> fut) {
    // Create a router object.
    Router router = Router.router(vertx);
    //CORS handler
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("Content-Type").allowedHeader("Accept"));

    //default headers
    router.route().handler(ctx -> {/* w  w w . j  a  v  a2s  .  c om*/
        ctx.response().putHeader("Cache-Control", "no-store, no-cache").putHeader("Content-Type",
                "application/json");

        if (StringUtils.isEmpty(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.NO_MEDIA_TYPE);
            return;
        } else if (!"application/json".equalsIgnoreCase(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.UNSUPPORTED_MEDIA_TYPE);
            return;
        }
        ctx.next();
    });

    //error handling
    router.route().failureHandler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        Failure ex;

        if (ctx.failure() instanceof Failure) { //specific error
            ex = (Failure) ctx.failure();
        } else { //general error
            ctx.failure().printStackTrace();
            ex = Failure.INTERNAL_ERROR;
        }
        error.put("message", ex.getMessage());
        response.setStatusCode(ex.getCode()).end(error.encode());
    });
    //default 404 handling
    router.route().last().handler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        error.put("message", Failure.NOT_FOUND.getMessage());
        response.setStatusCode(404).end(error.encode());
    });

    //routes
    Injector injector = Guice.createInjector(new AppInjector());
    router.route(HttpMethod.GET, "/people").handler(injector.getInstance(PersonResource.class)::get);

    // Create the HTTP server and pass the "accept" method to the request handler.
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setCompressionSupported(true);
    vertx.createHttpServer(serverOptions).requestHandler(router::accept)
            .listen(config().getInteger("http.port", 8080), result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
}

From source file:com.ddp.SimpleREST.java

License:Open Source License

@Override
public void start() {

    setUpInitialData();/*ww w .j ava  2 s  .  co m*/

    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().handler(BodyHandler.create());
    router.get("/hierarchy").handler(this::getListHierarchy);
    router.post("/hierarchy").handler(this::postHierarchy);
    router.post("/runner").handler(this::postSparkRunner);

    router.get("/hiveHierarchy").handler(this::getHiveHierarchy);
    router.post("/postJars").handler(BodyHandler.create().setUploadsDirectory(localUploadHome));
    router.post("/postJars").handler(this::postJars);

    router.post("/postScalaFiles").handler(BodyHandler.create().setUploadsDirectory(localUploadHome));
    router.post("/postScalaFiles").handler(this::postScalaFiles);

    router.post("/postSampleFiles").handler(BodyHandler.create().setUploadsDirectory(localUploadHome));
    router.post("/postSampleFiles").handler(this::postSampleFiles);

    router.post("/userFunctionHierarchy").handler(this::postUserFunctionHierarchy);
    router.get("/userFunctionHierarchy").handler(this::getUserFunctionHierarchy);

    router.get("/userFunctionCompile").handler(this::getUserFunctionCompile);

    vertx.createHttpServer().requestHandler(router::accept).listen(httpPort);

    eventBus = getVertx().eventBus();
    eventBus.registerDefaultCodec(BaseRequest.class, new BaseRequestCodec());

}

From source file:com.deblox.server.MockServer.java

License:Apache License

@Override
public void start(Future<Void> startFuture) {
    logger.info("starting with config: " + config().toString());
    Router router = Router.router(vertx);

    try {//from w  ww. j a  va 2  s. c  o  m
        serverConfig = Util.loadConfig(config().getString("serverConfig", "/conf.json")).getJsonObject(
                config().getString("serverVerticle", "com.deblox.solacemonitor.MonitorVerticle"));
        metrics = serverConfig.getJsonObject("config").getJsonObject("metrics");
        logger.info("metrics: " + metrics);
    } catch (IOException e) {
        e.printStackTrace();
    }

    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("Content-Type"));

    router.get("/SEMP").handler(ctx -> {
        logger.debug("mock server taking request");
        ctx.response().setChunked(true);
        ctx.response().write("POST YOUR SEMP REQUESTS HERE");
        ctx.response().end();
    });

    /*
            
    accepts XML posted to /SEMP,
    matches XML against metrics's request string in serverConfig's metrics object
    reads a XML file from resources matching the NAME of the metric e.g. stats
            
     */

    router.post("/SEMP").handler(ctx -> {
        logger.debug("mock server taking request");

        for (Map.Entry<String, String> entry : ctx.request().headers()) {
            logger.debug("Header: " + entry.getKey() + " : " + entry.getValue());
        }

        ctx.request().bodyHandler(body -> {
            logger.debug("Body Handler");
            logger.debug(body.toString());

            logger.debug("Matching metrics:");

            metrics.forEach(e -> {
                logger.debug(e.getKey());

                JsonObject j = (JsonObject) e.getValue();

                try {

                    if (j.getString("request").equals(body.toString())) {
                        logger.debug("MATCHED");

                        ctx.response().setChunked(true);
                        try {
                            ctx.response().sendFile("mock/" + e.getKey() + ".xml");
                        } catch (Exception x) {
                            x.printStackTrace();
                        }

                    }
                } catch (Exception x) {
                    logger.warn("skipping " + j.toString());
                }

                logger.debug(j.getString("request"));

            });

        });

    });

    // the server itself
    vertx.createHttpServer().requestHandler(router::accept).listen(config().getInteger("port", 8081));

    // send back deployment complete
    startFuture.complete();
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClient.java

License:Apache License

@Override
public <T> RestClientRequest<T> get(String uri, Class<T> responseClass,
        Handler<RestClientResponse<T>> responseHandler) {
    return handleRequest(HttpMethod.GET, uri, responseClass, responseHandler);
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

License:Apache License

private void endRequest() {
    copyHeadersToHttpClientRequest();/*from   ww w.j a va2s  .  c o  m*/
    writeContentLength();
    cacheKey = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody());

    evictBefore(cacheKey);
    evictAllBefore();

    log.debug("Calling uri: {} {}", method, uri);
    if (HttpMethod.GET.equals(method) && requestCacheOptions != null) {
        try {
            if (isEvicting(requestCacheOptions)) {
                log.debug("Cache MISS. Proceeding with request for key {}", cacheKey);
                finishRequest(Optional.of(cacheKey));
            } else {
                final RestClientResponse cachedRestClientResponse = restClient.getRequestCache().get(cacheKey);
                if (cachedRestClientResponse != null) {
                    log.debug("Cache HIT. Retrieving entry from cache for key {}", cacheKey);
                    resetExpires(cacheKey);
                    vertx.runOnContext(aVoid -> {
                        try {
                            responseHandler.handle(cachedRestClientResponse);
                        } catch (Throwable t) {
                            log.error("Failed invoking rest handler", t);
                            if (exceptionHandler != null) {
                                exceptionHandler.handle(t);
                            } else {
                                throw t;
                            }
                        }
                    });
                } else if (restClient.getRunningRequests().containsKey(cacheKey)
                        && !restClient.getRunningRequests().get(cacheKey).isEmpty()) {
                    log.debug("Cache FUTURE HIT for key {}", cacheKey);
                    restClient.getRunningRequests().put(cacheKey, this);
                } else {
                    log.debug("Cache MISS. Proceeding with request for key {}", cacheKey);
                    finishRequest(Optional.of(cacheKey));
                }
            }
        } catch (Throwable t) {
            log.error("Failed invoking rest handler", t);
            if (exceptionHandler != null) {
                exceptionHandler.handle(t);
            } else {
                throw t;
            }
        }
    } else {
        finishRequest(Optional.empty());
    }
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

License:Apache License

private void handleResponse(RestClientResponse<T> restClientResponse) {
    if (HttpMethod.GET.equals(method) && requestCacheOptions != null) {
        final RestClientRequestSlice<T> restClientRequestSlice = getRestClientRequestSlice();

        if (restClientRequestSlice.isLastFiredRestClientRequest()) {
            cache(restClientResponse);//from w ww.jav a2 s  .c  o  m
        }

        for (DefaultRestClientRequest<T> entry : restClientRequestSlice.getRestClientRequestSlice()) {
            vertx.runOnContext(aVoid -> {
                try {
                    log.debug("Handling FUTURE HIT for key {} and restClientRequest {}", cacheKey, entry);
                    entry.responseHandler.handle(restClientResponse);
                } catch (Throwable t) {
                    log.error("Failed invoking rest handler", t);
                    if (entry.exceptionHandler != null) {
                        entry.exceptionHandler.handle(t);
                    } else {
                        throw t;
                    }
                }
            });
        }
        restClient.getRunningRequests().get(cacheKey)
                .removeAll(restClientRequestSlice.getRestClientRequestSlice());
    } else {
        try {
            responseHandler.handle(restClientResponse);
        } catch (Throwable t) {
            log.error("Failed invoking rest handler", t);
            if (exceptionHandler != null) {
                exceptionHandler.handle(t);
            } else {
                throw t;
            }
        }
    }
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

License:Apache License

private void handleException(RuntimeException exception) {
    if (HttpMethod.GET.equals(method) && requestCacheOptions != null) {
        final RestClientRequestSlice<T> restClientRequestSlice = getRestClientRequestSlice();
        for (DefaultRestClientRequest<T> entry : restClientRequestSlice.getRestClientRequestSlice()) {
            vertx.runOnContext(aVoid -> {
                if (entry.exceptionHandler != null) {
                    log.error("Http error. Handling exception", exception);
                    entry.exceptionHandler.handle(exception);
                } else {
                    throw exception;
                }/*  w w  w. j a v a2s .co  m*/
            });
        }
        restClient.getRunningRequests().get(cacheKey)
                .removeAll(restClientRequestSlice.getRestClientRequestSlice());
    } else {
        if (exceptionHandler != null) {
            log.error("Http error. Handling exception", exception);
            exceptionHandler.handle(exception);
        } else {
            throw exception;
        }
    }
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

License:Apache License

private void cache(RestClientResponse restClientResponse) {
    if (HttpMethod.GET.equals(method) && requestCacheOptions != null
            && requestCacheOptions.getCachedStatusCodes().contains(restClientResponse.statusCode())) {
        log.debug("Caching entry with key {}", cacheKey);

        cancelOutstandingEvictionTimer(cacheKey);
        restClient.getRequestCache().put(cacheKey, restClientResponse);
        createEvictionTimer(cacheKey, requestCacheOptions.getExpiresAfterWriteMillis());
    }/*from   w w w. j  ava  2 s. com*/
}