io.netty.handler.codec.DecoderResult Java Examples

The following examples show how to use io.netty.handler.codec.DecoderResult. 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: DefaultSocks5CommandRequest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(128);
    buf.append(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", type: ");
    } else {
        buf.append("(type: ");
    }
    buf.append(type());
    buf.append(", dstAddrType: ");
    buf.append(dstAddrType());
    buf.append(", dstAddr: ");
    buf.append(dstAddr());
    buf.append(", dstPort: ");
    buf.append(dstPort());
    buf.append(')');

    return buf.toString();
}
 
Example #2
Source File: HttpObjectAggregatorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceAggregatedRequest() {
    EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(1024 * 1024));

    Exception boom = new Exception("boom");
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost");
    req.setDecoderResult(DecoderResult.failure(boom));

    assertTrue(embedder.writeInbound(req) && embedder.finish());

    FullHttpRequest aggregatedReq = embedder.readInbound();
    FullHttpRequest replacedReq = aggregatedReq.replace(Unpooled.EMPTY_BUFFER);

    assertEquals(replacedReq.decoderResult(), aggregatedReq.decoderResult());
    aggregatedReq.release();
    replacedReq.release();
}
 
Example #3
Source File: HttpObjectAggregatorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceAggregatedResponse() {
    EmbeddedChannel embedder = new EmbeddedChannel(new HttpObjectAggregator(1024 * 1024));

    Exception boom = new Exception("boom");
    HttpResponse rep = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    rep.setDecoderResult(DecoderResult.failure(boom));

    assertTrue(embedder.writeInbound(rep) && embedder.finish());

    FullHttpResponse aggregatedRep = embedder.readInbound();
    FullHttpResponse replacedRep = aggregatedRep.replace(Unpooled.EMPTY_BUFFER);

    assertEquals(replacedRep.decoderResult(), aggregatedRep.decoderResult());
    aggregatedRep.release();
    replacedRep.release();
}
 
Example #4
Source File: RiposteHandlerInternalUtilTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void getDecoderFailure_returns_null_when_DecoderResult_is_not_a_failure(
    boolean isUnfinished
) {
    // given
    HttpObject httpObjectMock = mock(HttpObject.class);
    DecoderResult nonFailureDecoderResult = (isUnfinished) ? DecoderResult.UNFINISHED : DecoderResult.SUCCESS;
    doReturn(nonFailureDecoderResult).when(httpObjectMock).decoderResult();

    // when
    Throwable result = implSpy.getDecoderFailure(httpObjectMock);

    // then
    assertThat(result).isNull();
}
 
Example #5
Source File: RequestInfoSetterHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void doChannelRead_HttpRequest_throws_exception_when_failed_decoder_result() {
    // given
    HttpRequest msgMock = mock(HttpRequest.class);
    Throwable decoderFailureCauseMock = mock(Throwable.class);
    DecoderResult decoderResult = DecoderResult.failure(decoderFailureCauseMock);
    doReturn(decoderResult).when(msgMock).decoderResult();
    doReturn(null).when(stateMock).getRequestInfo();

    // when
    Throwable thrownException = Assertions.catchThrowable(() -> handler.doChannelRead(ctxMock, msgMock));

    // then
    assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class);
    assertThat(thrownException.getCause()).isSameAs(decoderFailureCauseMock);
}
 
Example #6
Source File: HttpObjectDecoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private HttpMessage invalidMessage(ByteBuf in, Exception cause) {
    currentState = State.BAD_MESSAGE;

    // Advance the readerIndex so that ByteToMessageDecoder does not complain
    // when we produced an invalid message without consuming anything.
    in.skipBytes(in.readableBytes());

    if (message != null) {
        message.setDecoderResult(DecoderResult.failure(cause));
    } else {
        message = createInvalidMessage();
        message.setDecoderResult(DecoderResult.failure(cause));
    }

    HttpMessage ret = message;
    message = null;
    return ret;
}
 
Example #7
Source File: HttpObjectDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private HttpMessage invalidMessage(ByteBuf in, Exception cause) {
        currentState = State.BAD_MESSAGE;

        // Advance the readerIndex so that ByteToMessageDecoder does not complain
        // when we produced an invalid message without consuming anything.//提升readerIndex,这样ByteToMessageDecoder就不会报错了
//当我们产生了一个无效的消息而没有消耗任何东西。
        in.skipBytes(in.readableBytes());

        if (message != null) {
            message.setDecoderResult(DecoderResult.failure(cause));
        } else {
            message = createInvalidMessage();
            message.setDecoderResult(DecoderResult.failure(cause));
        }

        HttpMessage ret = message;
        message = null;
        return ret;
    }
 
Example #8
Source File: DefaultSocks5PasswordAuthRequest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", username: ");
    } else {
        buf.append("(username: ");
    }
    buf.append(username());
    buf.append(", password: ****)");

    return buf.toString();
}
 
