use of ratpack.http.MediaType in project ratpack by ratpack.
the class FormDecoder method parseForm.
@SuppressWarnings("deprecation")
public static Form parseForm(Context context, TypedData body, MultiValueMap<String, String> base) throws RuntimeException {
Request request = context.getRequest();
HttpMethod method = io.netty.handler.codec.http.HttpMethod.valueOf(request.getMethod().getName());
HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri());
nettyRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, body.getContentType().toString());
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest);
HttpContent content = new DefaultHttpContent(body.getBuffer());
decoder.offer(content);
decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
Map<String, List<String>> attributes = new LinkedHashMap<>(base.getAll());
Map<String, List<UploadedFile>> files = new LinkedHashMap<>();
try {
InterfaceHttpData data = decoder.next();
while (data != null) {
if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) {
List<String> values = attributes.get(data.getName());
if (values == null) {
values = new ArrayList<>(1);
attributes.put(data.getName(), values);
}
try {
values.add(((Attribute) data).getValue());
} catch (IOException e) {
throw uncheck(e);
} finally {
data.release();
}
} else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) {
List<UploadedFile> values = files.get(data.getName());
if (values == null) {
values = new ArrayList<>(1);
files.put(data.getName(), values);
}
try {
FileUpload nettyFileUpload = (FileUpload) data;
final ByteBuf byteBuf = nettyFileUpload.getByteBuf();
byteBuf.retain();
context.onClose(ro -> byteBuf.release());
MediaType contentType;
String rawContentType = nettyFileUpload.getContentType();
if (rawContentType == null) {
contentType = null;
} else {
Charset charset = nettyFileUpload.getCharset();
if (charset == null) {
contentType = DefaultMediaType.get(rawContentType);
} else {
contentType = DefaultMediaType.get(rawContentType + ";charset=" + charset);
}
}
UploadedFile fileUpload = new DefaultUploadedFile(new ByteBufBackedTypedData(byteBuf, contentType), nettyFileUpload.getFilename());
values.add(fileUpload);
} catch (IOException e) {
throw uncheck(e);
} finally {
data.release();
}
}
data = decoder.next();
}
} catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) {
// ignore
} finally {
decoder.destroy();
}
return new DefaultForm(new ImmutableDelegatingMultiValueMap<>(attributes), new ImmutableDelegatingMultiValueMap<>(files));
}
Aggregations