Java Code Examples for io.netty.buffer.ByteBufUtil#writeUtf8()

The following examples show how to use io.netty.buffer.ByteBufUtil#writeUtf8() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CommandEncoder.java    From redisson with Apache License 2.0 6 votes vote down vote up
private ByteBuf encode(Object in) {
    if (in instanceof byte[]) {
        return Unpooled.wrappedBuffer((byte[]) in);
    }
    if (in instanceof ByteBuf) {
        return (ByteBuf) in;
    }
    if (in instanceof ChannelName) {
        return Unpooled.wrappedBuffer(((ChannelName) in).getName());
    }

    String payload = in.toString();
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(ByteBufUtil.utf8MaxBytes(payload));
    ByteBufUtil.writeUtf8(buf, payload);
    return buf;
}
 
Example 2
Source File: NettyServerHandler.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private void respondWithHttpError(
    ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {
  Metadata metadata = new Metadata();
  metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
  metadata.put(InternalStatus.MESSAGE_KEY, msg);
  byte[][] serialized = InternalMetadata.serialize(metadata);

  Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2)
      .status("" + code)
      .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8");
  for (int i = 0; i < serialized.length; i += 2) {
    headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
  }
  encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
  ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
  encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}
 
Example 3
Source File: NettyServerHandler.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void respondWithHttpError(
    ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {
  Metadata metadata = new Metadata();
  metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
  metadata.put(InternalStatus.MESSAGE_KEY, msg);
  byte[][] serialized = InternalMetadata.serialize(metadata);

  Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2)
      .status("" + code)
      .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8");
  for (int i = 0; i < serialized.length; i += 2) {
    headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
  }
  encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
  ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
  encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}
 
Example 4
Source File: Http1ClientCodecUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullResponse() throws Exception {
  outputReceived = new CountDownLatch(1);
  ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response");

  FullHttpResponse responseIn = new DefaultFullHttpResponse(HTTP_1_1, OK, body);

  channel.writeInbound(responseIn);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Response responseOut = responses.remove(0);

  assertTrue(responseOut != null);
  assertTrue(responseOut instanceof FullResponse);
  assertEquals("HTTP/1.1", responseOut.version());
  assertEquals(OK, responseOut.status());
  assertTrue(responseOut.hasBody());
  assertFalse(responseOut.body() == null);
  assertEquals(body, responseOut.body());
}
 
