com.jetdrone.vertx.yoke.middleware.BodyParser Maven / Gradle / Ivy
/**
* Copyright 2011-2014 the original author or authors.
*/
package com.jetdrone.vertx.yoke.middleware;
import com.jetdrone.vertx.yoke.Middleware;
import com.jetdrone.vertx.yoke.core.JSON;
import com.jetdrone.vertx.yoke.core.YokeFileUpload;
import org.jetbrains.annotations.NotNull;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServerFileUpload;
import org.vertx.java.core.json.DecodeException;
import java.util.HashMap;
/** # BodyParser
*
* Parse request bodies, supports *application/json*, *application/x-www-form-urlencoded*, and *multipart/form-data*.
*
* Once data has been parsed the result is visible in the field `body` of the request.
*
* If the content type was *multipart/form-data* and there were uploaded files the files are ```files()``` returns
* `Map<String, HttpServerFileUpload>`.
*
* ### Limitations
*
* Currently when parsing *multipart/form-data* if there are several files uploaded under the same name, only the last
* is preserved.
*/
public class BodyParser extends Middleware {
/**
* Location on the file system to store the uploaded files.
*/
private final String uploadDir;
/** Instantiates a Body parser with a configurable upload directory.
*
*
* Yoke yoke = new Yoke(...);
* yoke.use(new BodyParser("/upload"));
*
*
* @param uploadDir upload directory path
*/
public BodyParser(@NotNull String uploadDir) {
this.uploadDir = uploadDir;
}
/** Instantiates a Body parser using the system default temp directory.
*
*
* Yoke yoke = new Yoke(...);
* yoke.use(new BodyParser());
*
*/
public BodyParser() {
this(System.getProperty("java.io.tmpdir"));
}
/** Handler for the parser. When the request method is GET or HEAD this is a Noop middleware.
* If not the middleware verifies if there is a body and according to its headers tries to
* parse it as JSON, form data or multi part upload.
*
* @param request http yoke request
* @param next middleware to be called next
*/
@Override
public void handle(@NotNull final YokeRequest request, @NotNull final Handler