@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());
  }
 private static void processGoAwayWriteResult(
     final ChannelHandlerContext ctx,
     final int lastStreamId,
     final long errorCode,
     final ByteBuf debugData,
     ChannelFuture future) {
   try {
     if (future.isSuccess()) {
       if (errorCode != NO_ERROR.code()) {
         if (logger.isDebugEnabled()) {
           logger.debug(
               format(
                   "Sent GOAWAY: lastStreamId '%d', errorCode '%d', "
                       + "debugData '%s'. Forcing shutdown of the connection.",
                   lastStreamId, errorCode, debugData.toString(UTF_8)),
               future.cause());
         }
         ctx.close();
       }
     } else {
       if (logger.isErrorEnabled()) {
         logger.error(
             format(
                 "Sending GOAWAY failed: lastStreamId '%d', errorCode '%d', "
                     + "debugData '%s'. Forcing shutdown of the connection.",
                 lastStreamId, errorCode, debugData.toString(UTF_8)),
             future.cause());
       }
       ctx.close();
     }
   } finally {
     // We're done with the debug data now.
     debugData.release();
   }
 }
  @Override
  protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, PacketsMessage message)
      throws Exception {
    ByteBuf content = message.getContent();
    MainBaseClient client = message.getClient();

    if (log.isTraceEnabled()) {
      log.trace(
          "In message: {} sessionId: {}",
          content.toString(CharsetUtil.UTF_8),
          client.getSessionId());
    }
    while (content.isReadable()) {
      try {
        Packet packet = decoder.decodePackets(content, client.getSessionId());
        Namespace ns = namespacesHub.get(packet.getEndpoint());
        if (ns == null) {
          log.debug(
              "Can't find namespace for endpoint: {}, sessionId: {} probably it was removed.",
              packet.getEndpoint(),
              client.getSessionId());
          return;
        }

        if (packet.getType() == PacketType.CONNECT) {
          client.addChildClient(ns);
        }

        NamespaceClient nClient = (NamespaceClient) client.getChildClient(ns);
        if (nClient == null) {
          log.debug(
              "Can't find namespace client in namespace: {}, sessionId: {} probably it was disconnected.",
              ns.getName(),
              client.getSessionId());
          return;
        }
        packetListener.onPacket(packet, nClient);
      } catch (Exception ex) {
        String c = content.toString(CharsetUtil.UTF_8);
        log.error(
            "Error during data processing. Client sessionId: "
                + client.getSessionId()
                + ", data: "
                + c,
            ex);
        return;
      }
    }
  }
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) {
   ByteBuf readMessage = (ByteBuf) msg;
   System.out.println("channelRead : " + readMessage.toString(Charset.defaultCharset()));
   //        ctx.writeAndFlush(msg);
   ctx.write(msg);
 }
 @Override
 public void updateResponse(HttpServerResponse<O> response, Throwable error) {
   response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
   response.getHeaders().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
   ByteBuf buffer =
       response.getChannelHandlerContext().alloc().buffer(1024); // 1KB initial length.
   PrintStream printStream = null;
   try {
     printStream = new PrintStream(new ByteBufOutputStream(buffer));
     error.printStackTrace(printStream);
     String errorPage =
         ERROR_HTML_TEMPLATE.replace(
             STACKTRACE_TEMPLATE_VARIABLE, buffer.toString(Charset.defaultCharset()));
     response.writeString(errorPage);
   } finally {
     ReferenceCountUtil.release(buffer);
     if (null != printStream) {
       try {
         printStream.flush();
         printStream.close();
       } catch (Exception e) {
         logger.error(
             "Error closing stream for generating error response stacktrace. This is harmless.",
             e);
       }
     }
   }
 }
 /** Creates a client-side handler. */
 public EchoClientHandler() {
   firstMessage = Unpooled.buffer(EchoClient.SIZE);
   for (int i = 0; i < firstMessage.capacity(); i++) {
     firstMessage.writeByte((byte) i);
   }
   System.out.println(firstMessage.toString());
 }
 @Test
 public void testEncode() throws IOException {
   Packet packet = new Packet(PacketType.ACK);
   packet.setAckId(140L);
   ByteBuf result = Unpooled.buffer();
   //        encoder.encodePacket(packet, result);
   Assert.assertEquals("6:::140", result.toString(CharsetUtil.UTF_8));
 }
Example #8
0
 @Override
 public String getBodyText() {
   if (sentResponse) {
     body.resetReaderIndex();
     return body.toString(CharsetUtil.UTF_8);
   } else {
     return null;
   }
 }
