@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 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 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());
  }
示例#4
0
  private static void testSpdySessionHandlerPing(SpdyVersion version, boolean server) {
    EmbeddedChannel sessionHandler =
        new EmbeddedChannel(
            new SpdySessionHandler(version, server), new EchoHandler(closeSignal, server));

    while (sessionHandler.readOutbound() != null) {
      continue;
    }

    int localStreamId = server ? 1 : 2;
    int remoteStreamId = server ? 2 : 1;

    SpdyPingFrame localPingFrame = new DefaultSpdyPingFrame(localStreamId);
    SpdyPingFrame remotePingFrame = new DefaultSpdyPingFrame(remoteStreamId);

    // Check if session handler returns identical local PINGs
    sessionHandler.writeInbound(localPingFrame);
    assertPing(sessionHandler.readOutbound(), localPingFrame.getId());
    assertNull(sessionHandler.readOutbound());

    // Check if session handler ignores un-initiated remote PINGs
    sessionHandler.writeInbound(remotePingFrame);
    assertNull(sessionHandler.readOutbound());

    sessionHandler.finish();
  }
  @AdviseWith(adviceClasses = NettyUtilAdvice.class)
  @NewEnv(type = NewEnv.Type.CLASSLOADER)
  @Test
  public void testExecute() throws Exception {
    EmbeddedChannel embeddedChannel = NettyTestUtil.createEmptyEmbeddedChannel();

    ChannelPipeline channelPipeline = embeddedChannel.pipeline();

    channelPipeline.addFirst(NettyRPCChannelHandler.NAME, NettyRPCChannelHandler.INSTANCE);

    NettyChannelAttributes.putFabricWorker(
        embeddedChannel,
        0,
        new LocalFabricWorker<Serializable>(
            new EmbeddedProcessChannel<Serializable>(new DefaultNoticeableFuture<Serializable>())));

    ProcessCallableExecutor processCallableExecutor =
        new NettyFabricWorkerProcessCallableExecutor(embeddedChannel, 0, Long.MAX_VALUE);

    NoticeableFuture<Serializable> noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() {
                return StringPool.BLANK;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    Assert.assertEquals(StringPool.BLANK, noticeableFuture.get());

    final ProcessException processException = new ProcessException("");

    noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() throws ProcessException {
                throw processException;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    try {
      noticeableFuture.get();

      Assert.fail();
    } catch (ExecutionException ee) {
      Assert.assertSame(processException, ee.getCause());
    }
  }
  @Test
  public void testExecute() throws Exception {
    EmbeddedChannel embeddedChannel = NettyTestUtil.createEmptyEmbeddedChannel();

    ChannelPipeline channelPipeline = embeddedChannel.pipeline();

    channelPipeline.addFirst(NettyRPCChannelHandler.NAME, NettyRPCChannelHandler.INSTANCE);

    ProcessCallableExecutor processCallableExecutor =
        new NettyFabricAgentProcessCallableExecutor(embeddedChannel);

    NoticeableFuture<Serializable> noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() {
                return StringPool.BLANK;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    Assert.assertEquals(StringPool.BLANK, noticeableFuture.get());

    final ProcessException processException = new ProcessException("");

    noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() throws ProcessException {
                throw processException;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    try {
      noticeableFuture.get();

      Assert.fail();
    } catch (ExecutionException ee) {
      Assert.assertSame(processException, ee.getCause());
    }
  }
示例#7
0
  private static void testSpdySessionHandlerGoAway(SpdyVersion version, boolean server) {
    EmbeddedChannel sessionHandler =
        new EmbeddedChannel(
            new SpdySessionHandler(version, server), new EchoHandler(closeSignal, server));

    while (sessionHandler.readOutbound() != null) {
      continue;
    }

    int localStreamId = server ? 1 : 2;

    SpdySynStreamFrame spdySynStreamFrame =
        new DefaultSpdySynStreamFrame(localStreamId, 0, (byte) 0);
    spdySynStreamFrame.headers().set("Compression", "test");

    SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(localStreamId);
    spdyDataFrame.setLast(true);

    // Send an initial request
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertSynReply(
        sessionHandler.readOutbound(), localStreamId, false, spdySynStreamFrame.headers());
    assertNull(sessionHandler.readOutbound());
    sessionHandler.writeInbound(spdyDataFrame);
    assertDataFrame(sessionHandler.readOutbound(), localStreamId, true);
    assertNull(sessionHandler.readOutbound());

    // Check if session handler sends a GOAWAY frame when closing
    sessionHandler.writeInbound(closeMessage);
    assertGoAway(sessionHandler.readOutbound(), localStreamId);
    assertNull(sessionHandler.readOutbound());
    localStreamId += 2;

    // Check if session handler returns REFUSED_STREAM if it receives
    // SYN_STREAM frames after sending a GOAWAY frame
    spdySynStreamFrame.setStreamId(localStreamId);
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertRstStream(sessionHandler.readOutbound(), localStreamId, SpdyStreamStatus.REFUSED_STREAM);
    assertNull(sessionHandler.readOutbound());

    // Check if session handler ignores Data frames after sending
    // a GOAWAY frame
    spdyDataFrame.setStreamId(localStreamId);
    sessionHandler.writeInbound(spdyDataFrame);
    assertNull(sessionHandler.readOutbound());

    sessionHandler.finish();
  }
示例#8
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();
  }
  @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();
  }
示例#10
0
 @Test
 public void testEncode() {
   byte[] b = new byte[2048];
   new Random().nextBytes(b);
   ch.writeOutbound(b);
   assertThat((ByteBuf) ch.readOutbound(), is(wrappedBuffer(b)));
 }
示例#11
0
  private void testCompressNone(ZlibWrapper encoderWrapper, ZlibWrapper decoderWrapper)
      throws Exception {
    EmbeddedChannel chEncoder = new EmbeddedChannel(createEncoder(encoderWrapper));

    // Closing an encoder channel without writing anything should generate both header and footer.
    assertTrue(chEncoder.finish());

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

    // Decoder should not generate anything at all.
    for (; ; ) {
      ByteBuf buf = chDecoderZlib.readInbound();
      if (buf == null) {
        break;
      }

      buf.release();
      fail("should decode nothing");
    }

    assertFalse(chDecoderZlib.finish());
  }
  @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 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 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));
 }
  @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());
  }
  private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req =
        ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(
                HTTP_1_1,
                HttpMethod.GET,
                "/chat",
                Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(HttpHeaderNames.HOST, "server.example.com");
    req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
    req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    if (subProtocol) {
      new WebSocketServerHandshaker00("ws://example.com/chat", "chat", Integer.MAX_VALUE)
          .handshake(ch, req);
    } else {
      new WebSocketServerHandshaker00("ws://example.com/chat", null, Integer.MAX_VALUE)
          .handshake(ch, req);
    }

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals(
        "ws://example.com/chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION));

    if (subProtocol) {
      Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    } else {
      Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
    }
    LastHttpContent content = ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.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 testOutbound() throws Exception {
    List<Interceptor> interceptors = new ArrayList<>();

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

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

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

    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ChannelDuplexHandler() {
              @Override
              public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                  throws Exception {
                InterceptorChain chain =
                    new InterceptorChain(ctx, interceptors, (ResourceResponse) msg);
                chain.fireOutbound();
              }
            });

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

    channel.writeAndFlush(response);
    ResourceResponse endResponse = (ResourceResponse) channel.readOutbound();

    assertThat(endResponse).isNotNull();
    assertThat(interceptor2.responses()).hasSize(1);
    assertThat(interceptor2.responses()).contains(response);
    assertThat(interceptor1.responses()).hasSize(1);
    assertThat(interceptor1.responses()).contains(response);
  }
  @Test
  public void testCorrelationWithRequestReplacement() throws Exception {

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

    MockInterceptor interceptor1 = new MockInterceptor();
    DefaultInterceptor interceptor2 =
        new DefaultInterceptor() {
          @Override
          public void onInbound(InboundInterceptorContext context) throws Exception {
            ResourceRequest replacement =
                new DefaultResourceRequest.Builder(context.request()).build();
            context.forward(replacement);
          }

          @Override
          public void onOutbound(OutboundInterceptorContext context) throws Exception {
            ResourceResponse replacement =
                new DefaultResourceResponse(context.request(), ResourceResponse.ResponseType.ERROR);
            context.forward(replacement);
          }
        };
    MockInterceptor interceptor3 = new MockInterceptor();

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

    EmbeddedChannel channel =
        new EmbeddedChannel(
            new ChannelDuplexHandler() {
              @Override
              public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                  throws Exception {
                InterceptorChain chain =
                    new InterceptorChain(ctx, interceptors, (ResourceResponse) msg);
                chain.fireOutbound();
              }

              @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(request).isNotSameAs(endRequest);
    assertThat(request.requestId()).isEqualTo(endRequest.requestId());

    ResourceResponse response =
        new DefaultResourceResponse(endRequest, ResourceResponse.ResponseType.READ);
    channel.writeAndFlush(response);
    ResourceResponse endResponse = (ResourceResponse) channel.readOutbound();

    assertThat(response).isNotSameAs(endResponse);
    assertThat(response.inReplyTo()).isNotSameAs(request);
    assertThat(response.requestId()).isEqualTo(request.requestId());
  }
 private static void assertBuffer(EmbeddedChannel channel, ByteBuf buffer) {
   ByteBuf written = channel.readOutbound();
   Assert.assertEquals(buffer, written);
   written.release();
 }
示例#29
0
  private static void testSpdySessionHandler(SpdyVersion version, boolean server) {
    EmbeddedChannel sessionHandler =
        new EmbeddedChannel(
            new SpdySessionHandler(version, server), new EchoHandler(closeSignal, server));

    while (sessionHandler.readOutbound() != null) {
      continue;
    }

    int localStreamId = server ? 1 : 2;
    int remoteStreamId = server ? 2 : 1;

    SpdySynStreamFrame spdySynStreamFrame =
        new DefaultSpdySynStreamFrame(localStreamId, 0, (byte) 0);
    spdySynStreamFrame.headers().set("Compression", "test");

    SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(localStreamId);
    spdyDataFrame.setLast(true);

    // Check if session handler returns INVALID_STREAM if it receives
    // a data frame for a Stream-ID that is not open
    sessionHandler.writeInbound(new DefaultSpdyDataFrame(localStreamId));
    assertRstStream(sessionHandler.readOutbound(), localStreamId, SpdyStreamStatus.INVALID_STREAM);
    assertNull(sessionHandler.readOutbound());

    // Check if session handler returns PROTOCOL_ERROR if it receives
    // a data frame for a Stream-ID before receiving a SYN_REPLY frame
    sessionHandler.writeInbound(new DefaultSpdyDataFrame(remoteStreamId));
    assertRstStream(sessionHandler.readOutbound(), remoteStreamId, SpdyStreamStatus.PROTOCOL_ERROR);
    assertNull(sessionHandler.readOutbound());
    remoteStreamId += 2;

    // Check if session handler returns PROTOCOL_ERROR if it receives
    // multiple SYN_REPLY frames for the same active Stream-ID
    sessionHandler.writeInbound(new DefaultSpdySynReplyFrame(remoteStreamId));
    assertNull(sessionHandler.readOutbound());
    sessionHandler.writeInbound(new DefaultSpdySynReplyFrame(remoteStreamId));
    assertRstStream(sessionHandler.readOutbound(), remoteStreamId, SpdyStreamStatus.STREAM_IN_USE);
    assertNull(sessionHandler.readOutbound());
    remoteStreamId += 2;

    // Check if frame codec correctly compresses/uncompresses headers
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertSynReply(
        sessionHandler.readOutbound(), localStreamId, false, spdySynStreamFrame.headers());
    assertNull(sessionHandler.readOutbound());
    SpdyHeadersFrame spdyHeadersFrame = new DefaultSpdyHeadersFrame(localStreamId);

    spdyHeadersFrame.headers().add("HEADER", "test1");
    spdyHeadersFrame.headers().add("HEADER", "test2");

    sessionHandler.writeInbound(spdyHeadersFrame);
    assertHeaders(sessionHandler.readOutbound(), localStreamId, false, spdyHeadersFrame.headers());
    assertNull(sessionHandler.readOutbound());
    localStreamId += 2;

    // Check if session handler closed the streams using the number
    // of concurrent streams and that it returns REFUSED_STREAM
    // if it receives a SYN_STREAM frame it does not wish to accept
    spdySynStreamFrame.setStreamId(localStreamId);
    spdySynStreamFrame.setLast(true);
    spdySynStreamFrame.setUnidirectional(true);

    sessionHandler.writeInbound(spdySynStreamFrame);
    assertRstStream(sessionHandler.readOutbound(), localStreamId, SpdyStreamStatus.REFUSED_STREAM);
    assertNull(sessionHandler.readOutbound());

    // Check if session handler rejects HEADERS for closed streams
    int testStreamId = spdyDataFrame.getStreamId();
    sessionHandler.writeInbound(spdyDataFrame);
    assertDataFrame(sessionHandler.readOutbound(), testStreamId, spdyDataFrame.isLast());
    assertNull(sessionHandler.readOutbound());
    spdyHeadersFrame.setStreamId(testStreamId);

    sessionHandler.writeInbound(spdyHeadersFrame);
    assertRstStream(sessionHandler.readOutbound(), testStreamId, SpdyStreamStatus.INVALID_STREAM);
    assertNull(sessionHandler.readOutbound());

    // Check if session handler drops active streams if it receives
    // a RST_STREAM frame for that Stream-ID
    sessionHandler.writeInbound(new DefaultSpdyRstStreamFrame(remoteStreamId, 3));
    assertNull(sessionHandler.readOutbound());
    remoteStreamId += 2;

    // Check if session handler honors UNIDIRECTIONAL streams
    spdySynStreamFrame.setLast(false);
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertNull(sessionHandler.readOutbound());
    spdySynStreamFrame.setUnidirectional(false);

    // Check if session handler returns PROTOCOL_ERROR if it receives
    // multiple SYN_STREAM frames for the same active Stream-ID
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertRstStream(sessionHandler.readOutbound(), localStreamId, SpdyStreamStatus.PROTOCOL_ERROR);
    assertNull(sessionHandler.readOutbound());
    localStreamId += 2;

    // Check if session handler returns PROTOCOL_ERROR if it receives
    // a SYN_STREAM frame with an invalid Stream-ID
    spdySynStreamFrame.setStreamId(localStreamId - 1);
    sessionHandler.writeInbound(spdySynStreamFrame);
    assertRstStream(
        sessionHandler.readOutbound(), localStreamId - 1, SpdyStreamStatus.PROTOCOL_ERROR);
    assertNull(sessionHandler.readOutbound());
    spdySynStreamFrame.setStreamId(localStreamId);

    // Check if session handler returns PROTOCOL_ERROR if it receives
    // an invalid HEADERS frame
    spdyHeadersFrame.setStreamId(localStreamId);

    spdyHeadersFrame.setInvalid();
    sessionHandler.writeInbound(spdyHeadersFrame);
    assertRstStream(sessionHandler.readOutbound(), localStreamId, SpdyStreamStatus.PROTOCOL_ERROR);
    assertNull(sessionHandler.readOutbound());

    sessionHandler.finish();
  }
示例#30
0
 @Test
 public void testEncodeOtherType() {
   String str = "Meep!";
   ch.writeOutbound(str);
   assertThat(ch.readOutbound(), is((Object) str));
 }