Java Code Examples for io.netty.handler.codec.http.HttpContent#content()

The following examples show how to use io.netty.handler.codec.http.HttpContent#content() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JBinaryHttpSparknginClient.java    From Sparkngin with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Ack toAck(HttpContent content) {
  ByteBuf byteBuf = content.content() ;
  byte[] data = new byte[byteBuf.readableBytes()] ;
  byteBuf.readBytes(data) ;
  //byteBuf.release() ;
  Ack ack = null;
  try {
    ack = (Ack)IOUtil.deserialize(data);
  } catch (Exception e) {
    e.printStackTrace();
    ack = new Ack() ;
    ack.setStatus(Ack.Status.ERROR);
    ack.setMessage(e.getMessage());
  }
  return ack ;
}
 
Example 2
Source File: HttpPostMultipartRequestDecoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Initialized the internals from a new chunk
 *
 * @param content
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostMultipartRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}
 
Example 3
Source File: HttpPostStandardRequestDecoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Initialized the internals from a new chunk
 *
 * @param content
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostStandardRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}
 
Example 4
Source File: HttpPostMultipartRequestDecoder.java    From dorado with Apache License 2.0 6 votes vote down vote up
/**
 * Initialized the internals from a new chunk
 *
 * @param content the new received chunk
 * @throws ErrorDataDecoderException if there is a problem with the charset
 *                                   decoding or other errors
 */
@Override
public HttpPostMultipartRequestDecoder offer(HttpContent content) {
	checkDestroyed();

	// Maybe we should better not copy here for performance reasons but this will
	// need
	// more care by the caller to release the content in a correct manner later
	// So maybe something to optimize on a later stage
	ByteBuf buf = content.content();
	if (undecodedChunk == null) {
		undecodedChunk = buf.copy();
	} else {
		undecodedChunk.writeBytes(buf);
	}
	if (content instanceof LastHttpContent) {
		isLastChunk = true;
	}
	parseBody();
	if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
		undecodedChunk.discardReadBytes();
	}
	return this;
}
 
Example 5
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private void put(HttpRequest request, HttpContent content, String index, String digest) throws IOException {
    if (digestBlob == null) {
        digestBlob = blobService.newBlob(index, digest);
    }
    boolean continueExpected = HttpUtil.is100ContinueExpected(currentMessage);
    if (content == null) {
        if (continueExpected) {
            ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        return;
    }


    boolean isLast = content instanceof LastHttpContent;
    ByteBuf byteBuf = content.content();
    try {
        writeToFile(request, byteBuf, isLast, continueExpected);
    } finally {
        byteBuf.release();
    }
}
 
Example 6
Source File: HttpPostMultipartRequestDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialized the internals from a new chunk
 *
 * @param content
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostMultipartRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}
 
Example 7
Source File: HttpPostStandardRequestDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialized the internals from a new chunk
 *
 * @param content
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostStandardRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}
 
Example 8
Source File: HttpPostRequestEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpPostRequestEncoderSlicedBuffer() throws Exception {
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, "http://localhost");

    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
    // add Form attribute
    encoder.addBodyAttribute("getform", "POST");
    encoder.addBodyAttribute("info", "first value");
    encoder.addBodyAttribute("secondinfo", "secondvalue a&");
    encoder.addBodyAttribute("thirdinfo", "short text");
    int length = 100000;
    char[] array = new char[length];
    Arrays.fill(array, 'a');
    String longText = new String(array);
    encoder.addBodyAttribute("fourthinfo", longText.substring(0, 7470));
    File file1 = new File(getClass().getResource("/file-01.txt").toURI());
    encoder.addBodyFileUpload("myfile", file1, "application/x-zip-compressed", false);
    encoder.finalizeRequest();
    while (! encoder.isEndOfInput()) {
        HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
        ByteBuf content = httpContent.content();
        int refCnt = content.refCnt();
        assertTrue("content: " + content + " content.unwrap(): " + content.unwrap() + " refCnt: " + refCnt,
                (content.unwrap() == content || content.unwrap() == null) && refCnt == 1 ||
                content.unwrap() != content && refCnt == 2);
        httpContent.release();
    }
    encoder.cleanFiles();
    encoder.close();
}
 