Example #9
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));
 }
 @Test
 public void testEncodeWithArgs() throws IOException {
   Packet packet = new Packet(PacketType.ACK);
   packet.setAckId(12L);
   //        packet.setArgs(Arrays.<Object>asList("woot", "wa"));
   ByteBuf result = Unpooled.buffer();
   //        encoder.encodePacket(packet, result);
   Assert.assertEquals("6:::12+[\"woot\",\"wa\"]", result.toString(CharsetUtil.UTF_8));
 }
 private void readAltSvcFrame(
     ChannelHandlerContext ctx, ByteBuf payload, Http2FrameObserver observer)
     throws Http2Exception {
   long maxAge = payload.readUnsignedInt();
   int port = payload.readUnsignedShort();
   payload.skipBytes(1);
   short protocolIdLength = payload.readUnsignedByte();
   ByteBuf protocolId = payload.readSlice(protocolIdLength);
   short hostLength = payload.readUnsignedByte();
   String host = payload.toString(payload.readerIndex(), hostLength, UTF_8);
   payload.skipBytes(hostLength);
   String origin = null;
   if (payload.isReadable()) {
     origin = payload.toString(UTF_8);
     payload.skipBytes(payload.readableBytes());
   }
   observer.onAltSvcRead(ctx, streamId, maxAge, port, protocolId, host, origin);
 }
Example #12
0
 @Override
 public String getString(Charset encoding) {
   if (byteBuf == null) {
     return "";
   }
   if (encoding == null) {
     encoding = HttpConstants.DEFAULT_CHARSET;
   }
   return byteBuf.toString(encoding);
 }
  private void checkMessage(final ByteBuf buffer) {
    final String message = buffer.toString(Charset.forName("US-ASCII"));

    final Matcher msgMatch = REGEX.matcher(message);

    if (msgMatch.matches()) {
      setup(msgMatch.group(1), msgMatch.group(2));
    } else {
      invalidate();
    }
  }
Example #14
0
 @Override
 public String toString() {
   return "QueueMessage{"
       + "uuid="
       + uuid
       + ", type="
       + type
       + ", buffer="
       + buffer.toString(defaultCharset)
       + '}';
 }
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;

    try {
      System.out.print(in.toString(CharsetUtil.US_ASCII));
      System.out.flush();
    } finally {
      in.release();
    }
  }
Example #16
0
  public QueryRequest(ByteBuf buffer) {
    super(buffer, kXR_query);
    reqcode = buffer.getUnsignedShort(4);
    fhandle = buffer.getInt(8);
    int alen = buffer.getInt(20);

    /* The protocol spec doesn't state anything about trailing zeros in args,
     * however the xrdfs client sends zero terminated paths.
     */
    args = NULL_CHARACTER.trimTrailingFrom(buffer.toString(24, alen, US_ASCII));
  }
 @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));
 }
Example #18
0
 /**
  * Returns a decoded TXT (text) resource record, stored as an {@link java.util.ArrayList} of
  * {@code String}s.
  *
  * @param response the DNS response that contains the resource record being decoded
  * @param resource the resource record being decoded
  */
 @Override
 public List<String> decode(DnsResponse response, DnsResource resource) {
   List<String> list = new ArrayList<String>();
   ByteBuf data = resource.content().readerIndex(response.originalIndex());
   int index = data.readerIndex();
   while (index < data.writerIndex()) {
     int len = data.getUnsignedByte(index++);
     list.add(data.toString(index, len, CharsetUtil.UTF_8));
     index += len;
   }
   return list;
 }
  /**
   * Read a string that is prefixed by its length encoded by a 4 bytes integer.
   *
   * @param in the buffer to consume
   * @return the read string or {@code null} if not enough data available to read the whole string
   */
  private String readLengthPrefixedString(ByteBuf in) {
    if (!in.isReadable(INT_LENGTH)) {
      return null;
    }
    int length = in.readInt();
    if (!in.isReadable(length)) {
      return null;
    }

    String str = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
    in.skipBytes(length);
    return str;
  }
Example #20
0
 /**
  * Read a string from a channel buffer with the specified length. It resets the reader index of
  * the buffer to the end of the string. Defaults to UTF-8 encoding in case charset passed in is
  * null
  *
  * @param buffer The Netty buffer containing the String.
  * @param length The number of bytes in the String.
  * @param charset The Charset say 'UTF-8' in which the decoding needs to be done.
  * @return Returns the read string.
  */
 public static String readString(ByteBuf buffer, int length, Charset charset) {
   String str = null;
   if (null == charset) {
     charset = CharsetUtil.UTF_8;
   }
   try {
     ByteBuf stringBuffer = buffer.readSlice(length);
     str = stringBuffer.toString(charset);
   } catch (Exception e) {
     LOG.error("Error occurred while trying to read string from buffer: {}", e);
   }
   return str;
 }
