@Test
  public void testInboundChainNoChanges() throws Exception {
    List<Interceptor> interceptors = new ArrayList<>();

    MockInterceptor interceptor1 = new MockInterceptor();
    MockInterceptor interceptor2 = new MockInterceptor();

    interceptors.add(interceptor1);
    interceptors.add(interceptor2);

    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ChannelDuplexHandler() {
              @Override
              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                InterceptorChain chain =
                    new InterceptorChain(ctx, interceptors, (ResourceRequest) msg);
                chain.fireInbound();
              }
            });

    ResourceRequest request =
        new DefaultResourceRequest.Builder(RequestType.READ, new ResourcePath("/foo/bar")).build();
    channel.writeInbound(request);

    ResourceRequest endRequest = (ResourceRequest) channel.readInbound();

    assertThat(endRequest).isNotNull();
    assertThat(interceptor1.requests()).hasSize(1);
    assertThat(interceptor1.requests()).contains(request);
    assertThat(interceptor2.requests()).hasSize(1);
    assertThat(interceptor2.requests()).contains(request);
  }
  @Test
  public void testLargeFileRegionChunked() throws Exception {
    EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
    assertTrue(channel.writeOutbound(response));

    ByteBuf buffer = channel.readOutbound();

    assertEquals(
        "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
        buffer.toString(CharsetUtil.US_ASCII));
    buffer.release();
    assertTrue(channel.writeOutbound(FILE_REGION));
    buffer = channel.readOutbound();
    assertEquals("80000000\r\n", buffer.toString(CharsetUtil.US_ASCII));
    buffer.release();

    FileRegion region = channel.readOutbound();
    assertSame(FILE_REGION, region);
    region.release();
    buffer = channel.readOutbound();
    assertEquals("\r\n", buffer.toString(CharsetUtil.US_ASCII));
    buffer.release();

    assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT));
    buffer = channel.readOutbound();
    assertEquals("0\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII));
    buffer.release();

    assertFalse(channel.finish());
  }
  @Test
  public void testRemoveItselfWithReplayError() {
    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ReplayingDecoder() {
              private boolean removed;

              @Override
              protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                  throws Exception {
                assertFalse(removed);
                ctx.pipeline().remove(this);

                in.readBytes(1000);

                removed = true;
              }
            });

    ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'a', 'b', 'c'});
    channel.writeInbound(buf.copy());
    ByteBuf b = channel.readInbound();

    assertEquals("Expect to have still all bytes in the buffer", b, buf);
    b.release();
    buf.release();
  }
 @Test
 public void testEncode() {
   byte[] b = new byte[2048];
   new Random().nextBytes(b);
   ch.writeOutbound(b);
   assertThat((ByteBuf) ch.readOutbound(), is(wrappedBuffer(b)));
 }
  @Test
  public void testDummyIncoming() {
    ch.writeInbound(Unpooled.wrappedBuffer(new byte[] {0x02, (byte) 0xFF, 0x01, 23}));

    UsnIncomingMessage msg = (UsnIncomingMessage) ch.readInbound();
    assertEquals(msg.getMessageType(), DUMMY_INCOMING);
  }
  @Test
  public void testConnect() {
    StringBuilder builder = new StringBuilder();
    try {
      builder
          .append("환영합니다. ")
          .append(InetAddress.getLocalHost().getHostName())
          .append("에 접속하셨습니다!\r\n")
          .append("현재 시간은 ")
          .append(new Date().toString())
          .append(" 입니다.\r\n");
    } catch (UnknownHostException e) {
      fail();
      e.printStackTrace();
    }

    EmbeddedChannel embeddedChannel = new EmbeddedChannel(new TelnetServerHandlerV3());

    String expected = (String) embeddedChannel.readOutbound();
    assertNotNull(expected);

    assertEquals(builder.toString(), (String) expected);

    String request = "hello";
    expected = "입력하신 명령이 '" + request + "' 입니까?\r\n";

    embeddedChannel.writeInbound(request);

    String response = (String) embeddedChannel.readOutbound();
    assertEquals(expected, response);

    embeddedChannel.finish();
  }
  @Test
  public void testNoneExtensionMatchingSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown")))
        .andReturn(null)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown2")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown")))
        .andReturn(null)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown2")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("unknown, unknown2");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();

    // test
    assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
  }
  @Test
  public void testRemoveItselfWriteBuffer() {
    final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[] {'a', 'b', 'c'});
    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ReplayingDecoder() {
              private boolean removed;

              @Override
              protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                  throws Exception {
                assertFalse(removed);
                in.readByte();
                ctx.pipeline().remove(this);

                // This should not let it keep call decode
                buf.writeByte('d');
                removed = true;
              }
            });

    channel.writeInbound(buf.copy());
    ByteBuf b = channel.readInbound();
    assertEquals(b, Unpooled.wrappedBuffer(new byte[] {'b', 'c'}));
    b.release();
    buf.release();
  }
  @Test
  public void testDummyOutgoingAck() {
    ch.writeInbound(Unpooled.wrappedBuffer(new byte[] {(byte) 0x81, (byte) 0xFF, 0x00}));

    UsnIncomingMessage msg = (UsnIncomingMessage) ch.readInbound();
    assertEquals(msg.getMessageType(), DUMMY_OUTGOING_ACK);
  }
  /**
   * This test makes sure that even when the decoder is confronted with various chunk sizes in the
   * middle of decoding, it can recover and decode all the time eventually.
   */
  @Test
  public void shouldHandleNonUniformNetworkBatches() {
    ByteBuf incoming = Unpooled.copiedBuffer(SET_REQUEST_WITH_CONTENT);
    while (incoming.isReadable()) {
      channel.writeInbound(incoming.readBytes(5));
    }

    BinaryMemcacheRequest request = (BinaryMemcacheRequest) channel.readInbound();

    assertThat(request, notNullValue());
    assertThat(request.getHeader(), notNullValue());
    assertThat(request.getKey(), notNullValue());
    assertThat(request.getExtras(), nullValue());

    request.release();

    MemcacheContent content1 = (MemcacheContent) channel.readInbound();
    MemcacheContent content2 = (MemcacheContent) channel.readInbound();

    assertThat(content1, instanceOf(MemcacheContent.class));
    assertThat(content2, instanceOf(LastMemcacheContent.class));

    assertThat(content1.content().readableBytes(), is(3));
    assertThat(content2.content().readableBytes(), is(5));

    content1.release();
    content2.release();
  }
  @Test
  public void testValidInitRequest() throws Exception {

    // Given
    EmbeddedChannel channel = new EmbeddedChannel(new InitRequestHandler());

    InitRequest initRequest =
        new InitRequest(
            42,
            InitMessage.DEFAULT_VERSION,
            new HashMap<String, String>() {
              {
                put(InitMessage.HOST_PORT_KEY, "0.0.0.0:0");
                put(InitMessage.PROCESS_NAME_KEY, "test-process");
              }
            });

    channel.writeInbound(initRequest);
    channel.writeOutbound(channel.readInbound());

    // Then
    InitResponse initResponse = channel.readOutbound();

    // Assert
    assertNotNull(initResponse);
    assertEquals(initRequest.getId(), initResponse.getId());
    assertEquals(initRequest.getVersion(), initResponse.getVersion());
    assertEquals(initRequest.getHostPort(), initResponse.getHostPort());
  }
  @Test
  public void testIncorrectProtocolVersion() throws Exception {
    // Given
    EmbeddedChannel channel = new EmbeddedChannel(new InitRequestHandler());

    InitRequest initRequest =
        new InitRequest(
            42,
            1,
            new HashMap<String, String>() {
              {
                put(InitMessage.HOST_PORT_KEY, "0.0.0.0:0");
                put(InitMessage.PROCESS_NAME_KEY, "test-process");
              }
            });

    channel.writeInbound(initRequest);
    ErrorMessage error = channel.readOutbound();
    assertNotNull(error);
    assertThat(error.getType(), is(ErrorType.FatalProtocolError));
    assertThat(error.getMessage(), containsString("version"));

    this.expectedClosedChannelException.expect(ClosedChannelException.class);
    channel.writeOutbound();
  }
  @Test
  public void testLastResponseWithHeaderRemoveTrailingSpaces() {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder());
    ch.writeInbound(
        Unpooled.copiedBuffer(
            "HTTP/1.1 200 OK\r\nX-Header: h2=h2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT       \r\n\r\n",
            CharsetUtil.US_ASCII));

    HttpResponse res = ch.readInbound();
    assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1));
    assertThat(res.getStatus(), is(HttpResponseStatus.OK));
    assertThat(res.headers().get("X-Header"), is("h2=h2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT"));
    assertThat(ch.readInbound(), is(nullValue()));

    ch.writeInbound(Unpooled.wrappedBuffer(new byte[1024]));
    HttpContent content = ch.readInbound();
    assertThat(content.content().readableBytes(), is(1024));
    content.release();

    assertThat(ch.finish(), is(true));

    LastHttpContent lastContent = ch.readInbound();
    assertThat(lastContent.content().isReadable(), is(false));
    lastContent.release();

    assertThat(ch.readInbound(), is(nullValue()));
  }
  @Test
  public void testRemoveAndWriteAllReentrance() {
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final PendingWriteQueue queue = new PendingWriteQueue(channel.pipeline().firstContext());

    ChannelPromise promise = channel.newPromise();
    promise.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            queue.removeAndWriteAll();
          }
        });
    queue.add(1L, promise);

    ChannelPromise promise2 = channel.newPromise();
    queue.add(2L, promise2);
    queue.removeAndWriteAll();
    channel.flush();
    assertTrue(promise.isSuccess());
    assertTrue(promise2.isSuccess());
    assertTrue(channel.finish());

    assertEquals(1L, channel.readOutbound());
    assertEquals(2L, channel.readOutbound());
    assertNull(channel.readOutbound());
    assertNull(channel.readInbound());
  }
  @Test
  public void shouldFireChannelWritabilityChangedAfterRemoval() {
    final AtomicReference<ChannelHandlerContext> ctxRef =
        new AtomicReference<ChannelHandlerContext>();
    final AtomicReference<PendingWriteQueue> queueRef = new AtomicReference<PendingWriteQueue>();
    final ByteBuf msg = Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII);

    final EmbeddedChannel channel =
        new EmbeddedChannel(
            new ChannelHandlerAdapter() {
              @Override
              public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                ctxRef.set(ctx);
                queueRef.set(new PendingWriteQueue(ctx));
              }

              @Override
              public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
                final PendingWriteQueue queue = queueRef.get();

                final ByteBuf msg = (ByteBuf) queue.current();
                if (msg == null) {
                  return;
                }

                assertThat(msg.refCnt(), is(1));

                // This call will trigger another channelWritabilityChanged() event because the
                // number of
                // pending bytes will go below the low watermark.
                //
                // If PendingWriteQueue.remove() did not remove the current entry before triggering
                // channelWritabilityChanged() event, we will end up with attempting to remove the
                // same
                // element twice, resulting in the double release.
                queue.remove();

                assertThat(msg.refCnt(), is(0));
              }
            });

    channel.config().setWriteBufferLowWaterMark(1);
    channel.config().setWriteBufferHighWaterMark(3);

    final PendingWriteQueue queue = queueRef.get();

    // Trigger channelWritabilityChanged() by adding a message that's larger than the high
    // watermark.
    queue.add(msg, channel.newPromise());

    channel.finish();

    assertThat(msg.refCnt(), is(0));
  }
  @Test
  public void testWrite() throws Exception {
    ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(128));
    EmbeddedChannel channel = createChannel();

    Assert.assertEquals(0, channel.outboundMessages().size());

    NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false);
    conn.write(buff);
    channel.runPendingTasks();
    Assert.assertEquals(1, channel.outboundMessages().size());
  }
  @Test
  public void testMainSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(mainExtensionMock)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(fallbackExtensionMock)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    expect(mainExtensionMock.rsv()).andReturn(WebSocketExtension.RSV1).anyTimes();
    expect(mainExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("main", Collections.<String, String>emptyMap()))
        .once();
    expect(mainExtensionMock.newExtensionEncoder()).andReturn(new DummyEncoder()).once();
    expect(mainExtensionMock.newExtensionDecoder()).andReturn(new DummyDecoder()).once();
    replay(mainExtensionMock);

    expect(fallbackExtensionMock.rsv()).andReturn(WebSocketExtension.RSV1).anyTimes();
    replay(fallbackExtensionMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("main, fallback");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();
    List<WebSocketExtensionData> resExts =
        WebSocketExtensionUtil.extractExtensions(
            res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));

    // test
    assertEquals(1, resExts.size());
    assertEquals("main", resExts.get(0).name());
    assertTrue(resExts.get(0).parameters().isEmpty());
    assertNotNull(ch.pipeline().get(DummyDecoder.class));
    assertNotNull(ch.pipeline().get(DummyEncoder.class));
  }
  @Test
  public void testInboundChainShortCircuit() throws Exception {

    List<Interceptor> interceptors = new ArrayList<>();

    ResourceRequest request =
        new DefaultResourceRequest.Builder(RequestType.READ, new ResourcePath("/foo/bar")).build();
    ResourceResponse response =
        new DefaultResourceErrorResponse(request, ResourceErrorResponse.ErrorType.NOT_AUTHORIZED);

    MockInterceptor interceptor1 = new MockInterceptor();
    MockInterceptor interceptor2 =
        new MockInterceptor() {
          @Override
          public void onInbound(InboundInterceptorContext context) throws Exception {
            requests.add(context.request());
            context.replyWith(response);
          }
        };
    MockInterceptor interceptor3 = new MockInterceptor();

    interceptors.add(interceptor1);
    interceptors.add(interceptor2);
    interceptors.add(interceptor3);

    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ChannelDuplexHandler() {
              @Override
              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                InterceptorChain chain =
                    new InterceptorChain(ctx, interceptors, (ResourceRequest) msg);
                chain.fireInbound();
              }
            });

    channel.writeInbound(request);
    ResourceRequest endRequest = (ResourceRequest) channel.readInbound();
    Object endResponse = channel.readOutbound();

    assertThat(endRequest).isNull();

    assertThat(interceptor1.requests()).hasSize(1);
    assertThat(interceptor1.requests()).contains(request);
    assertThat(interceptor2.requests()).hasSize(1);
    assertThat(interceptor2.requests()).contains(request);
    assertThat(interceptor3.requests()).isEmpty();

    assertThat(interceptor3.responses()).isEmpty();
    assertThat(interceptor2.responses()).isEmpty();
    assertThat(interceptor1.responses()).hasSize(1);
    assertThat(interceptor1.responses()).contains(response);
  }
 @Test
 public void echo() {
   String m = "echo test\n";
   EmbeddedChannel ch = new EmbeddedChannel(new EchoServerHandler());
   ByteBuf in = Unpooled.copiedBuffer(m, CharsetUtil.UTF_8);
   ch.writeInbound(in);
   ByteBuf r = (ByteBuf) ch.readOutbound();
   releaseLater(r);
   assertThat("응답이 없습니다", r, notNullValue());
   assertThat("참조수는 1이어야 합니다", r.refCnt(), is(1));
   assertThat("수신한 텍스트가 결과로 와야합니다", r.toString(CharsetUtil.UTF_8), equalTo(m));
 }
 /**
  * Release remaining content from the {@link EmbeddedChannel} and remove the decoder from the
  * {@link Http2Stream}.
  *
  * @param stream The stream for which {@code decoder} is the decompressor for
  * @param decoder The decompressor for {@code stream}
  */
 private static void cleanup(Http2Stream stream, EmbeddedChannel decoder) {
   if (decoder.finish()) {
     for (; ; ) {
       final ByteBuf buf = decoder.readInbound();
       if (buf == null) {
         break;
       }
       buf.release();
     }
   }
   stream.decompressor(null);
 }
  @Test
  public void testDummyIncomingAck() {
    ByteBuf expectResult = Unpooled.wrappedBuffer(new byte[] {(byte) 0x82, 0x00, 0x00});

    ch.writeOutbound(UsnMessageHelper.makeDummyIncomingAck());

    ByteBuf outBuff = (ByteBuf) ch.readOutbound();

    while (expectResult.isReadable()) {
      assertEquals(expectResult.readUnsignedByte(), outBuff.readUnsignedByte());
    }
  }
  // See https://github.com/netty/netty/issues/3967
  @Test
  public void testCloseChannelOnCreation() {
    EmbeddedChannel channel = new EmbeddedChannel();
    channel.close().syncUninterruptibly();

    final PendingWriteQueue queue = new PendingWriteQueue(channel.pipeline().firstContext());

    IllegalStateException ex = new IllegalStateException();
    ChannelPromise promise = channel.newPromise();
    queue.add(1L, promise);
    queue.removeAndFailAll(ex);
    assertSame(ex, promise.cause());
  }