Example 9
Source File: RequestUtils.java    From tutorials with MIT License 5 votes vote down vote up
static StringBuilder formatBody(HttpContent httpContent) {
    StringBuilder responseData = new StringBuilder();
    ByteBuf content = httpContent.content();
    if (content.isReadable()) {
        responseData.append(content.toString(CharsetUtil.UTF_8)
            .toUpperCase());
        responseData.append("\r\n");
    }
    return responseData;
}
 
Example 10
Source File: HarCaptureFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
/**
 * Adds the size of this httpContent to the requestBodySize.
 *
 * @param httpContent HttpContent to size
 */
protected void captureRequestSize(HttpContent httpContent) {
    Log.e("InnerHandle", "captureRequestSize " + harEntry.getId());
    ByteBuf bufferedContent = httpContent.content();
    int contentSize = bufferedContent.readableBytes();
    requestBodySize.addAndGet(contentSize);
}
 
Example 11
Source File: HarCaptureFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
/**
 * Adds the size of this httpContent to the responseBodySize.
 *
 * @param httpContent HttpContent to size
 */
protected void captureResponseSize(HttpContent httpContent) {
    Log.e("InnerHandle", "captureResponseSize " + harEntry.getId());
    ByteBuf bufferedContent = httpContent.content();
    int contentSize = bufferedContent.readableBytes();
    responseBodySize.addAndGet(contentSize);
    proxyManager.dataReceived(contentSize);
}
 
Example 12
Source File: NettyHttpServerHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            nettySource.consume(new NettyHttpRecord(Optional.ofNullable(""),
                    content.toString(CharsetUtil.UTF_8).getBytes()));
        }

        if (msg instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) msg;

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}
 
Example 13
Source File: Buffering.java    From logbook with MIT License 5 votes vote down vote up
@Override
public State buffer(final HttpMessage message, final HttpContent content) {
    final ByteBuf source = content.content();
    final int index = source.readerIndex();
    source.readBytes(buffer, source.readableBytes());
    source.readerIndex(index);
    return this;
}
 
Example 14
Source File: TrackingPixelRouteHandlerUnitTest.java    From Sparkngin with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onResponse(HttpResponse response) {
  count++;
  HttpContent content = (HttpContent) response;
  ByteBuf buf = content.content();
  try {
    assertEquals(TrackingPixelRouteHandler.getImageBytes(), buf);
  } catch(AssertionError e){
    failure++;
  }
}
 
Example 15
Source File: HarCaptureFilter.java    From CapturePacket with MIT License 4 votes vote down vote up
/**
 * Adds the size of this httpContent to the requestBodySize.
 *
 * @param httpContent HttpContent to size
 */
protected void captureRequestSize(HttpContent httpContent) {
    ByteBuf bufferedContent = httpContent.content();
    int contentSize = bufferedContent.readableBytes();
    requestBodySize.addAndGet(contentSize);
}
 
Example 16
Source File: HttpPostRequestEncoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br>
 * Once finalized, no data must be added.<br>
 * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote
 * server.通过准备请求中的标头完成请求,并返回准备发送的请求。一旦确定,就不需要添加任何数据。如果请求不需要chunk (isChunked() == false),此请求是发送到远程服务器的唯一对象。
 *
 * @return the request object (chunked or not according to size of body)
 * @throws ErrorDataEncoderException
 *             if the encoding is in error or if the finalize were already done
 */
