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

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

Introduction

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

Prototype

@Override
    public List<InterfaceHttpData> getBodyHttpDatas() 

Source Link

Usage

From source file:org.apache.hyracks.http.server.PostRequest.java

License:Apache License

public static IServletRequest create(FullHttpRequest request) throws IOException {
    List<String> names = new ArrayList<>();
    List<String> values = new ArrayList<>();
    HttpPostRequestDecoder decoder = null;
    try {//from w w w .  j  a v a2s. c o  m
        decoder = new HttpPostRequestDecoder(request);
    } catch (Exception e) {
        //ignore. this means that the body of the POST request does not have key value pairs
        LOGGER.log(Level.WARNING,
                "Failed to decode a post message. Fix the API not to have queries as POST body", e);
    }
    if (decoder != null) {
        try {
            List<InterfaceHttpData> bodyHttpDatas = decoder.getBodyHttpDatas();
            for (InterfaceHttpData data : bodyHttpDatas) {
                if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) {
                    Attribute attr = (MixedAttribute) data;
                    names.add(data.getName());
                    values.add(attr.getValue());
                }
            }
        } finally {
            decoder.destroy();
        }
    }
    return new PostRequest(request, new QueryStringDecoder(request.uri()).parameters(), names, values);
}

From source file:org.apache.hyracks.http.server.util.ServletUtils.java

License:Apache License

public static IServletRequest post(FullHttpRequest request) throws IOException {
    List<String> names = new ArrayList<>();
    List<String> values = new ArrayList<>();
    HttpPostRequestDecoder decoder = null;
    try {/*w  w  w.  j ava  2 s. c  o  m*/
        decoder = new HttpPostRequestDecoder(request);
    } catch (Exception e) {
        //ignore. this means that the body of the POST request does not have key value pairs
        LOGGER.log(Level.WARNING,
                "Failed to decode a post message. Fix the API not to have queries as POST body", e);
    }
    if (decoder != null) {
        try {
            List<InterfaceHttpData> bodyHttpDatas = decoder.getBodyHttpDatas();
            for (InterfaceHttpData data : bodyHttpDatas) {
                if (data.getHttpDataType().equals(HttpDataType.Attribute)) {
                    Attribute attr = (MixedAttribute) data;
                    names.add(data.getName());
                    values.add(attr.getValue());
                }
            }
        } finally {
            decoder.destroy();
        }
    }
    return new PostRequest(request, new QueryStringDecoder(request.uri()).parameters(), names, values);
}

From source file:org.ftccommunity.ftcxtensible.networking.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String page;/*from ww w. j a va2 s . com*/

        if (req.getMethod() == HttpMethod.POST) {
            LinkedList<InterfaceHttpData> postData = new LinkedList<>();
            HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(
                    new DefaultHttpDataFactory(false), req);
            postRequestDecoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    postData.add(data);
                }
            }
            context.addPostData(postData);
        }

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        HttpResponseStatus responseStatus = OK;
        String uri = (req.getUri().equals("/") ? context.getServerSettings().getIndex() : req.getUri());
        if (uri.equals(context.getServerSettings().getHardwareMapJsonPage())) {
            GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
            Gson gson = gsonBuilder.create();
            HardwareMap hardwareMap = context.getHardwareMap();
            page = gson.toJson(ImmutableSet.copyOf(hardwareMap.dcMotor));
        } else if (uri.equals(context.getServerSettings().getLogPage())) {
            page = context.getStatus().getLog();
        } else {
            if (cache.containsKey(uri)) {
                page = cache.get(uri);
                responseStatus = NOT_MODIFIED;
            } else {
                try {
                    page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8);
                } catch (FileNotFoundException e) {
                    Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri);
                    page = "File Not Found!";
                    responseStatus = NOT_FOUND;
                } catch (IOException e) {
                    page = "An Error Occurred!\n" + e.toString();
                    responseStatus = NOT_FOUND;
                    Log.e("NET_OP_MODE::", e.toString(), e);
                }
                cache.put(uri, page);
            }
        }

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
                Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)));

        String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
        String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension))
                + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8"));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:org.ftccommunity.ftcxtensible.networking.http.RobotHttpServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String page;/*w  w w .j a  v  a2 s . c  o m*/

        if (req.getMethod() == HttpMethod.POST) {
            LinkedList<InterfaceHttpData> postData = new LinkedList<>();
            HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(
                    new DefaultHttpDataFactory(false), req);
            postRequestDecoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    postData.add(data);
                }
            }
            context.addPostData(postData);
        }

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        HttpResponseStatus responseStatus = OK;
        String uri = (req.getUri().equals("/") ? context.serverSettings().getIndex() : req.getUri());
        if (uri.equals(context.serverSettings().getHardwareMapJsonPage())) {
            GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
            Gson gson = gsonBuilder.create();
            ExtensibleHardwareMap hardwareMap = context.hardwareMap();
            page = gson.toJson(hardwareMap.dcMotors());
        } else if (uri.equals(context.serverSettings().getLogPage())) {
            page = context.status().getLog();
        } else {
            if (cache.containsKey(uri)) {
                page = cache.get(uri);
                responseStatus = NOT_MODIFIED;
            } else {
                try {
                    page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8);
                } catch (FileNotFoundException e) {
                    Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri);
                    page = "File Not Found!";
                    responseStatus = NOT_FOUND;
                } catch (IOException e) {
                    page = "An Error Occurred!\n" + e.toString();
                    responseStatus = NOT_FOUND;
                    Log.e("NET_OP_MODE::", e.toString(), e);
                }
                cache.put(uri, page);
            }
        }

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
                Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)));

        String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
        String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension))
                + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8"));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:org.jboss.arquillian.warp.impl.client.execution.HttpRequestWrapper.java

