Example usage for io.vertx.core.http HttpServerRequest bodyHandler

List of usage examples for io.vertx.core.http HttpServerRequest bodyHandler

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerRequest bodyHandler.

Prototype

@Fluent
default HttpServerRequest bodyHandler(@Nullable Handler<Buffer> bodyHandler) 

Source Link

Document

Convenience method for receiving the entire request body in one piece.

Usage

From source file:docoverride.json.Examples.java

License:Open Source License

public void mapToPojo(HttpServerRequest request) {
    request.bodyHandler(buff -> {
        JsonObject jsonObject = buff.toJsonObject();
        User javaObject = jsonObject.mapTo(User.class);
    });// w  w  w.ja  v a  2  s  .  co m
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example11(HttpServerRequest request) {

    request.bodyHandler(totalBuffer -> {
        System.out.println("Full body received, length = " + totalBuffer.length());
    });//from  w  w w. j ava 2  s . c  o m
}

From source file:io.advantageous.qbit.vertx.http.server.HttpServerVertx.java

License:Apache License

private void handleRequestWithBody(HttpServerRequest request) {
    final String contentType = request.headers().get("Content-Type");

    if (HttpContentTypes.isFormContentType(contentType)) {
        request.setExpectMultipart(true);
    }/*ww  w  .jav  a  2  s .  c  o  m*/

    final Buffer[] bufferHolder = new Buffer[1];
    final HttpRequest bodyHttpRequest = vertxUtils.createRequest(request, () -> bufferHolder[0],
            new HashMap<>(), simpleHttpServer.getDecorators(), simpleHttpServer.getHttpResponseCreator());
    if (simpleHttpServer.getShouldContinueReadingRequestBody().test(bodyHttpRequest)) {
        request.bodyHandler((buffer) -> {
            bufferHolder[0] = buffer;
            simpleHttpServer.handleRequest(bodyHttpRequest);
        });
    } else {
        logger.info("Request body rejected {} {}", request.method(), request.absoluteURI());
    }
}

From source file:io.nitor.api.backend.lambda.LambdaHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    final String path = normalizePath(sreq.path(), routeLength);
    if (path == null) {
        ctx.response().setStatusCode(NOT_FOUND.code()).end();
        return;/*from ww  w  . ja  v a  2 s . c o m*/
    }
    HttpServerResponse sres = ctx.response();
    PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path);
    final String lambdaFunction, qualifier;
    if (matchRes == null) {
        logger.error("No matching path template");
        sres.setStatusCode(BAD_GATEWAY.code());
        return;
    } else {
        lambdaFunction = matchRes.getValue().getKey();
        qualifier = matchRes.getValue().getValue();
    }
    sreq.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer event) {
            byte[] body = event.getBytes();
            APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent();
            /*
            * Handle body
            */
            String bodyObjStr = null;
            boolean isBase64Encoded = true;
            if (body != null && body.length > 0) {
                String ct = sreq.getHeader("content-type").toLowerCase();
                if (ct.startsWith("text/") || ct.startsWith("application/json")
                        || (ct.indexOf("charset=") > 0)) {
                    String charset = "utf-8";
                    if (ct.indexOf("charset=") > 0) {
                        charset = getCharsetFromContentType(ct);
                    }
                    try {
                        bodyObjStr = Charset.forName(charset).newDecoder()
                                .onMalformedInput(CodingErrorAction.REPORT)
                                .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body))
                                .toString();
                        isBase64Encoded = false;
                    } catch (CharacterCodingException e) {
                        logger.error("Decoding body failed", e);
                    }
                }
                if (bodyObjStr == null) {
                    bodyObjStr = Base64.getEncoder().encodeToString(body);
                }
                reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded);
            }
            Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey())));
            Map<String, String> headerValue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, Entry::getValue));

            /*
            * Handle request context
            */
            RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx))
                    .withUserAgent(sreq.getHeader(USER_AGENT));
            if (ctx.user() != null) {
                reqId.withUser(ctx.user().principal().toString());
            }
            ProxyRequestContext reqCtx = new ProxyRequestContext()
                    .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString())
                    .withIdentity(reqId);
            reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue)
                    .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path)
                    .withQueryStringParameters(splitQuery(sreq.query()))
                    .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query()))
                    .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx);
            String reqStr = JsonObject.mapFrom(reqObj).toString();
            byte[] sendBody = reqStr.getBytes(UTF_8);
            InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE)
                    .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody))
                    .build();
            logger.info("Calling lambda " + lambdaFunction + ":" + qualifier);
            logger.debug("Payload: " + reqStr);
            CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req);
            respFuture.whenComplete((iresp, err) -> {
                if (iresp != null) {
                    try {
                        String payload = iresp.payload().asString(UTF_8);
                        JsonObject resp = new JsonObject(payload);
                        int statusCode = resp.getInteger("statusCode");
                        sres.setStatusCode(statusCode);
                        for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) {
                            sres.putHeader(next.getKey(), next.getValue().toString());
                        }
                        String respBody = resp.getString("body");
                        byte[] bodyArr = new byte[0];
                        if (body != null && !respBody.isEmpty()) {
                            if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) {
                                bodyArr = Base64.getDecoder().decode(body);
                            } else {
                                bodyArr = respBody.getBytes(UTF_8);
                            }
                        }
                        sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length));
                        Buffer buffer = Buffer.buffer(bodyArr);
                        tryToCacheContent(ctx, buffer);
                        sres.write(buffer);
                    } catch (Throwable t) {
                        logger.error("Error processing lambda request", t);
                        if (!sres.headWritten()) {
                            sres.setStatusCode(BAD_GATEWAY.code());
                            sres.putHeader(CONTENT_TYPE, "application/json");
                            Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString());
                            sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                            sres.write(response);
                        }
                    } finally {
                        sres.end();
                    }
                } else {
                    logger.error("Error processing lambda request", err);
                    sres.setStatusCode(BAD_GATEWAY.code());
                    sres.putHeader(CONTENT_TYPE, "application/json");
                    Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString());
                    sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                    sres.end(response);
                }
            });
        }
    });
}