Example #9
Source File: DefaultSocks5CommandResponse.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(128);
    buf.append(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", status: ");
    } else {
        buf.append("(status: ");
    }
    buf.append(status());
    buf.append(", bndAddrType: ");
    buf.append(bndAddrType());
    buf.append(", bndAddr: ");
    buf.append(bndAddr());
    buf.append(", bndPort: ");
    buf.append(bndPort());
    buf.append(')');

    return buf.toString();
}
 
Example #10
Source File: RoutingHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void doChannelRead_HttpRequest_throws_exception_when_failed_decoder_result() {
    // given
    HttpRequest msgMock = mock(HttpRequest.class);
    Throwable decoderFailureCauseMock = mock(Throwable.class);
    DecoderResult decoderResult = DecoderResult.failure(decoderFailureCauseMock);
    doReturn(decoderResult).when(msgMock).decoderResult();
    doReturn(null).when(stateMock).getRequestInfo();

    // when
    Throwable thrownException = Assertions.catchThrowable(() -> handlerSpy.doChannelRead(ctxMock, msgMock));

    // then
    assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class);
    assertThat(thrownException.getCause()).isSameAs(decoderFailureCauseMock);
}
 
Example #11
Source File: DefaultSocks5PasswordAuthResponse.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", status: ");
    } else {
        buf.append("(status: ");
    }
    buf.append(status());
    buf.append(')');

    return buf.toString();
}
 
Example #12
Source File: DefaultSocks5InitialRequest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", authMethods: ");
    } else {
        buf.append("(authMethods: ");
    }
    buf.append(authMethods());
    buf.append(')');

    return buf.toString();
}
 
Example #13
Source File: HttpSnoopServerHandler.java    From julongchain with Apache License 2.0 5 votes vote down vote up
private static void appendDecoderResult(StringBuilder buf, HttpObject o) {
    DecoderResult result = o.decoderResult();
    if (result.isSuccess()) {
        return;
    }

    buf.append(".. WITH DECODER FAILURE: ");
    buf.append(result.cause());
    buf.append("\r\n");
}
 
Example #14
Source File: NettyHttpResponse.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void recycle() {
    this.content = null;
    this.headers.clear();
    this.version = HttpVersion.HTTP_1_1;
    this.status = DEFAULT_STATUS;
    this.lastHttpContent = null;
    this.decoderResult = DecoderResult.SUCCESS;
}
 
Example #15
Source File: RequestInfoSetterHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void doChannelRead_HttpContent_throws_exception_when_failed_decoder_result() {
    // given
    Throwable decoderFailureCauseMock = mock(Throwable.class);
    DecoderResult decoderResult = DecoderResult.failure(decoderFailureCauseMock);
    doReturn(decoderResult).when(httpContentMock).decoderResult();

    // when
    Throwable thrownException = Assertions.catchThrowable(() -> handler.doChannelRead(ctxMock, httpContentMock));

    // then
    assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class);
    assertThat(thrownException.getCause()).isSameAs(decoderFailureCauseMock);
    verify(httpContentMock).release();
}
 
Example #16
Source File: DefaultHttpObject.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void setDecoderResult(DecoderResult decoderResult) {
    if (decoderResult == null) {
        throw new NullPointerException("decoderResult");
    }
    this.decoderResult = decoderResult;
}
 
Example #17
Source File: AbstractBinaryMemcacheDecoder.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to create a message indicating a invalid decoding result.
 *
 * @param cause the cause of the decoding failure.
 * @return a valid message indicating failure.
 */
private M invalidMessage(Exception cause) {
    state = State.BAD_MESSAGE;
    M message = buildInvalidMessage();
    message.setDecoderResult(DecoderResult.failure(cause));
    return message;
}
 
Example #18
Source File: HttpServerHandler.java    From cantor with Apache License 2.0 5 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (FullHttpRequest.class.isAssignableFrom(msg.getClass())) {
            FullHttpRequest req = FullHttpRequest.class.cast(msg);
            DecoderResult result = req.decoderResult();

            if (result.isFailure()) {
                if (log.isWarnEnabled())
                    log.warn("http decoder failure", result.cause());
                ReferenceCountUtil.release(msg);
                ctx.writeAndFlush(HttpResponses.badRequest());
                ctx.channel().close();
                return;
            }

            if (HttpUtil.is100ContinueExpected(req))
                ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), CONTINUE));

            FullHttpRequest safeReq = new DefaultFullHttpRequest(req.protocolVersion(),
                                                                 req.method(),
                                                                 req.uri(),
//                                                                 Buffers.safeByteBuf(req.content(), ctx.alloc()),
                                                                 req.content(),
                                                                 req.headers(),
                                                                 req.trailingHeaders());
            channelRead(ctx, safeReq);
        } else
            ctx.fireChannelRead(msg);
    }
 
Example #19
Source File: HttpInvalidMessageTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithBadInitialLine() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder());
    ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0 with extra\r\n", CharsetUtil.UTF_8));
    HttpRequest req = (HttpRequest) ch.readInbound();
    DecoderResult dr = req.getDecoderResult();
    assertFalse(dr.isSuccess());
    assertTrue(dr.isFailure());
    ensureInboundTrafficDiscarded(ch);
}
 