License:Apache License

@Override
public Map<String, List<String>> getHttpDataAttributes() {

    if (!HttpMethod.POST.equals(getMethod())) {
        throw new IllegalArgumentException("Cannot parse HttpData for requests other than POST");
    }//from w  ww . ja v a 2  s. com

    try {
        if (httpDataAttributes == null) {
            final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false),
                    request);
            final Map<String, List<String>> map = new HashMap<String, List<String>>();

            try {
                for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
                    if (data.getHttpDataType() == HttpDataType.Attribute) {
                        Attribute attribute = (Attribute) data;

                        List<String> list = map.get(attribute.getName());
                        if (list == null) {
                            list = new LinkedList<String>();
                            map.put(attribute.getName(), list);
                        }

                        list.add(attribute.getValue());
                    }
                }
            } finally {
                decoder.destroy();
            }

            httpDataAttributes = map;
        }

        return Collections.unmodifiableMap(httpDataAttributes);

    } catch (IOException e) {
        throw new IllegalStateException("Cannot parse http request data", e);
    }
}

From source file:org.kaaproject.kaa.server.transports.http.transport.commands.AbstractHttpSyncCommand.java

License:Apache License

@Override
public void parse() throws Exception {
    LOG.trace("CommandName: " + COMMAND_NAME + ": Parse..");
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, getRequest());
    if (decoder.isMultipart()) {
        LOG.trace("Chunked: " + HttpHeaders.isTransferEncodingChunked(getRequest()));
        LOG.trace(": Multipart..");
        List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
        if (!datas.isEmpty()) {
            for (InterfaceHttpData data : datas) {
                LOG.trace("Multipart1 name " + data.getName() + " type " + data.getHttpDataType().name());
                if (data.getHttpDataType() == HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) data;
                    if (CommonEpConstans.REQUEST_SIGNATURE_ATTR_NAME.equals(data.getName())) {
                        requestSignature = attribute.get();
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Multipart name " + data.getName() + " type "
                                    + data.getHttpDataType().name() + " Signature set. size: "
                                    + requestSignature.length);
                            LOG.trace(MessageEncoderDecoder.bytesToHex(requestSignature));
                        }//w  ww  .j ava  2  s.  c o  m

                    } else if (CommonEpConstans.REQUEST_KEY_ATTR_NAME.equals(data.getName())) {
                        requestKey = attribute.get();
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Multipart name " + data.getName() + " type "
                                    + data.getHttpDataType().name() + " requestKey set. size: "
                                    + requestKey.length);
                            LOG.trace(MessageEncoderDecoder.bytesToHex(requestKey));
                        }
                    } else if (CommonEpConstans.REQUEST_DATA_ATTR_NAME.equals(data.getName())) {
                        requestData = attribute.get();
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Multipart name " + data.getName() + " type "
                                    + data.getHttpDataType().name() + " requestData set. size: "
                                    + requestData.length);
                            LOG.trace(MessageEncoderDecoder.bytesToHex(requestData));
                        }
                    } else if (CommonEpConstans.NEXT_PROTOCOL_ATTR_NAME.equals(data.getName())) {
                        nextProtocol = ByteBuffer.wrap(attribute.get()).getInt();
                        LOG.trace("[{}] next protocol is {}", getSessionUuid(), nextProtocol);
                    }
                }
            }
        } else {
            LOG.error("Multipart.. size 0");
            throw new BadRequestException("HTTP Request inccorect, multiprat size is 0");
        }
    }
}

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

License:Apache License

/**
 * Create a new instance./*from   w w w  .  ja v  a  2s . 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();
        }
    }
}

From source file:org.wisdom.engine.wrapper.ContextFromNetty.java

License:Apache License

/**
 * Decodes the content of the request. Notice that the content can be split in several chunk.
 *
 * @param req     the request/* www.ja  va 2s. c o  m*/
 * @param content the content
 * @param decoder the decoder.
 */
public void decodeContent(HttpRequest req, HttpContent content, HttpPostRequestDecoder decoder) {
    // Determine whether the content is chunked.
    boolean readingChunks = HttpHeaders.isTransferEncodingChunked(req);
    // Offer the content to the decoder.
    if (readingChunks) {
        // If needed, read content chunk by chunk.
        decoder.offer(content);
        readHttpDataChunkByChunk(decoder);
    } else {
        // Else, read content.
        if (content.content().isReadable()) {
            // We may have the content in different HTTP message, check if we already have a content.
            // Issue #257.
            // To avoid we run out of memory we cut the read body to 100Kb. This can be configured using the
            // "request.body.max.size" property.
            boolean exceeded = raw != null && raw.length >= services.getConfiguration()
                    .getIntegerWithDefault("request.body.max.size", 100 * 1024);
            if (!exceeded) {
                if (this.raw == null) {
                    this.raw = new byte[content.content().readableBytes()];
                    int readerIndex = content.content().readerIndex();
                    content.content().getBytes(readerIndex, this.raw);
                } else {
                    byte[] bytes = new byte[content.content().readableBytes()];
                    int readerIndex = content.content().readerIndex();
                    content.content().getBytes(readerIndex, bytes);
                    this.raw = Bytes.concat(this.raw, bytes);
                }
            }
        }
        decoder.offer(content);
        try {
            for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
                readAttributeOrFile(data);
            }
        } catch (HttpPostRequestDecoder.NotEnoughDataDecoderException e) {
            LOGGER.debug("Error when decoding content, not enough data", e);
        }
    }
}