From source file:io.nonobot.core.handlers.GitHubVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    Router router = Router.router(vertx);
    bot.webRouter().mountSubRouter("/github", router);
    router.post().handler(ctx -> {/*from   ww  w.  java2  s.  com*/
        HttpServerRequest req = ctx.request();
        String event = req.getHeader("X-Github-Event");
        if (!"push".equals(event)) {
            req.response().setStatusCode(400).end("X-Github-Event " + event + " not handled");
            return;
        }
        String contentType = req.getHeader("Content-Type");
        if (!"application/json".equals(contentType)) {
            req.response().setStatusCode(400).end("Content-Type " + contentType + " not handled");
            return;
        }
        req.bodyHandler(body -> {
            JsonObject json = body.toJsonObject();
            req.response().end();
            String chatId = req.getParam("chat");
            JsonArray commits = json.getJsonArray("commits");
            if (chatId != null && commits != null && commits.size() > 0) {
                String commitWord = commits.size() > 1 ? "commits" : "commit";
                bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                        "Got " + commits.size() + " new " + commitWord + " from "
                                + json.getJsonObject("pusher").getString("name") + " on "
                                + json.getJsonObject("repository").getString("full_name"));
                for (int index = 0; index < commits.size(); index++) {
                    JsonObject commit = commits.getJsonObject(index);
                    bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                            "  * " + commit.getString("message") + " " + commit.getString("url"));
                }
            }
        });
    });
}

From source file:org.atmosphere.vertx.AtmosphereCoordinator.java

License:Apache License

/**
 * Route an http request inside the {@link AtmosphereFramework}
 *
 * @param request//from   ww  w. j ava2  s .  com
 */
public AtmosphereCoordinator route(final HttpServerRequest request) {
    boolean async = false;
    try {
        VertxAsyncIOWriter w = new VertxAsyncIOWriter(request);
        final AtmosphereRequest r = AtmosphereUtils.request(request);
        final AtmosphereResponse res = new AtmosphereResponse.Builder().asyncIOWriter(w).writeHeader(false)
                .request(r).build();

        request.response().exceptionHandler(new Handler<Throwable>() {
            @Override
            public void handle(Throwable event) {
                try {
                    logger.debug("exceptionHandler", event);
                    AsynchronousProcessor.class.cast(framework.getAsyncSupport()).cancelled(r, res);
                } catch (IOException e) {
                    logger.debug("", e);
                } catch (ServletException e) {
                    logger.debug("", e);
                }
            }
        });

        if (r.getMethod().equalsIgnoreCase("POST")) {
            async = true;
            request.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer body) {
                    r.body(body.toString());
                    try {
                        route(r, res);
                        request.response().end();
                    } catch (IOException e1) {
                        logger.debug("", e1);
                    }
                }
            });
        }

        if (!async) {
            route(r, res);
        }
    } catch (Throwable e) {
        logger.error("", e);
    }
    return this;
}

From source file:org.entcore.directory.controllers.UserBookController.java

License:Open Source License

@Put("/preference/:application")
@SecuredAction(value = "user.preference", type = ActionType.AUTHENTICATED)
public void updatePreference(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override/* w  w  w. ja v a  2  s  . c om*/
        public void handle(final UserInfos user) {
            if (user != null) {
                final JsonObject params = new JsonObject().put("userId", user.getUserId());
                final String application = request.params().get("application").replaceAll("\\W+", "");
                request.bodyHandler(new Handler<Buffer>() {
                    @Override
                    public void handle(Buffer body) {
                        params.put("conf", body.toString("UTF-8"));
                        String query = "MATCH (u:User {id:{userId}})"
                                + "MERGE (u)-[:PREFERS]->(uac:UserAppConf)" + " ON CREATE SET uac."
                                + application + " = {conf}" + " ON MATCH SET uac." + application + " = {conf}";
                        neo.execute(query, params,
                                validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                                    @Override
                                    public void handle(Either<String, JsonObject> result) {
                                        if (result.isRight()) {
                                            renderJson(request, result.right().getValue());

                                            UserUtils.getSession(eb, request, new Handler<JsonObject>() {
                                                public void handle(JsonObject session) {
                                                    final JsonObject cache = session.getJsonObject("cache");

                                                    if (cache.containsKey("preferences")) {
                                                        JsonObject prefs = cache.getJsonObject("preferences");
                                                        prefs.put(application, params.getString("conf"));
                                                        if ("theme".equals(application)) {
                                                            prefs.remove(THEME_ATTRIBUTE + getHost(request));
                                                        }
                                                        UserUtils.addSessionAttribute(eb, user.getUserId(),
                                                                "preferences", prefs, new Handler<Boolean>() {
                                                                    public void handle(Boolean event) {
                                                                        UserUtils.removeSessionAttribute(eb,
                                                                                user.getUserId(),
                                                                                THEME_ATTRIBUTE
                                                                                        + getHost(request),
                                                                                null);
                                                                        if (!event)
                                                                            log.error(
                                                                                    "Could not add preferences attribute to session.");
                                                                    }
                                                                });
                                                    }
                                                }
                                            });
                                        } else {
                                            leftToResponse(request, result.left());
                                        }
                                    }
                                }));
                    }
                });
            } else {
                badRequest(request);
            }
        }
    });
}