Example #20
Source File: HttpPostRequestDecoderTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testFullHttpRequestUpload() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");

    req.setDecoderResult(DecoderResult.SUCCESS);
    req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

    for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
        final String body =
                "--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                        "Content-Type: image/gif\r\n" +
                        "\r\n" +
                        data + "\r\n" +
                        "--" + boundary + "--\r\n";

        req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    }
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}
 
Example #21
Source File: HttpInvalidMessageTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseWithBadInitialLine() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder());
    ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 BAD_CODE Bad Server\r\n", CharsetUtil.UTF_8));
    HttpResponse res = (HttpResponse) ch.readInbound();
    DecoderResult dr = res.getDecoderResult();
    assertFalse(dr.isSuccess());
    assertTrue(dr.isFailure());
    ensureInboundTrafficDiscarded(ch);
}
 
Example #22
Source File: HttpPostRequestDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFullHttpRequestUpload() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");

    req.setDecoderResult(DecoderResult.SUCCESS);
    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);

    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

    for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
        final String body =
                "--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                        "Content-Type: image/gif\r\n" +
                        "\r\n" +
                        data + "\r\n" +
                        "--" + boundary + "--\r\n";

        req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    }
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}
 
Example #23
Source File: HttpPostRequestDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuotedBoundary() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "http://localhost");

    req.setDecoderResult(DecoderResult.SUCCESS);
    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=\"" + boundary + '"');
    req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);

    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

    for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
        final String body =
                "--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                        "Content-Type: image/gif\r\n" +
                        "\r\n" +
                        data + "\r\n" +
                        "--" + boundary + "--\r\n";

        req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    }
    // Create decoder instance to test.
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    decoder.destroy();
}
 
Example #24
Source File: RequestAdapter.java    From k3pler with GNU General Public License v3.0 5 votes vote down vote up
private String getShortResult(DecoderResult result){
    if (result.isSuccess())
        return "S";
    else if (result.isFinished())
        return "F";
    else if (result.isFailure())
        return "X";
    else
        return "-";
}
 
Example #25
Source File: MqttMessage.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public MqttMessage(
        MqttFixedHeader mqttFixedHeader,
        Object variableHeader,
        Object payload,
        DecoderResult decoderResult) {
    this.mqttFixedHeader = mqttFixedHeader;
    this.variableHeader = variableHeader;
    this.payload = payload;
    this.decoderResult = decoderResult;
}
 
Example #26
Source File: HttpInvalidMessageTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithBadHeader() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder());
    ch.writeInbound(Unpooled.copiedBuffer("GET /maybe-something HTTP/1.0\r\n", CharsetUtil.UTF_8));
    ch.writeInbound(Unpooled.copiedBuffer("Good_Name: Good Value\r\n", CharsetUtil.UTF_8));
    ch.writeInbound(Unpooled.copiedBuffer("Bad=Name: Bad Value\r\n", CharsetUtil.UTF_8));
    ch.writeInbound(Unpooled.copiedBuffer("\r\n", CharsetUtil.UTF_8));
    HttpRequest req = (HttpRequest) ch.readInbound();
    DecoderResult dr = req.getDecoderResult();
    assertFalse(dr.isSuccess());
    assertTrue(dr.isFailure());
    assertEquals("Good Value", req.headers().get("Good_Name"));
    assertEquals("/maybe-something", req.getUri());
    ensureInboundTrafficDiscarded(ch);
}
 
Example #27
Source File: SampleHandler.java    From xio with Apache License 2.0 5 votes vote down vote up
private static void appendDecoderResult(StringBuilder buf, HttpObject o) {
  DecoderResult result = o.getDecoderResult();
  if (result.isSuccess()) {
    return;
  }

  buf.append(".. WITH DECODER FAILURE: ");
  buf.append(result.cause());
  buf.append("\r\n");
}
 
Example #28
Source File: AbstractMemcacheObject.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void setDecoderResult(DecoderResult result) {
    if (result == null) {
        throw new NullPointerException("DecoderResult should not be null.");
    }

    decoderResult = result;
}
 
Example #29
Source File: RequestFilterHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void doChannelRead_HttpRequest_throws_exception_when_failed_decoder_result() {
    // given
    Throwable decoderFailureCauseMock = mock(Throwable.class);
    DecoderResult decoderResult = DecoderResult.failure(decoderFailureCauseMock);
    doReturn(decoderResult).when(firstChunkMsgMock).decoderResult();
    state.setRequestInfo(null);

    // when
    Throwable thrownException = Assertions.catchThrowable(() -> handlerSpy.doChannelRead(ctxMock, firstChunkMsgMock));

    // then
    assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class);
    assertThat(thrownException.getCause()).isSameAs(decoderFailureCauseMock);
}
 
Example #30
Source File: HttpSnoopServerHandler.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
private static void appendDecoderResult(StringBuilder buf, HttpObject o) {
    DecoderResult result = o.decoderResult();
    if (result.isSuccess()) {
        return;
    }

    buf.append(".. WITH DECODER FAILURE: ");
    buf.append(result.cause());
    buf.append("\r\n");
}