Example #21
0
 private void getParams() {
   if (request.method() == HttpMethod.GET) {
     params = null;
   } else if (request.method() == HttpMethod.POST) {
     ByteBuf content = request.content();
     if (content.isReadable()) {
       String param = content.toString(WaarpStringUtils.UTF8);
       QueryStringDecoder queryStringDecoder2 = new QueryStringDecoder("/?" + param);
       params = queryStringDecoder2.parameters();
     } else {
       params = null;
     }
   }
 }
  @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 testCacheKeyTemplates() {
    HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("test").build();

    HttpRequestTemplate<ByteBuf> template =
        group
            .newTemplateBuilder("testCacheKeyTemplates", ByteBuf.class)
            .withUriTemplate("/foo/{id}")
            .withMethod("GET")
            .withCacheProvider("/cache/{id}", new FakeCacheProvider("/cache/5"))
            .build();

    RibbonRequest<ByteBuf> request = template.requestBuilder().withRequestProperty("id", 5).build();
    ByteBuf result = request.execute();
    assertEquals("/cache/5", result.toString(Charset.defaultCharset()));
  }
Example #24
0
  @Override
  public void decodeInto(ChannelHandlerContext context, ByteBuf buffer) {
    this.type = EnumSimplePacket.values()[buffer.readInt()];

    try {
      if (this.type.getDecodeClasses().length > 0) {
        this.data = NetworkUtil.decodeData(this.type.getDecodeClasses(), buffer);
      }
    } catch (Exception e) {
      System.err.println(
          "[Galacticraft] Error handling simple packet type: "
              + this.type.toString()
              + " "
              + buffer.toString());
      e.printStackTrace();
    }
  }
Example #25
0
 @Override
 public void toXStream(XStreamBuilder builder) throws IOException {
   builder.writeStartObject();
   if (uuid != null) {
     builder.writeStringField("uuid", uuid.toString());
   }
   if (buffer != null) {
     buffer.resetReaderIndex();
     if (getMessageType() == QueueMessageType.STRING) {
       builder.writeFieldName("message");
       builder.writeString(buffer.toString(defaultCharset));
     } else if (getMessageType() == QueueMessageType.JSON) {
       builder.writeRawField("message", buffer);
     }
   }
   builder.writeEndObject();
 }
Example #26
0
  @Test
  public void testHuffmanDecode() throws Exception {
    final String expected = "https://www.example.com";

    final byte[] encoded =
        TestUtil.bytes(
            0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82,
            0xae, 0x43, 0xd3);

    final ByteBuf in = Unpooled.wrappedBuffer(encoded);
    final ByteBuf out = Unpooled.buffer();

    Huffman.decode(in, out);

    final String decoded = out.toString(US_ASCII);
    assertThat(decoded, is(expected));
  }
  private void sendMessage(
      HttpMessage msg, Channel channel, ByteBuf out, HttpResponse res, ChannelPromise promise) {
    channel.write(res);

    if (log.isTraceEnabled()) {
      log.trace(
          "Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
    }

    if (out.isReadable()) {
      channel.write(out);
    } else {
      out.release();
    }

    channel
        .writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, promise)
        .addListener(ChannelFutureListener.CLOSE);
  }
Example #28
0
  private void addFaviconToStatusResponse(ServerStatusResponse response) {
    File var2 = this.getFile("server-icon.png");

    if (var2.isFile()) {
      ByteBuf var3 = Unpooled.buffer();

      try {
        BufferedImage var4 = ImageIO.read(var2);
        Validate.validState(var4.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
        Validate.validState(var4.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
        ImageIO.write(var4, "PNG", new ByteBufOutputStream(var3));
        ByteBuf var5 = Base64.encode(var3);
        response.setFavicon("data:image/png;base64," + var5.toString(Charsets.UTF_8));
      } catch (Exception var9) {
        logger.error("Couldn\'t load server icon", var9);
      } finally {
        var3.release();
      }
    }
  }
  private void handleWebsocket(
      final OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise)
      throws IOException {
    while (true) {
      Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
      Packet packet = queue.poll();
      if (packet == null) {
        promise.setSuccess();
        break;
      }

      final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
      encoder.encodePacket(packet, out, ctx.alloc(), true);

      WebSocketFrame res = new TextWebSocketFrame(out);
      if (log.isTraceEnabled()) {
        log.trace(
            "Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
      }

      if (out.isReadable()) {
        ctx.channel().writeAndFlush(res, promise);
      } else {
        promise.setSuccess();
        out.release();
      }

      for (ByteBuf buf : packet.getAttachments()) {
        ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
        outBuf.writeByte(4);
        outBuf.writeBytes(buf);
        if (log.isTraceEnabled()) {
          log.trace(
              "Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
        }
        ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
      }
    }
  }
Example #30
0
  private void a(ServerPing serverping) {
    File file = this.d("server-icon.png");

    if (file.isFile()) {
      ByteBuf bytebuf = Unpooled.buffer();

      try {
        BufferedImage bufferedimage = ImageIO.read(file);

        Validate.validState(
            bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
        Validate.validState(
            bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
        ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf));
        ByteBuf bytebuf1 = Base64.encode(bytebuf);

        serverping.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
      } catch (Exception exception) {
        MinecraftServer.LOGGER.error("Couldn\'t load server icon", exception);
      } finally {
        bytebuf.release();
      }
    }
  }