Exemple #23
0
  private boolean handleClientSideCustomPacket(
      S3FPacketCustomPayload msg, ChannelHandlerContext context) {
    String channelName = msg.getChannelName();
    if ("FML|MP".equals(channelName)) {
      try {
        if (multipart == null) {
          multipart = new MultiPartCustomPayload(msg.getBufferData());
        } else {
          multipart.processPart(msg.getBufferData());
        }
      } catch (IOException e) {
        this.kickWithMessage(e.getMessage());
        multipart = null;
        return true;
      }

      if (multipart.isComplete()) {
        msg = multipart;
        channelName = msg.getChannelName();
        multipart = null;
      } else {
        return true; // Haven't received all so return till we have.
      }
    }
    if ("FML|HS".equals(channelName)
        || "REGISTER".equals(channelName)
        || "UNREGISTER".equals(channelName)) {
      FMLProxyPacket proxy = new FMLProxyPacket(msg);
      proxy.setDispatcher(this);
      handshakeChannel.writeInbound(proxy);
      // forward any messages into the regular channel
      for (Object push : handshakeChannel.inboundMessages()) {
        List<FMLProxyPacket> messageResult =
            FMLNetworkHandler.forwardHandshake(
                (FMLMessage.CompleteHandshake) push, this, Side.CLIENT);
        for (FMLProxyPacket result : messageResult) {
          result.setTarget(Side.CLIENT);
          result.payload().resetReaderIndex();
          context.fireChannelRead(result);
        }
      }
      handshakeChannel.inboundMessages().clear();
      return true;
    } else if (NetworkRegistry.INSTANCE.hasChannel(channelName, Side.CLIENT)) {
      FMLProxyPacket proxy = new FMLProxyPacket(msg);
      proxy.setDispatcher(this);
      context.fireChannelRead(proxy);
      return true;
    }
    return false;
  }
  @Test
  public void testClosureWithoutContentLength2() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder());

    // Write the partial response.
    ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.1 200 OK\r\n\r\n12345678", CharsetUtil.US_ASCII));

    // Read the response headers.
    HttpResponse res = ch.readInbound();
    assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1));
    assertThat(res.getStatus(), is(HttpResponseStatus.OK));

    // Read the partial content.
    HttpContent content = ch.readInbound();
    assertThat(content.content().toString(CharsetUtil.US_ASCII), is("12345678"));
    assertThat(content, is(not(instanceOf(LastHttpContent.class))));
    content.release();

    assertThat(ch.readInbound(), is(nullValue()));

    // Close the connection.
    assertTrue(ch.finish());

    // The decoder should still produce the last content.
    LastHttpContent lastContent = ch.readInbound();
    assertThat(lastContent.content().isReadable(), is(false));
    lastContent.release();

    // But nothing more.
    assertThat(ch.readInbound(), is(nullValue()));
  }
  @Test
  public void testResponseWithContentLength() {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder());
    ch.writeInbound(
        Unpooled.copiedBuffer(
            "HTTP/1.1 200 OK\r\n" + "Content-Length: 10\r\n" + "\r\n", CharsetUtil.US_ASCII));

    byte[] data = new byte[10];
    for (int i = 0; i < data.length; i++) {
      data[i] = (byte) i;
    }
    ch.writeInbound(Unpooled.wrappedBuffer(data, 0, data.length / 2));
    ch.writeInbound(Unpooled.wrappedBuffer(data, 5, data.length / 2));

    HttpResponse res = ch.readInbound();
    assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1));
    assertThat(res.getStatus(), is(HttpResponseStatus.OK));

    HttpContent firstContent = ch.readInbound();
    assertThat(firstContent.content().readableBytes(), is(5));
    assertEquals(Unpooled.wrappedBuffer(data, 0, 5), firstContent.content());
    firstContent.release();

    LastHttpContent lastContent = ch.readInbound();
    assertEquals(5, lastContent.content().readableBytes());
    assertEquals(Unpooled.wrappedBuffer(data, 5, 5), lastContent.content());
    lastContent.release();

    assertThat(ch.finish(), is(false));
    assertThat(ch.readInbound(), is(nullValue()));
  }
  @Test
  public void testGarbageHeaders() {
    // A response without headers - from https://github.com/netty/netty/issues/2103
    byte[] data =
        ("<html>\r\n"
                + "<head><title>400 Bad Request</title></head>\r\n"
                + "<body bgcolor=\"white\">\r\n"
                + "<center><h1>400 Bad Request</h1></center>\r\n"
                + "<hr><center>nginx/1.1.19</center>\r\n"
                + "</body>\r\n"
                + "</html>\r\n")
            .getBytes();

    EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder());

    ch.writeInbound(Unpooled.wrappedBuffer(data));

    // Garbage input should generate the 999 Unknown response.
    HttpResponse res = ch.readInbound();
    assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_0));
    assertThat(res.getStatus().code(), is(999));
    assertThat(res.getDecoderResult().isFailure(), is(true));
    assertThat(res.getDecoderResult().isFinished(), is(true));
    assertThat(ch.readInbound(), is(nullValue()));

    // More garbage should not generate anything (i.e. the decoder discards anything beyond this
    // point.)
    ch.writeInbound(Unpooled.wrappedBuffer(data));
    assertThat(ch.readInbound(), is(nullValue()));

    // Closing the connection should not generate anything since the protocol has been violated.
    ch.finish();
    assertThat(ch.readInbound(), is(nullValue()));
  }
  @Test
  public void testInvalidCallBeforeInitRequest() throws Exception {
    // Given
    EmbeddedChannel channel = new EmbeddedChannel(new InitRequestHandler());

    CallRequest callRequest = Fixtures.callRequest(0, false, Unpooled.EMPTY_BUFFER);
    channel.writeInbound(callRequest);
    ErrorMessage error = channel.readOutbound();
    assertNotNull(error);
    assertThat(error.getType(), is(ErrorType.FatalProtocolError));

    this.expectedClosedChannelException.expect(ClosedChannelException.class);
    channel.writeOutbound();
  }
  @Test
  public void test() {
    String writeData = "test";
    EmbeddedChannel embeddedChannel = new EmbeddedChannel(new StripDecoder());

    ByteBuf request = Unpooled.wrappedBuffer(writeData.getBytes());
    embeddedChannel.writeInbound(request);

    ByteBuf response = (ByteBuf) embeddedChannel.readOutbound();

    assertEquals("a" + writeData + "a", response.toString(Charset.defaultCharset()));

    embeddedChannel.finish();
  }
  @Test
  public void testMemcachedRequestEncoder() {

    MemcachedRequest request = new MemcachedRequest(Opcode.SET, "key1", "value1");

    EmbeddedChannel channel = new EmbeddedChannel(new MemcachedRequestEncoder());

    Assert.assertTrue(channel.writeOutbound(request));

    ByteBuf encoded = (ByteBuf) channel.readOutbound();

    Assert.assertNotNull(encoded);

    Assert.assertEquals(request.magic(), encoded.readByte() & 0xFF);

    Assert.assertEquals(request.opCode(), encoded.readByte() & 0xFF);

    Assert.assertEquals(4, encoded.readShort());

    Assert.assertEquals((byte) 0x08, encoded.readByte() & 0xFF);

    Assert.assertEquals((byte) 0, encoded.readByte() & 0xFF);

    Assert.assertEquals(0, encoded.readShort());
    // 注意发送端发的什么位模式这里就收什么位模式。
    // 其实这里也要注意,如果传的刚好是0x8000,解析出来也要注意符号的问题。主要要弄清java是怎么补位和截断,然后保证传的位模式不要被误解。

    Assert.assertEquals(4 + 6 + 8, encoded.readInt());

    Assert.assertEquals(request.id(), encoded.readInt());

    Assert.assertEquals(request.cas(), encoded.readLong());

    Assert.assertEquals(request.flags(), encoded.readInt());

    Assert.assertEquals(request.expires(), encoded.readInt());

    byte[] data = new byte[encoded.readableBytes()];

    encoded.readBytes(data);

    Assert.assertEquals((request.key() + request.body()).getBytes(CharsetUtil.UTF_8), data);

    Assert.assertFalse(encoded.isReadable());

    Assert.assertFalse(channel.finish());

    Assert.assertNull(channel.readInbound());
  }
Exemple #30
0
  @Test
  public void testGZIP2() throws Exception {
    ByteBuf data = Unpooled.wrappedBuffer("message".getBytes(CharsetUtil.UTF_8));
    ByteBuf deflatedData = Unpooled.wrappedBuffer(gzip("message"));

    EmbeddedChannel chDecoderGZip = new EmbeddedChannel(createDecoder(ZlibWrapper.GZIP));
    chDecoderGZip.writeInbound(deflatedData.copy());
    assertTrue(chDecoderGZip.finish());
    ByteBuf buf = chDecoderGZip.readInbound();
    assertEquals(buf, data);
    assertNull(chDecoderGZip.readInbound());
    data.release();
    deflatedData.release();
    buf.release();
  }