예제 #1
0
  @Test
  public void testGZIP() throws Exception {
    ByteBuf data = Unpooled.wrappedBuffer("test".getBytes());

    EmbeddedByteChannel chEncoder = new EmbeddedByteChannel(new JZlibEncoder(ZlibWrapper.GZIP));

    chEncoder.writeOutbound(data.copy());
    assertTrue(chEncoder.finish());

    byte[] deflatedData = chEncoder.readOutbound().array();

    EmbeddedByteChannel chDecoderGZip = new EmbeddedByteChannel(new JZlibDecoder(ZlibWrapper.GZIP));

    chDecoderGZip.writeInbound(Unpooled.wrappedBuffer(deflatedData));
    assertTrue(chDecoderGZip.finish());

    assertEquals(data, chDecoderGZip.readInbound());

    EmbeddedByteChannel chDecoderZlibOrNone =
        new EmbeddedByteChannel(new JZlibDecoder(ZlibWrapper.ZLIB_OR_NONE));

    chDecoderZlibOrNone.writeInbound(Unpooled.wrappedBuffer(deflatedData));
    assertTrue(chDecoderZlibOrNone.finish());

    assertEquals(data, chDecoderZlibOrNone.readInbound());
  }
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
   Protocol.DirectionData prot = this.server ? this.protocol.TO_SERVER : this.protocol.TO_CLIENT;
   ByteBuf copy = in.copy();
   try {
     int packetId = DefinedPacket.readVarInt(in);
     DefinedPacket packet = null;
     if (prot.hasPacket(packetId)) {
       packet = prot.createPacket(packetId);
       packet.read(in, prot.getDirection(), this.protocolVersion);
       if (in.readableBytes() != 0) {
         throw new BadPacketException(
             "Did not read all bytes from packet "
                 + packet.getClass()
                 + " "
                 + packetId
                 + " Protocol "
                 + this.protocol
                 + " Direction "
                 + prot);
       }
     } else {
       in.skipBytes(in.readableBytes());
     }
     out.add(new PacketWrapper(packet, copy));
     copy = null;
   } finally {
     if (copy != null) {
       copy.release();
     }
   }
 }
예제 #3
0
  @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();
  }
예제 #4
0
  @Override
  public void createMember(RequestContext ctx, ResourceState state, Responder responder)
      throws Exception {

    if (state instanceof LazyResourceState) {
      LazyResourceState lazyResourceState = (LazyResourceState) state;
      ByteBuf content = lazyResourceState.contentAsByteBuf();
      setScriptFile(content.copy());

      parent.writeSourceFile(this.id(), content.copy());

      responder.resourceCreated(scriptFileResource);
      return;
    }
    responder.invalidRequest("The uploaded script must be a binary javascript file.");
  }
예제 #5
0
  @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();
  }
예제 #6
0
  /**
   * Invokes a handler in a controlled way, allowing it to be tested.
   *
   * @param handler The handler to invoke
   * @return A result object indicating what happened
   * @throws InvocationTimeoutException if the handler takes more than {@link #timeout(int)} seconds
   *     to send a response or call {@code next()} on the context
   */
  public Invocation invoke(Handler handler) throws InvocationTimeoutException {
    Request request = new DefaultRequest(requestHeaders, method, uri, requestBody);

    Registry registry = registryBuilder.build();

    return new DefaultInvocation(
        request, status, responseHeaders, responseBody.copy(), registry, timeout, handler);
  }
 @Override
 public FullBinaryMemcacheResponse copy() {
   ByteBuf extras = getExtras();
   if (extras != null) {
     extras = extras.copy();
   }
   return new DefaultFullBinaryMemcacheResponse(getKey(), extras, content().copy());
 }
예제 #8
0
 @Override
 protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
   // 跳过4个字节
   msg = msg.skipBytes(4);
   // 剔除最后一个字符串 03
   msg = msg.copy(0, msg.readableBytes() - 1);
   // 加进集合中
   out.add(msg.toString(charset));
 }
예제 #9
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();
  }
