Example usage for io.netty.handler.codec.http HttpHeaderValues FORM_DATA

List of usage examples for io.netty.handler.codec.http HttpHeaderValues FORM_DATA

Introduction

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

Prototype

AsciiString FORM_DATA

To view the source code for io.netty.handler.codec.http HttpHeaderValues FORM_DATA.

Click Source Link

Document

"form-data" See HttpHeaderNames#CONTENT_DISPOSITION

Usage

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

License:Apache License

/**
 * Create a new instance./*from   ww w .  j  av  a  2 s  .c om*/
 *
 * @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();
        }
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java

License:Open Source License

/**
 * Add the InterfaceHttpData to the Body list
 *
 * @throws NullPointerException      for data
 * @throws ErrorDataEncoderException if the encoding is in error or if the finalize
 *                                   were already done
 *//*from www  .  j av  a  2 s  . c o m*/
void addBodyHttpData(InterfaceHttpData data) throws ErrorDataEncoderException {
    if (headerFinalized) {
        throw new ErrorDataEncoderException("Cannot add value once finalized");
    }
    if (data == null) {
        throw new NullPointerException("data");
    }
    bodyListDatas.add(data);
    if (!isMultipart) {
        if (data instanceof Attribute) {
            Attribute attribute = (Attribute) data;
            try {
                // name=value& with encoded name and attribute
                String key = encodeAttribute(attribute.getName(), charset);
                String value = encodeAttribute(attribute.getValue(), charset);
                Attribute newattribute = factory.createAttribute(request, key, value);
                multipartHttpDatas.add(newattribute);
                globalBodySize += newattribute.getName().length() + 1 + newattribute.length() + 1;
            } catch (IOException e) {
                throw new ErrorDataEncoderException(e);
            }
        } else if (data instanceof FileUpload) {
            // since not Multipart, only name=filename => Attribute
            FileUpload fileUpload = (FileUpload) data;
            // name=filename& with encoded name and filename
            String key = encodeAttribute(fileUpload.getName(), charset);
            String value = encodeAttribute(fileUpload.getFilename(), charset);
            Attribute newattribute = factory.createAttribute(request, key, value);
            multipartHttpDatas.add(newattribute);
            globalBodySize += newattribute.getName().length() + 1 + newattribute.length() + 1;
        }
        return;
    }
    /*
     * Logic:
       * if not Attribute:
       *      add Data to body list
       *      if (duringMixedMode)
       *          add endmixedmultipart delimiter
       *          currentFileUpload = null
       *          duringMixedMode = false;
       *      add multipart delimiter, multipart body header and Data to multipart list
       *      reset currentFileUpload, duringMixedMode
       * if FileUpload: take care of multiple file for one field => mixed mode
       *      if (duringMixeMode)
       *          if (currentFileUpload.name == data.name)
       *              add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
       *          else
       *              add endmixedmultipart delimiter, multipart body header and Data to multipart list
       *              currentFileUpload = data
       *              duringMixedMode = false;
       *      else
       *          if (currentFileUpload.name == data.name)
       *              change multipart body header of previous file into multipart list to
       *                      mixedmultipart start, mixedmultipart body header
       *              add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
       *              duringMixedMode = true
       *          else
       *              add multipart delimiter, multipart body header and Data to multipart list
       *              currentFileUpload = data
       *              duringMixedMode = false;
       * Do not add last delimiter! Could be:
       * if duringmixedmode: endmixedmultipart + endmultipart
       * else only endmultipart
       */
    if (data instanceof Attribute) {
        if (duringMixedMode) {
            InternalAttribute internal = new InternalAttribute(charset);
            internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
        }
        InternalAttribute internal = new InternalAttribute(charset);
        if (!multipartHttpDatas.isEmpty()) {
            // previously a data field so CRLF
            internal.addValue("\r\n");
        }
        internal.addValue("--" + multipartDataBoundary + "\r\n");
        // content-disposition: form-data; name="field1"
        Attribute attribute = (Attribute) data;
        internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
                + HttpHeaderValues.NAME + "=\"" + attribute.getName() + "\"\r\n");
        // Add Content-Length: xxx
        internal.addValue(HttpHeaderNames.CONTENT_LENGTH + ": " + attribute.length() + "\r\n");
        Charset localcharset = attribute.getCharset();
        if (localcharset != null) {
            // Content-Type: text/plain; charset=charset
            internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " + DEFAULT_TEXT_CONTENT_TYPE + "; "
                    + HttpHeaderValues.CHARSET + '=' + localcharset.name() + "\r\n");
        }
        // CRLF between body header and data
        internal.addValue("\r\n");
        multipartHttpDatas.add(internal);
        multipartHttpDatas.add(data);
        globalBodySize += attribute.length() + internal.size();
    } else if (data instanceof FileUpload) {
        FileUpload fileUpload = (FileUpload) data;
        InternalAttribute internal = new InternalAttribute(charset);
        if (!multipartHttpDatas.isEmpty()) {
            // previously a data field so CRLF
            internal.addValue("\r\n");
        }
        boolean localMixed;
        if (duringMixedMode) {
            if (currentFileUpload != null && currentFileUpload.getName().equals(fileUpload.getName())) {
                // continue a mixed mode

                localMixed = true;
            } else {
                // end a mixed mode

                // add endmixedmultipart delimiter, multipart body header
                // and
                // Data to multipart list
                internal.addValue("--" + multipartMixedBoundary + "--");
                multipartHttpDatas.add(internal);
                multipartMixedBoundary = null;
                // start a new one (could be replaced if mixed start again
                // from here
                internal = new InternalAttribute(charset);
                internal.addValue("\r\n");
                localMixed = false;
                // new currentFileUpload and no more in Mixed mode
                currentFileUpload = fileUpload;
                duringMixedMode = false;
            }
        } else {
            if (encoderMode != EncoderMode.HTML5 && currentFileUpload != null
                    && currentFileUpload.getName().equals(fileUpload.getName())) {
                // create a new mixed mode (from previous file)

                // change multipart body header of previous file into
                // multipart list to
                // mixedmultipart start, mixedmultipart body header

                // change Internal (size()-2 position in multipartHttpDatas)
                // from (line starting with *)
                // --AaB03x
                // * Content-Disposition: form-data; name="files";
                // filename="file1.txt"
                // Content-Type: text/plain
                // to (lines starting with *)
                // --AaB03x
                // * Content-Disposition: form-data; name="files"
                // * Content-Type: multipart/mixed; boundary=BbC04y
                // *
                // * --BbC04y
                // * Content-Disposition: attachment; filename="file1.txt"
                // Content-Type: text/plain
                initMixedMultipart();
                InternalAttribute pastAttribute = (InternalAttribute) multipartHttpDatas
                        .get(multipartHttpDatas.size() - 2);
                // remove past size
                globalBodySize -= pastAttribute.size();
                StringBuilder replacement = new StringBuilder(
                        139 + multipartDataBoundary.length() + multipartMixedBoundary.length() * 2
                                + fileUpload.getFilename().length() + fileUpload.getName().length())

                                        .append("--").append(multipartDataBoundary).append("\r\n")

                                        .append(HttpHeaderNames.CONTENT_DISPOSITION).append(": ")
                                        .append(HttpHeaderValues.FORM_DATA).append("; ")
                                        .append(HttpHeaderValues.NAME).append("=\"")
                                        .append(fileUpload.getName()).append("\"\r\n")

                                        .append(HttpHeaderNames.CONTENT_TYPE).append(": ")
                                        .append(HttpHeaderValues.MULTIPART_MIXED).append("; ")
                                        .append(HttpHeaderValues.BOUNDARY).append('=')
                                        .append(multipartMixedBoundary).append("\r\n\r\n")

                                        .append("--").append(multipartMixedBoundary).append("\r\n")

                                        .append(HttpHeaderNames.CONTENT_DISPOSITION).append(": ")
                                        .append(HttpHeaderValues.ATTACHMENT).append("; ");

                if (!fileUpload.getFilename().isEmpty()) {
                    replacement.append(HttpHeaderValues.FILENAME).append("=\"")
                            .append(fileUpload.getFilename());
                }

                replacement.append("\"\r\n");

                pastAttribute.setValue(replacement.toString(), 1);
                pastAttribute.setValue("", 2);

                // update past size
                globalBodySize += pastAttribute.size();

                // now continue
                // add mixedmultipart delimiter, mixedmultipart body header
                // and
                // Data to multipart list
                localMixed = true;
                duringMixedMode = true;
            } else {
                // a simple new multipart
                // add multipart delimiter, multipart body header and Data
                // to multipart list
                localMixed = false;
                currentFileUpload = fileUpload;
                duringMixedMode = false;
            }
        }

        if (localMixed) {
            // add mixedmultipart delimiter, mixedmultipart body header and
            // Data to multipart list
            internal.addValue("--" + multipartMixedBoundary + "\r\n");
            // Content-Disposition: attachment; filename="file1.txt"
            if (!fileUpload.getFilename().isEmpty()) {
                internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.ATTACHMENT
                        + "; " + HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
            } else {
                internal.addValue(
                        HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.ATTACHMENT + ";\r\n");
            }
        } else {
            internal.addValue("--" + multipartDataBoundary + "\r\n");
            // Content-Disposition: form-data; name="files";
            // filename="file1.txt"
            if (!fileUpload.getFilename().isEmpty()) {
                internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
                        + HttpHeaderValues.NAME + "=\"" + fileUpload.getName() + "\"; "
                        + HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
            } else {
                internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
                        + HttpHeaderValues.NAME + "=\"" + fileUpload.getName() + "\";\r\n");
            }
        }
        // Add Content-Length: xxx
        internal.addValue(HttpHeaderNames.CONTENT_LENGTH + ": " + fileUpload.length() + "\r\n");
        // Content-Type: image/gif
        // Content-Type: text/plain; charset=ISO-8859-1
        // Content-Transfer-Encoding: binary
        internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " + fileUpload.getContentType());
        String contentTransferEncoding = fileUpload.getContentTransferEncoding();
        if (contentTransferEncoding != null && contentTransferEncoding.equals(DEFAULT_TRANSFER_ENCODING)) {
            internal.addValue("\r\n" + HttpHeaderNames.CONTENT_TRANSFER_ENCODING + ": "
                    + DEFAULT_BINARY_CONTENT_TYPE + "\r\n\r\n");
        } else if (fileUpload.getCharset() != null) {
            internal.addValue(
                    "; " + HttpHeaderValues.CHARSET + '=' + fileUpload.getCharset().name() + "\r\n\r\n");
        } else {
            internal.addValue("\r\n\r\n");
        }
        multipartHttpDatas.add(internal);
        multipartHttpDatas.add(data);
        globalBodySize += fileUpload.length() + internal.size();
    }
}