final String contentType = request.getHeader("content-type");
final boolean isJSON = contentType != null && contentType.contains("application/json");
final boolean isMULTIPART = contentType != null && contentType.contains("multipart/form-data");
final boolean isURLENCODEC = contentType != null && contentType.contains("application/x-www-form-urlencoded");
final Buffer buffer = (!isMULTIPART && !isURLENCODEC) ? new Buffer(0) : null;
// enable the parsing at Vert.x level
request.expectMultiPart(true);
if (isMULTIPART) {
request.uploadHandler(new Handler<HttpServerFileUpload>() {
@Override
public void handle(final HttpServerFileUpload fileUpload) {
if (request.files() == null) {
request.setFiles(new HashMap<String, YokeFileUpload>());
}
final YokeFileUpload upload = new YokeFileUpload(vertx(), fileUpload, uploadDir);
// setup callbacks
fileUpload.exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable throwable) {
next.handle(throwable);
}
});
// stream to the generated path
fileUpload.streamToFileSystem(upload.path());
// store a reference in the request
request.files().put(fileUpload.name(), upload);
// set up a callback to remove the file from the file system when the request completes
request.response().endHandler(new Handler<Void>() {
@Override
public void handle(Void event) {
if (upload.isTransient()) {
upload.delete();
}
}
});
}
});
}
request.dataHandler(new Handler<Buffer>() {
long size = 0;
final long limit = request.bodyLengthLimit();
@Override
public void handle(Buffer event) {
if (limit != -1) {
size += event.length();
if (size < limit) {
if (!isMULTIPART && !isURLENCODEC) {
buffer.appendBuffer(event);
}
} else {
request.dataHandler(null);
request.endHandler(null);
request.put("canceled", true);
next.handle(413);
}
} else {
if (!isMULTIPART && !isURLENCODEC) {
buffer.appendBuffer(event);
}
}
}
});
request.endHandler(new Handler<Void>() {
@Override
public void handle(Void _void) {
if (isJSON) {
if (buffer != null && buffer.length() > 0) {
try {
String content = buffer.toString();
request.setBody(JSON.decode(content));
} catch (DecodeException e) {
next.handle(400);
return;
}
if (!request.get("canceled", false)) {
next.handle(null);
}
} else if (buffer != null && buffer.length() == 0) {
// special case for IE and Safari than even for 0 content length, send content type header
if (request.contentLength() == 0) {
request.setBody(null);
if (!request.get("canceled", false)) {