@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 testEncode() {
   byte[] b = new byte[2048];
   new Random().nextBytes(b);
   ch.writeOutbound(b);
   assertThat((ByteBuf) ch.readOutbound(), is(wrappedBuffer(b)));
 }
  @Test
  public void testCompatibleExtensionTogetherSuccess() {
    // 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.RSV2).anyTimes();
    expect(fallbackExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("fallback", Collections.<String, String>emptyMap()))
        .once();
    expect(fallbackExtensionMock.newExtensionEncoder()).andReturn(new Dummy2Encoder()).once();
    expect(fallbackExtensionMock.newExtensionDecoder()).andReturn(new Dummy2Decoder()).once();
    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(2, resExts.size());
    assertEquals("main", resExts.get(0).name());
    assertEquals("fallback", resExts.get(1).name());
    assertNotNull(ch.pipeline().get(DummyDecoder.class));
    assertNotNull(ch.pipeline().get(DummyEncoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Decoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Encoder.class));
  }
  @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 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 testInitHandlerRemovesItself() throws Exception {

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

    assertEquals(3, channel.pipeline().names().size());

    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());

    // Assert Pipeline is empty
    assertEquals(2, channel.pipeline().names().size());

    // Make sure Messages are still passed through
    channel.writeInbound(initRequest);
    channel.writeOutbound(channel.readInbound());
    InitRequest sameInitRequest = channel.readOutbound();
    assertEquals(initRequest.getId(), sameInitRequest.getId());
    assertEquals(initRequest.getVersion(), sameInitRequest.getVersion());
    assertEquals(initRequest.getHostPort(), sameInitRequest.getHostPort());
  }
  @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());
    }
  }
  @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 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());
  }
Example #11
0
  private void testCompress0(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper, ByteBuf data)
      throws Exception {
    EmbeddedChannel chEncoder = new EmbeddedChannel(createEncoder(encoderWrapper));

    chEncoder.writeOutbound(data.copy());
    chEncoder.flush();

    EmbeddedChannel chDecoderZlib = new EmbeddedChannel(createDecoder(decoderWrapper));
    for (; ; ) {
      ByteBuf deflatedData = chEncoder.readOutbound();
      if (deflatedData == null) {
        break;
      }
      chDecoderZlib.writeInbound(deflatedData);
    }

    byte[] decompressed = new byte[data.readableBytes()];
    int offset = 0;
    for (; ; ) {
      ByteBuf buf = chDecoderZlib.readInbound();
      if (buf == null) {
        break;
      }
      int length = buf.readableBytes();
      buf.readBytes(decompressed, offset, length);
      offset += length;
      buf.release();
      if (offset == decompressed.length) {
        break;
      }
    }
    assertEquals(data, Unpooled.wrappedBuffer(decompressed));
    assertNull(chDecoderZlib.readInbound());

    // Closing an encoder channel will generate a footer.
    assertTrue(chEncoder.finish());
    for (; ; ) {
      Object msg = chEncoder.readOutbound();
      if (msg == null) {
        break;
      }
      ReferenceCountUtil.release(msg);
    }
    // But, the footer will be decoded into nothing. It's only for validation.
    assertFalse(chDecoderZlib.finish());

    data.release();
  }
  private static void assertWriteFails(ChannelHandler handler, int count) {
    final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.US_ASCII);
    final EmbeddedChannel channel = new EmbeddedChannel(handler);
    ByteBuf[] buffers = new ByteBuf[count];
    for (int i = 0; i < buffers.length; i++) {
      buffers[i] = buffer.duplicate().retain();
    }
    try {
      Assert.assertFalse(channel.writeOutbound(buffers));
      Assert.fail();
    } catch (Exception e) {
      Assert.assertTrue(e instanceof TestException);
    }
    Assert.assertFalse(channel.finish());
    channel.closeFuture().syncUninterruptibly();

    buffer.release();
    Assert.assertNull(channel.readOutbound());
  }
 @Test
 public void verifyAMF3BinaryEncodingAndDecoding() throws InterruptedException {
   EmbeddedChannel outChannel =
       new EmbeddedChannel(
           amf3Protocol.getLengthFieldPrepender(), amf3Protocol.getJavaObjectToAMF3Encoder());
   EmbeddedChannel inChannel =
       new EmbeddedChannel(frameDecoder, amf3Protocol.createAMF3ToJavaObjectDecoder());
   Event event = Events.event(playerStats, Events.SESSION_MESSAGE);
   outChannel.writeOutbound(event);
   assertTrue(outChannel.finish());
   ByteBuf buffer = (ByteBuf) outChannel.readOutbound();
   assertNotNull(buffer);
   inChannel.writeInbound(buffer);
   // assertTrue(inChannel.finish());
   //		Event decoded = (Event)inChannel.readInbound();
   //		assertTrue(decoded.getType() == Events.SESSION_MESSAGE);
   //		PlayerStats playerStats = (PlayerStats) decoded.getSource();
   //		assertEquals(playerStats, this.playerStats);
 }
  private static void assertWrite(ChannelHandler handler, int count) {
    final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.US_ASCII);
    final EmbeddedChannel channel = new EmbeddedChannel(handler);
    channel.config().setWriteBufferLowWaterMark(1);
    channel.config().setWriteBufferHighWaterMark(3);

    ByteBuf[] buffers = new ByteBuf[count];
    for (int i = 0; i < buffers.length; i++) {
      buffers[i] = buffer.duplicate().retain();
    }
    Assert.assertTrue(channel.writeOutbound(buffers));
    Assert.assertTrue(channel.finish());
    channel.closeFuture().syncUninterruptibly();

    for (int i = 0; i < buffers.length; i++) {
      assertBuffer(channel, buffer);
    }
    buffer.release();
    Assert.assertNull(channel.readOutbound());
  }
 @Test
 public void testEncodeOtherType() {
   String str = "Meep!";
   ch.writeOutbound(str);
   assertThat(ch.readOutbound(), is((Object) str));
 }
 @Test
 public void testEncodeEmpty() {
   ch.writeOutbound(EmptyArrays.EMPTY_BYTES);
   assertThat((ByteBuf) ch.readOutbound(), is(Unpooled.EMPTY_BUFFER));
 }