use of io.netty.handler.codec.http.multipart.HttpPostRequestDecoder in project netty by netty.
the class HttpUploadServerHandler method channelRead0.
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = this.request = (HttpRequest) msg;
URI uri = new URI(request.uri());
if (!uri.getPath().startsWith("/form")) {
// Write Menu
writeMenu(ctx);
return;
}
responseContent.setLength(0);
responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
responseContent.append("===================================\r\n");
responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");
responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
responseContent.append("\r\n\r\n");
// new getMethod
for (Entry<String, String> entry : request.headers()) {
responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
}
responseContent.append("\r\n\r\n");
// new getMethod
Set<Cookie> cookies;
String value = request.headers().get(HttpHeaderNames.COOKIE);
if (value == null) {
cookies = Collections.emptySet();
} else {
cookies = ServerCookieDecoder.STRICT.decode(value);
}
for (Cookie cookie : cookies) {
responseContent.append("COOKIE: " + cookie + "\r\n");
}
responseContent.append("\r\n\r\n");
QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
Map<String, List<String>> uriAttributes = decoderQuery.parameters();
for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
for (String attrVal : attr.getValue()) {
responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
}
}
responseContent.append("\r\n\r\n");
// if GET Method: should not try to create a HttpPostRequestDecoder
if (request.method().equals(HttpMethod.GET)) {
// GET Method: should not try to create a HttpPostRequestDecoder
// So stop here
responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
// Not now: LastHttpContent will be sent writeResponse(ctx.channel());
return;
}
try {
decoder = new HttpPostRequestDecoder(factory, request);
} catch (ErrorDataDecoderException e1) {
e1.printStackTrace();
responseContent.append(e1.getMessage());
writeResponse(ctx.channel());
ctx.channel().close();
return;
}
readingChunks = HttpUtil.isTransferEncodingChunked(request);
responseContent.append("Is Chunked: " + readingChunks + "\r\n");
responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
if (readingChunks) {
// Chunk version
responseContent.append("Chunks: ");
readingChunks = true;
}
}
// if not it handles the form get
if (decoder != null) {
if (msg instanceof HttpContent) {
// New chunk is received
HttpContent chunk = (HttpContent) msg;
try {
decoder.offer(chunk);
} catch (ErrorDataDecoderException e1) {
e1.printStackTrace();
responseContent.append(e1.getMessage());
writeResponse(ctx.channel());
ctx.channel().close();
return;
}
responseContent.append('o');
// example of reading chunk by chunk (minimize memory usage due to
// Factory)
readHttpDataChunkByChunk();
// example of reading only if at the end
if (chunk instanceof LastHttpContent) {
writeResponse(ctx.channel());
readingChunks = false;
reset();
}
}
} else {
writeResponse(ctx.channel());
}
}
use of io.netty.handler.codec.http.multipart.HttpPostRequestDecoder 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));
}
use of io.netty.handler.codec.http.multipart.HttpPostRequestDecoder in project android by JetBrains.
the class GoogleCrashTest method checkServerReceivesPostedData.
@Ignore
@Test
public void checkServerReceivesPostedData() throws Exception {
String expectedReportId = "deadcafe";
Map<String, String> attributes = new ConcurrentHashMap<>();
myTestServer.setResponseSupplier(httpRequest -> {
if (httpRequest.method() != HttpMethod.POST) {
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
}
HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest);
try {
for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) {
if (httpData instanceof Attribute) {
Attribute attr = (Attribute) httpData;
attributes.put(attr.getName(), attr.getValue());
}
}
} catch (IOException e) {
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
} finally {
requestDecoder.destroy();
}
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8)));
});
CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException).setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
CompletableFuture<String> reportId = myReporter.submit(report);
assertEquals(expectedReportId, reportId.get());
// assert that the server get the expected data
assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID));
assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION));
// Note: the exception message should have been elided
assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE, attributes.get(GoogleCrash.KEY_EXCEPTION_INFO));
List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02");
report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
attributes.clear();
reportId = myReporter.submit(report);
assertEquals(expectedReportId, reportId.get());
// check that the crash count and descriptions made through
assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes")));
assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc"));
Path testData = Paths.get(AndroidTestBase.getTestDataPath());
List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8);
report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build();
attributes.clear();
reportId = myReporter.submit(report);
assertEquals(expectedReportId, reportId.get());
assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt"));
}
Aggregations