public HttpRequest finalizeRequest() throws ErrorDataEncoderException {
    // Finalize the multipartHttpDatas
    if (!headerFinalized) {
        if (isMultipart) {
            InternalAttribute internal = new InternalAttribute(charset);
            if (duringMixedMode) {
                internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            }
            internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
            globalBodySize += internal.size();
        }
        headerFinalized = true;
    } else {
        throw new ErrorDataEncoderException("Header already encoded");
    }

    HttpHeaders headers = request.headers();
    List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaderNames.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            String lowercased = contentType.toLowerCase();
            if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) ||
                    lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
                // ignore
            } else {
                headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '='
                + multipartDataBoundary;
        headers.add(HttpHeaderNames.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    }
    // Now consider size for chunk or not
    long realSize = globalBodySize;
    if (isMultipart) {
        iterator = multipartHttpDatas.listIterator();
    } else {
        realSize -= 1; // last '&' removed
        iterator = multipartHttpDatas.listIterator();
    }
    headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
            for (CharSequence v : transferEncoding) {
                if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) {
                    // ignore
                } else {
                    headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpUtil.setTransferEncodingChunked(request, true);

        // wrap to hide the possible content
        return new WrappedHttpRequest(request);
    } else {
        // get the only one body and set it to the request
        HttpContent chunk = nextChunk();
        if (request instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) request;
            ByteBuf chunkContent = chunk.content();
            if (fullRequest.content() != chunkContent) {
                fullRequest.content().clear().writeBytes(chunkContent);
                chunkContent.release();
            }
            return fullRequest;
        } else {
            return new WrappedFullHttpRequest(request, chunk);
        }
    }
}
 
Example 17
Source File: HarCaptureFilter.java    From browserup-proxy with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the size of this httpContent to the requestBodySize.
 *
 * @param httpContent HttpContent to size
 */
protected void captureRequestSize(HttpContent httpContent) {
    ByteBuf bufferedContent = httpContent.content();
    int contentSize = bufferedContent.readableBytes();
    requestBodySize.addAndGet(contentSize);
}
 
Example 18
Source File: HarCaptureFilter.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
/**
 * Adds the size of this httpContent to the requestBodySize.
 *
 * @param httpContent HttpContent to size
 */
protected void captureRequestSize(HttpContent httpContent) {
    ByteBuf bufferedContent = httpContent.content();
    int contentSize = bufferedContent.readableBytes();
    requestBodySize.addAndGet(contentSize);
}
 
Example 19
Source File: HttpResponseHandler.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {

        response = (HttpResponse) msg;

        resultCallback.onStart(() -> ctx.channel().close());

    } else if (msg instanceof HttpContent) {

        HttpContent content = (HttpContent) msg;

        ByteBuf byteBuf = content.content();

        switch (response.status().code()) {
            case 200:
            case 201:
            case 204:
                ctx.fireChannelRead(byteBuf);
                break;
            default:
                errorBody.writeBytes(byteBuf);
        }

        if (content instanceof LastHttpContent) {
            try {

                switch (response.status().code()) {
                    case 101:
                    case 200:
                    case 201:
                    case 204:
                        break;
                    case 301:
                    case 302:
                        if (response.headers().contains(HttpHeaderNames.LOCATION)) {
                            String location = response.headers().get(HttpHeaderNames.LOCATION);
                            HttpRequest redirected = requestProvider.getHttpRequest(location);

                            ctx.channel().writeAndFlush(redirected);
                        }
                        break;
                    case 304:
                        throw new NotModifiedException(getBodyAsMessage(errorBody));
                    case 400:
                        throw new BadRequestException(getBodyAsMessage(errorBody));
                    case 401:
                        throw new UnauthorizedException(getBodyAsMessage(errorBody));
                    case 404:
                        throw new NotFoundException(getBodyAsMessage(errorBody));
                    case 406:
                        throw new NotAcceptableException(getBodyAsMessage(errorBody));
                    case 409:
                        throw new ConflictException(getBodyAsMessage(errorBody));
                    case 500:
                        throw new InternalServerErrorException(getBodyAsMessage(errorBody));
                    default:
                        throw new DockerException(getBodyAsMessage(errorBody), response.status().code());
                }
            } catch (Throwable e) {
                resultCallback.onError(e);
            } finally {
                resultCallback.onComplete();
            }
        }
    }
}
 
Example 20
Source File: NettyServletInputStream.java    From cxf with Apache License 2.0 4 votes vote down vote up
public NettyServletInputStream(HttpContent httpContent) {
    this.byteBuf = httpContent.content();
    this.in = new ByteBufInputStream(byteBuf);
}