Example usage for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder

List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder.

Prototype

public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) 

Source Link

Usage

From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java

License:Apache License

public HttpPostRequestDecoder getHttpPostRequestDecoder() {
    if (!httpPostRequestDecoderInit) {
        HttpMethod method = getMethod();
        if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
            try {
                httpPostRequestDecoder = new HttpPostRequestDecoder(factory, this, charset4ContentDecoder);
            } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
                log.error("request postDataDecode error:{}", this, e);
            } catch (HttpPostRequestDecoder.IncompatibleDataDecoderException e) {
            }//w w  w  .ja v  a 2 s  .c o  m
        }
        httpPostRequestDecoderInit = true;
    }
    return httpPostRequestDecoder;
}

From source file:io.syncframework.netty.RequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        this.request = (HttpRequest) msg;

        ////from w w w.j a  v a 2 s  .co  m
        // Verify application's domain. This is a common code to both static and dynamic request handlers... 
        // This may save CPU cycles if there is no domain responsible for the request.
        //
        domain = getDomain(request);
        application = ApplicationManager.getApplication(domain);
        if (application == null) {
            if (log.isTraceEnabled())
                log.trace("no application found responsible for domain: {}", domain);
            sendFileNotFound(ctx);
            return;
        }

        // check if GET or POST ... 
        // if GET it is possible that we may handle a static file request. 
        // In this case we don't need to create Request/Response wrappers objects...
        boolean isGET = this.request.method().equals(HttpMethod.GET);
        if (isGET) {
            boolean xsc = false;
            if (server.config().getTrustedProxyMode()) {
                xsc = this.request.headers().getAsString("X-SAS-Client") != null ? true : false;
            }
            if (log.isTraceEnabled())
                log.trace("Proxied request? {}", xsc);
            if (xsc) {
                // this point forward we translate the request into sas.Request...
                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());
                requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS,
                        this.request.headers().getAsString("X-SAS-Client"));

                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the action has been taken by the application
                    return;
                }
            } else {
                if (handleRequestStatically(ctx)) {
                    // no need to continue as the static file has been served
                    return;
                }

                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());
                // We already verified the X-SAS-Client header and it is not available...
                InetSocketAddress isa = (InetSocketAddress) ctx.channel().remoteAddress();
                requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS, isa.getHostString());

                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the page has been delivered
                    return;
                }
            }

            sendFileNotFound(ctx);
            return;
        }

        // treating POST requests...
        // posts may come with multiples reads... chunks or multipart...
        // utilize auxiliary requestWrapper.
        try {
            decoder = new HttpPostRequestDecoder(factory, request, HttpConstants.DEFAULT_CHARSET);
        } catch (ErrorDataDecoderException e1) {
            // e1.printStackTrace();
            log.error("failed to decode HTTP post request", e1);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            ctx.channel().close();
            return;
        }
    }

    if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (Exception e) {
                log.error("failed to decode HTTP post request", e);
                sendError(ctx, HttpResponseStatus.BAD_REQUEST);
                ctx.channel().close();
                return;
            }

            try {
                readHttpDataChunkByChunk();
            } catch (Exception e) {
                sendException(ctx, e);
                return;
            }

            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                if (log.isTraceEnabled())
                    log.trace("last http request chunk identified; handling request...");

                // this point forward we translate the request into sas.Request...
                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());

                boolean xsc = false;
                if (server.config().getTrustedProxyMode()) {
                    xsc = this.request.headers().getAsString("X-SAS-Client") != null ? true : false;
                }
                if (log.isTraceEnabled())
                    log.trace("Proxied request? {}", xsc);
                if (xsc) {
                    requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS,
                            this.request.headers().getAsString("X-SAS-Client"));
                } else {
                    InetSocketAddress isa = (InetSocketAddress) ctx.channel().remoteAddress();
                    requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS, isa.getHostString());
                }
                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the action has been taken by the application
                    return;
                }
                sendFileNotFound(ctx);
                return;
            }
        }
    } else {
        sendFileNotFound(ctx);
        return;
    }
}

From source file:org.restnext.core.http.RequestImpl.java

License:Apache License

/**
 * Create a new instance./*from  w  w w. java 2 s  .c  o m*/
 *
 * @param context netty channel handler context
 * @param request netty full http request
 */
public RequestImpl(final ChannelHandlerContext context, final FullHttpRequest request) {
    Objects.requireNonNull(request, "request");
    Objects.requireNonNull(context, "context");

    this.charset = HttpUtil.getCharset(request, StandardCharsets.UTF_8);
    this.version = HttpVersion.HTTP_1_0.equals(request.protocolVersion()) ? Version.HTTP_1_0 : Version.HTTP_1_1;
    this.method = Method.valueOf(request.method().name());
    this.uri = URI.create(normalize(request.uri()));
    this.baseUri = createBaseUri(context, request);
    this.keepAlive = HttpUtil.isKeepAlive(request);

    // copy the inbound netty request headers.
    this.headers = new MultivaluedHashMap<>();
    for (Map.Entry<String, String> entry : request.headers()) {
        this.headers.add(entry.getKey().toLowerCase(), entry.getValue());
    }

    this.parameters = new MultivaluedHashMap<>();
    // decode the inbound netty request uri parameters.
    QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri(), charset);
    for (Map.Entry<String, List<String>> entry : queryDecoder.parameters().entrySet()) {
        this.parameters.addAll(entry.getKey(), entry.getValue());
    }

    // decode the inbound netty request body parameters.
    if (Method.POST.equals(method)) {
        CharSequence charSequence = HttpUtil.getMimeType(request);
        AsciiString mimeType = charSequence != null ? AsciiString.of(charSequence) : AsciiString.EMPTY_STRING;
        boolean isFormData = mimeType.contains(HttpHeaderValues.FORM_DATA);

        if (isFormData) {
            // decode the inbound netty request body multipart/form-data parameters.
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(), request,
                    charset);
            try {
                for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
                    InterfaceHttpData.HttpDataType type = data.getHttpDataType();
                    switch (type) {
                    case Attribute: {
                        try {
                            Attribute attribute = (Attribute) data;
                            this.parameters.add(attribute.getName(), attribute.getValue());
                        } catch (IOException ignore) {
                            LOGGER.warn("Could not get attribute value");
                        }
                        break;
                    }
                    case FileUpload:
                        break;
                    case InternalAttribute:
                        break;
                    default: //nop
                    }
                }
            } finally {
                decoder.destroy();
            }
        } else {
            // decode the inbound netty request body raw | form-url-encoded | octet-stream parameters.
            this.content = request.content().hasArray() ? request.content().array()
                    : request.content().toString(charset).getBytes();
        }
    }
}