예제 #10
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();
  }
  // In line encoding of the packet, including discriminator setting
  @Override
  protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out)
      throws Exception {
    ByteBuf buffer = Unpooled.buffer();
    Class<? extends AbstractPacket> clazz = msg.getClass();
    if (!this.packets.contains(msg.getClass())) {
      throw new NullPointerException(
          "No Packet Registered for: " + msg.getClass().getCanonicalName());
    }

    byte discriminator = (byte) this.packets.indexOf(clazz);
    buffer.writeByte(discriminator);
    msg.encodeInto(ctx, buffer);
    FMLProxyPacket proxyPacket =
        new FMLProxyPacket(buffer.copy(), ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
    out.add(proxyPacket);
  }
예제 #12
0
 @Override
 public FileUpload copy() {
   DiskFileUpload upload =
       new DiskFileUpload(
           getName(),
           getFilename(),
           getContentType(),
           getContentTransferEncoding(),
           getCharset(),
           size);
   ByteBuf buf = content();
   if (buf != null) {
     try {
       upload.setContent(buf.copy());
     } catch (IOException e) {
       throw new ChannelException(e);
     }
   }
   return upload;
 }
  @Override
  public boolean applyProtocol(ByteBuf buffer, ChannelPipeline pipeline) {
    boolean isThisProtocol = false;
    int size = buffer.readableBytes();
    byte[] newb = new byte[size];
    buffer.copy().readBytes(newb);
    LOGGER.trace("{}", newb);

    final int opcode = buffer.getUnsignedByte(buffer.readerIndex() + 2);
    final int protocolVersion = buffer.getUnsignedByte(buffer.readerIndex() + 3);
    if (isNadProtocol(opcode, protocolVersion)) {
      pipeline.addLast("framer", createLengthBasedFrameDecoder());
      pipeline.addLast("eventDecoder", eventDecoder);
      pipeline.addLast(LOGIN_HANDLER_NAME, loginHandler);
      pipeline.addLast("lengthFieldPrepender", lengthFieldPrepender);
      pipeline.addLast("eventEncoder", eventEncoder);
      isThisProtocol = true;
    }
    return isThisProtocol;
  }
예제 #14
0
  private void writeToChannel() throws IOException {
    if (closed) {
      throw new IOException("Already closed: " + id);
    }

    chc.writeAndFlush(buf.copy()).addListener(listener);
    buf.clear();

    // if underlying channel is not writable (perhaps because of slow consumer) wait for
    // notification about writable state change
    synchronized (channelWritabilityMonitor) {
      // to prevent spurious wake up
      while (!chc.channel().isWritable()) {
        try {
          channelWritabilityMonitor.wait();
        } catch (InterruptedException e) {
          throw new IOException("Interrupted when waiting for channel writability state change", e);
        }
      }
    }
  }
예제 #15
0
  // make sure we don't return without first releasing the file reference content
  @Override
  public ReturnOption handle(FileDescriptor file, ByteBuf data) {
    if (file == FileDescriptor.FINAL) return this.downstream.handle(file, data);

    ByteBuf in = data;

    if (in != null) {
      while (in.isReadable()) {
        int amt = Math.min(in.readableBytes(), this.size - this.currchunk);

        ByteBuf out = in.copy(in.readerIndex(), amt);

        in.skipBytes(amt);
        this.currchunk += amt;

        boolean eof = (this.currchunk == this.size) || (!in.isReadable() && file.isEof());

        this.nextMessage(out, file, eof);

        if (eof) {
          this.seqnum++;
          this.currchunk = 0;
        }
      }

      in.release();
    } else if (file.isEof()) {
      this.nextMessage(null, file, false);
    }

    // write all messages in the queue
    while (this.outlist.size() > 0) {
      ReturnOption ret = this.downstream.handle(this.outlist.remove(0), this.outbuf.remove(0));

      if (ret != ReturnOption.CONTINUE) return ret;
    }

    return ReturnOption.CONTINUE;
  }
예제 #16
0
 @Override
 public ByteBuf copy(int index, int length) {
   return buf.copy(index, length);
 }
예제 #17
0
 @Override
 public ByteBuf copy() {
   return buf.copy();
 }
예제 #18
0
파일: Buffer.java 프로젝트: hgschmie/vert.x
 /** Returns a copy of the entire Buffer. */
 public Buffer copy() {
   return new Buffer(buffer.copy());
 }
 @Override
 public ByteBuf copy(int var1, int var2) {
   return a.copy(var1, var2);
 }