Search in sources :

Example 16 with HttpPostRequestDecoder

use of org.apache.flink.shaded.netty4.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 an HttpPostRequestDecoder
        if (HttpMethod.GET.equals(request.method())) {
            // GET Method: should not try to create an 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(), true);
            return;
        }
        boolean 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: ");
        }
    }
    // 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(), true);
                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());
                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) Cookie(io.netty.handler.codec.http.cookie.Cookie) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) URI(java.net.URI) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) List(java.util.List) ErrorDataDecoderException(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 17 with HttpPostRequestDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.HttpPostRequestDecoder 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)

Example 18 with HttpPostRequestDecoder

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

the class HttpRequest method init.

public void init(String remoteAddress) {
    this.remoteAddress = remoteAddress.substring(1);
    this.keepAlive = HttpUtil.isKeepAlive(nettyRequest);
    this.url = nettyRequest.uri();
    int pathEndPos = this.url().indexOf('?');
    this.uri = pathEndPos < 0 ? this.url() : this.url().substring(0, pathEndPos);
    this.protocol = nettyRequest.protocolVersion().text();
    this.method = nettyRequest.method().name();
    String cleanUri = this.uri;
    if (!"/".equals(this.contextPath())) {
        cleanUri = PathKit.cleanPath(cleanUri.replaceFirst(this.contextPath(), "/"));
        this.uri = cleanUri;
    }
    this.httpHeaders = nettyRequest.headers();
    if (!HttpServerHandler.PERFORMANCE) {
        SessionManager sessionManager = WebContext.blade().sessionManager();
        if (null != sessionManager) {
            this.session = SESSION_HANDLER.createSession(this);
        }
    }
    if ("GET".equals(this.method())) {
        return;
    }
    try {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, nettyRequest);
        this.isMultipart = decoder.isMultipart();
        List<ByteBuf> byteBuffs = new ArrayList<>(this.contents.size());
        for (HttpContent content : this.contents) {
            if (!isMultipart) {
                byteBuffs.add(content.content().copy());
            }
            decoder.offer(content);
            this.readHttpDataChunkByChunk(decoder);
            content.release();
        }
        if (!byteBuffs.isEmpty()) {
            this.body = Unpooled.copiedBuffer(byteBuffs.toArray(new ByteBuf[0]));
        }
    } catch (Exception e) {
        throw new HttpParseException("build decoder fail", e);
    }
}
Also used : SessionManager(com.blade.mvc.http.session.SessionManager) ArrayList(java.util.ArrayList) HttpParseException(com.blade.exception.HttpParseException) ByteBuf(io.netty.buffer.ByteBuf) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) HttpParseException(com.blade.exception.HttpParseException) IOException(java.io.IOException)

Aggregations

HttpPostRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)16 IOException (java.io.IOException)9 InterfaceHttpData (io.netty.handler.codec.http.multipart.InterfaceHttpData)7 List (java.util.List)7 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)6 Attribute (io.netty.handler.codec.http.multipart.Attribute)6 ArrayList (java.util.ArrayList)6 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 HttpContent (io.netty.handler.codec.http.HttpContent)4 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)4 URI (java.net.URI)4 ErrorDataDecoderException (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException)3 ByteBuf (io.netty.buffer.ByteBuf)2 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)2 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 HttpMethod (io.netty.handler.codec.http.HttpMethod)2 FileUpload (io.netty.handler.codec.http.multipart.FileUpload)2 IncompatibleDataDecoderException (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.IncompatibleDataDecoderException)2 File (java.io.File)2 Charset (java.nio.charset.Charset)2