Example 5
Source File: WebSocketEntrance.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx,
                                     FullHttpRequest req, FullHttpResponse res) {
    // 返回应答给客户端
    if (res.status().code() != 200) {
        ByteBuf buf = ByteBufUtil.writeUtf8(ctx.alloc(), res.status().toString());
        try {
            res.content().writeBytes(buf);
        } finally {
            buf.release();
        }
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // 如果是非Keep-Alive,关闭连接
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 6
Source File: SmartHomeSkillRequestHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void writeResult(ChannelHandlerContext ctx, FullHttpRequest req, AlexaMessage responseMsg) {
   String json = SerDer.serialize(responseMsg);
   logger.debug("got response {}", json);
   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
   ByteBufUtil.writeUtf8(response.content(), json);
   httpSender.sendHttpResponse(ctx, req, response);
}
 
Example 7
Source File: FileIdOperationEncoder.java    From fastdfs-client with Apache License 2.0 5 votes vote down vote up
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte cmd = cmd();
    int length = FDFS_GROUP_LEN + fileId.pathBytes().length;
    ByteBuf buf = alloc.buffer(length + FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(ERRNO_OK);
    writeFixLength(buf, fileId.group(), FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
 
Example 8
Source File: IrisUpnpServer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void msearch() {
   ByteBuf data = Unpooled.buffer();
   ByteBufUtil.writeUtf8(data, 
      "M-SEARCH * HTTP/1.1\r\n" +
      "HOST: 239.255.255.250:1900\r\n" +
      "MAN: \"ssdp:discover\"\r\n" +
      "MX: 10\r\n" +
      "ST: ssdp:all\r\n" + 
      "USER-AGENT: Iris OS/2.0 UPnP/1.1 Iris/2.0\r\n\r\n"
   );

   log.trace("sending upnp msearch on {}", inet);
   ctx.writeAndFlush(new DatagramPacket(data, remote));
}
 
Example 9
Source File: Http2CodecUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a buffer containing the error message from the given exception. If the cause is
 * {@code null} returns an empty buffer.
 */
public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) {
    if (cause == null || cause.getMessage() == null) {
        return Unpooled.EMPTY_BUFFER;
    }

    return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage());
}
 
Example 10
Source File: RedisEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void writeString(ByteBufAllocator allocator, byte type, String content, List<Object> out) {
    ByteBuf buf = allocator.ioBuffer(RedisConstants.TYPE_LENGTH + ByteBufUtil.utf8MaxBytes(content) +
                                     RedisConstants.EOL_LENGTH);
    buf.writeByte(type);
    ByteBufUtil.writeUtf8(buf, content);
    buf.writeShort(RedisConstants.EOL_SHORT);
    out.add(buf);
}
 
Example 11
Source File: Http2FrameCodecTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static ByteBuf bb(String s) {
    return ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, s);
}
 
Example 12
Source File: ByteBufUtilBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Benchmark
public void writeUtf8Wrapped() {
    wrapped.resetWriterIndex();
    ByteBufUtil.writeUtf8(wrapped, utf8Sequence);
}
 
Example 13
Source File: Http2ServerCodecUnitTest.java    From xio with Apache License 2.0 4 votes vote down vote up
@Test
public void testStreamingRequestWithTrailingHeaders() {
  outputReceived = new CountDownLatch(4);

  Http2Headers headers = new DefaultHttp2Headers().method("POST").path("/");
  Http2Request requestIn = Http2Request.build(1, headers, false);
  ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1");
  Http2Request content = Http2Request.build(1, new DefaultHttp2DataFrame(body1, false), false);
  ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2");
  Http2Request lastContent = Http2Request.build(1, new DefaultHttp2DataFrame(body2, true), false);
  Http2Headers trailers = new DefaultHttp2Headers().set("foo", "bar");
  Http2Request lastHeaders = Http2Request.build(1, trailers, true);

  channel.writeInbound(requestIn);
  channel.writeInbound(content);
  channel.writeInbound(lastContent);
  channel.writeInbound(lastHeaders);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Request requestOut = requests.remove(0);

  assertNotNull(requestOut);
  assertTrue(requestOut instanceof SegmentedRequest);
  assertEquals("h2", requestOut.version());
  assertEquals(HttpMethod.POST, requestOut.method());
  assertEquals("/", requestOut.path());
  assertFalse(requestOut.hasBody());
  assertNotNull(requestOut.body());
  assertEquals(0, requestOut.body().readableBytes());

  Request bodyOut1 = requests.remove(0);

  assertNotNull(bodyOut1);
  assertTrue(bodyOut1 instanceof SegmentedRequestData);
  assertEquals("h2", bodyOut1.version());
  assertEquals(HttpMethod.POST, bodyOut1.method());
  assertEquals("/", bodyOut1.path());
  assertFalse(bodyOut1.hasBody());
  assertNotNull(bodyOut1.body());
  assertNotNull(((SegmentedRequestData) bodyOut1).content());
  assertEquals(body1, ((SegmentedRequestData) bodyOut1).content());
  assertFalse(bodyOut1.endOfMessage());

  Request bodyOut2 = requests.remove(0);

  assertNotNull(bodyOut2);
  assertTrue(bodyOut2 instanceof SegmentedRequestData);
  assertEquals("h2", bodyOut2.version());
  assertEquals(HttpMethod.POST, bodyOut2.method());
  assertEquals("/", bodyOut2.path());
  assertFalse(bodyOut2.hasBody());
  assertNotNull(bodyOut2.body());
  assertNotNull(((SegmentedRequestData) bodyOut2).content());
  assertEquals(body2, ((SegmentedRequestData) bodyOut2).content());
  assertFalse(bodyOut2.endOfMessage());

  Request trailersOut = requests.remove(0);

  assertNotNull(trailersOut);
  assertTrue(trailersOut instanceof SegmentedRequestData);
  assertEquals("h2", trailersOut.version());
  assertEquals(HttpMethod.POST, trailersOut.method());
  assertEquals("/", trailersOut.path());
  assertFalse(trailersOut.hasBody());
  assertNotNull(trailersOut.body());
  assertEquals(0, trailersOut.body().readableBytes());
  assertEquals(1, ((SegmentedRequestData) trailersOut).trailingHeaders().size());
  assertEquals("bar", ((SegmentedRequestData) trailersOut).trailingHeaders().get("foo"));
  assertTrue(trailersOut.endOfMessage());
}
 
Example 14
Source File: ByteBufUtilBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Benchmark
public void writeUtf8StringWrapped() {
    wrapped.resetWriterIndex();
    ByteBufUtil.writeUtf8(wrapped, utf8);
}
 
Example 15
Source File: ByteBufUtilBenchmark.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Benchmark
public void writeUtf8Wrapped() {
    wrapped.resetWriterIndex();
    ByteBufUtil.writeUtf8(wrapped, utf8Sequence);
}
 
Example 16
Source File: Http2ClientCodecUnitTest.java    From xio with Apache License 2.0 4 votes vote down vote up
@Test
public void testStreamingRequest() throws Exception {
  outputReceived = new CountDownLatch(3);

  SegmentedRequest requestIn =
      DefaultSegmentedRequest.builder().method(POST).host("localhost").path("/").build();
  ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1");
  SegmentedData content =
      DefaultSegmentedData.builder().content(body1).endOfMessage(false).build();
  ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2");
  SegmentedData lastContent =
      DefaultSegmentedData.builder()
          .content(body2)
          .endOfMessage(true)
          .trailingHeaders(new DefaultHeaders())
          .build();

  channel.writeOutbound(requestIn);
  channel.writeOutbound(content);
  channel.writeOutbound(lastContent);

  channel.runPendingTasks(); // blocks

  Uninterruptibles.awaitUninterruptibly(outputReceived);

  Http2Request requestOut = (Http2Request) requests.remove(0);

  assertTrue(requestOut != null);
  assertTrue(requestOut.payload instanceof Http2Headers);
  assertEquals("POST", ((Http2Headers) requestOut.payload).method().toString());
  assertEquals("/", ((Http2Headers) requestOut.payload).path());
  assertFalse(requestOut.eos);

  Http2Request bodyOut1 = (Http2Request) requests.remove(0);

  assertTrue(bodyOut1 != null);
  assertTrue(bodyOut1.payload instanceof Http2DataFrame);
  assertFalse(((Http2DataFrame) bodyOut1.payload).content() == null);
  assertEquals(body1, ((Http2DataFrame) bodyOut1.payload).content());
  assertFalse(bodyOut1.eos);

  Http2Request bodyOut2 = (Http2Request) requests.remove(0);

  assertTrue(bodyOut2 != null);
  assertTrue(bodyOut2.payload instanceof Http2DataFrame);
  assertFalse(((Http2DataFrame) bodyOut2.payload).content() == null);
  assertEquals(body2, ((Http2DataFrame) bodyOut2.payload).content());
  assertTrue(bodyOut2.eos);
}
 
Example 17
Source File: ServiceTalkBufferAllocator.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public Buffer fromUtf8(CharSequence data, boolean direct) {
    return data.length() == 0 ? EMPTY_BUFFER : new NettyBuffer<>(ByteBufUtil.writeUtf8(direct ?
            forceDirectAllocator : forceHeapAllocator, data));
}
 
Example 18
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private static ByteBuf bb(String s, Channel c) {
  return ByteBufUtil.writeUtf8(c.alloc(), s);
}
 
Example 19
Source File: NettyBuffer.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public Buffer writeUtf8(CharSequence seq) {
    ByteBufUtil.writeUtf8(buffer, seq);
    return this;
}
 
Example 20
Source File: AWSSignatureVersion4.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
static void writeCanonicalString(
    ClientRequestContext ctx, RequestHeaders headers, HttpData payload, ByteBuf result) {
  // HTTPRequestMethod + '\n' +
  ByteBufUtil.writeUtf8(result, ctx.method().name());
  result.writeByte('\n');

  // CanonicalURI + '\n' +
  // TODO: make this more efficient
  ByteBufUtil.writeUtf8(result,
      ctx.path().replace("*", "%2A").replace(",", "%2C").replace(":", "%3A"));
  result.writeByte('\n');

  // CanonicalQueryString + '\n' +
  String query = ctx.query();
  if (query != null) {
    ByteBufUtil.writeUtf8(result, query);
  }
  result.writeByte('\n');

  // CanonicalHeaders + '\n' +
  ByteBuf signedHeaders = ctx.alloc().buffer();

  writeCanonicalHeaderValue(HOST, host(headers, ctx), signedHeaders, result);
  try {
    for (AsciiString canonicalHeader : OTHER_CANONICAL_HEADERS) {
      String value = headers.get(canonicalHeader);
      if (value != null) {
        writeCanonicalHeaderValue(canonicalHeader, value, signedHeaders, result);
      }
    }
    result.writeByte('\n'); // end headers

    // SignedHeaders + '\n' +
    signedHeaders.readByte(); // throw away the first semicolon
    result.writeBytes(signedHeaders);
  } finally {
    signedHeaders.release();
  }
  result.writeByte('\n');

  // HexEncode(Hash(Payload))
  if (!payload.isEmpty()) {
    ByteBufUtil.writeUtf8(result, ByteBufUtil.hexDump(sha256(payload)));
  } else {
    ByteBufUtil.writeUtf8(result, EMPTY_STRING_HASH);
  }
}