Search in sources :

Example 11 with Attribute

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute 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"));
}
Also used : Path(java.nio.file.Path) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Attribute(io.netty.handler.codec.http.multipart.Attribute) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) IOException(java.io.IOException) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)

Example 12 with Attribute

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute 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);
                }
            } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                List<UploadedFile> values = files.computeIfAbsent(data.getName(), k -> new ArrayList<>(1));
                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);
                }
            }
            data = decoder.next();
        }
    } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) {
    // ignore
    } finally {
        decoder.destroy();
    }
    return new DefaultForm(new ImmutableDelegatingMultiValueMap<>(attributes), new ImmutableDelegatingMultiValueMap<>(files));
}
Also used : Context(ratpack.handling.Context) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) MultiValueMap(ratpack.util.MultiValueMap) Form(ratpack.form.Form) ImmutableDelegatingMultiValueMap(ratpack.util.internal.ImmutableDelegatingMultiValueMap) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) DefaultMediaType(ratpack.http.internal.DefaultMediaType) IOException(java.io.IOException) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) UploadedFile(ratpack.form.UploadedFile) ArrayList(java.util.ArrayList) TypedData(ratpack.http.TypedData) LinkedHashMap(java.util.LinkedHashMap) Attribute(io.netty.handler.codec.http.multipart.Attribute) io.netty.handler.codec.http(io.netty.handler.codec.http) Request(ratpack.http.Request) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) MediaType(ratpack.http.MediaType) ByteBufBackedTypedData(ratpack.http.internal.ByteBufBackedTypedData) Map(java.util.Map) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) LinkedHashMap(java.util.LinkedHashMap) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) DefaultMediaType(ratpack.http.internal.DefaultMediaType) MediaType(ratpack.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) ByteBufBackedTypedData(ratpack.http.internal.ByteBufBackedTypedData) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) Request(ratpack.http.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) UploadedFile(ratpack.form.UploadedFile)

Example 13 with Attribute

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute in project flink by apache.

the class FileUploadHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final HttpObject msg) throws Exception {
    try {
        if (msg instanceof HttpRequest) {
            final HttpRequest httpRequest = (HttpRequest) msg;
            LOG.trace("Received request. URL:{} Method:{}", httpRequest.getUri(), httpRequest.getMethod());
            if (httpRequest.getMethod().equals(HttpMethod.POST)) {
                if (HttpPostRequestDecoder.isMultipart(httpRequest)) {
                    LOG.trace("Initializing multipart file upload.");
                    checkState(currentHttpPostRequestDecoder == null);
                    checkState(currentHttpRequest == null);
                    checkState(currentUploadDir == null);
                    currentHttpPostRequestDecoder = new HttpPostRequestDecoder(DATA_FACTORY, httpRequest);
                    currentHttpRequest = ReferenceCountUtil.retain(httpRequest);
                    // make sure that we still have a upload dir in case that it got deleted in
                    // the meanwhile
                    RestServerEndpoint.createUploadDir(uploadDir, LOG, false);
                    currentUploadDir = Files.createDirectory(uploadDir.resolve(UUID.randomUUID().toString()));
                } else {
                    ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
                }
            } else {
                ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
            }
        } else if (msg instanceof HttpContent && currentHttpPostRequestDecoder != null) {
            LOG.trace("Received http content.");
            // make sure that we still have a upload dir in case that it got deleted in the
            // meanwhile
            RestServerEndpoint.createUploadDir(uploadDir, LOG, false);
            final HttpContent httpContent = (HttpContent) msg;
            currentHttpPostRequestDecoder.offer(httpContent);
            while (httpContent != LastHttpContent.EMPTY_LAST_CONTENT && currentHttpPostRequestDecoder.hasNext()) {
                final InterfaceHttpData data = currentHttpPostRequestDecoder.next();
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
                    final DiskFileUpload fileUpload = (DiskFileUpload) data;
                    checkState(fileUpload.isCompleted());
                    // wrapping around another File instantiation is a simple way to remove any
                    // path information - we're
                    // solely interested in the filename
                    final Path dest = currentUploadDir.resolve(new File(fileUpload.getFilename()).getName());
                    fileUpload.renameTo(dest.toFile());
                    LOG.trace("Upload of file {} into destination {} complete.", fileUpload.getFilename(), dest.toString());
                } else if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    final Attribute request = (Attribute) data;
                    // this could also be implemented by using the first found Attribute as the
                    // payload
                    LOG.trace("Upload of attribute {} complete.", request.getName());
                    if (data.getName().equals(HTTP_ATTRIBUTE_REQUEST)) {
                        currentJsonPayload = request.get();
                    } else {
                        handleError(ctx, "Received unknown attribute " + data.getName() + '.', HttpResponseStatus.BAD_REQUEST, null);
                        return;
                    }
                }
            }
            if (httpContent instanceof LastHttpContent) {
                LOG.trace("Finalizing multipart file upload.");
                ctx.channel().attr(UPLOADED_FILES).set(new FileUploads(currentUploadDir));
                if (currentJsonPayload != null) {
                    currentHttpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, currentJsonPayload.length);
                    currentHttpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);
                    ctx.fireChannelRead(currentHttpRequest);
                    ctx.fireChannelRead(httpContent.replace(Unpooled.wrappedBuffer(currentJsonPayload)));
                } else {
                    currentHttpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
                    currentHttpRequest.headers().remove(HttpHeaders.Names.CONTENT_TYPE);
                    ctx.fireChannelRead(currentHttpRequest);
                    ctx.fireChannelRead(LastHttpContent.EMPTY_LAST_CONTENT);
                }
                reset();
            }
        } else {
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    } catch (Exception e) {
        handleError(ctx, "File upload failed.", HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) Path(java.nio.file.Path) FileUploads(org.apache.flink.runtime.rest.handler.FileUploads) DiskFileUpload(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DiskFileUpload) Attribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute) DiskAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DiskAttribute) InterfaceHttpData(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.InterfaceHttpData) LastHttpContent(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent) HttpPostRequestDecoder(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) File(java.io.File) LastHttpContent(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent) HttpContent(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent) IOException(java.io.IOException)

Aggregations

Attribute (io.netty.handler.codec.http.multipart.Attribute)10 InterfaceHttpData (io.netty.handler.codec.http.multipart.InterfaceHttpData)9 HttpPostRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)8 IOException (java.io.IOException)8 Path (java.nio.file.Path)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)3 HttpRequest (org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest)3 FileUpload (io.netty.handler.codec.http.multipart.FileUpload)2 StreamResetException (io.vertx.core.http.StreamResetException)2 File (java.io.File)2 URISyntaxException (java.net.URISyntaxException)2 ClosedChannelException (java.nio.channels.ClosedChannelException)2 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)2 DefaultFullHttpRequest (org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest)2 Attribute (org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute)2 CommandContext (com.alibaba.dubbo.qos.command.CommandContext)1 ByteBuf (io.netty.buffer.ByteBuf)1 io.netty.handler.codec.http (io.netty.handler.codec.http)1