Java Code Examples for io.netty.buffer.ByteBuf#writeCharSequence()

The following examples show how to use io.netty.buffer.ByteBuf#writeCharSequence() . 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: SetCodec.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static ByteBuf encodeSet(ByteBufAllocator alloc, Iterator<? extends CharSequence> iter, CodecContext context) {
    Charset charset = context.getClientCollation().getCharset();
    ByteBuf content = alloc.buffer();

    try {
        // Max size of var int, fill zero to protect memory data.
        VarIntUtils.reserveVarInt(content);

        CharSequence name = iter.next();
        int size = content.writeCharSequence(name, charset);

        while (iter.hasNext()) {
            name = iter.next();
            size += content.writeByte(',').writeCharSequence(name, charset) + 1;
        }

        return VarIntUtils.setReservedVarInt(content, size);
    } catch (Throwable e) {
        content.release();
        throw e;
    }
}
 
Example 2
Source File: BigDecimalCodec.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
static ByteBuf encodeAscii(ByteBufAllocator alloc, String ascii) {
    // Using ASCII, so byte size is string length.
    int size = ascii.length();

    if (size == 0) {
        // It is zero of var int, not terminal.
        return alloc.buffer(Byte.BYTES).writeByte(0);
    }

    ByteBuf buf = alloc.buffer(VarIntUtils.varIntBytes(size) + size);

    try {
        VarIntUtils.writeVarInt(buf, size);
        buf.writeCharSequence(ascii, StandardCharsets.US_ASCII);
        return buf;
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}
 
Example 3
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
private static void textEncode(DataType id, Object value, ByteBuf buff) {
  switch (id) {
    case NUMERIC:
      textEncodeNUMERIC((Number) value, buff);
      break;
    case NUMERIC_ARRAY:
      textEncodeNUMERIC_ARRAY((Number[]) value, buff);
      break;
    case UNKNOWN:
      //default to treating unknown as a string
      buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8);
      break;
    default:
      logger.debug("Data type " + id + " does not support text encoding");
      buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8);
      break;
  }
}
 
Example 4
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
// see https://github.com/rsocket/rsocket-java/issues/858
public void testWorkaround858() {
  ByteBuf buffer = rule.alloc().buffer();
  buffer.writeCharSequence("test", CharsetUtil.UTF_8);

  rule.socket.requestResponse(ByteBufPayload.create(buffer)).subscribe();

  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(rule.alloc(), 1, new RuntimeException("test")));

  Assertions.assertThat(rule.connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> FrameHeaderCodec.frameType(bb) == REQUEST_RESPONSE)
      .matches(ByteBuf::release);

  Assertions.assertThat(rule.socket.isDisposed()).isFalse();

  rule.assertHasNoLeaks();
}
 
Example 5
Source File: ChangeUserCommandCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private void sendChangeUserCommand() {
  ByteBuf packet = allocateBuffer();
  // encode packet header
  int packetStartIdx = packet.writerIndex();
  packet.writeMediumLE(0); // will set payload length later by calculation
  packet.writeByte(sequenceId);

  // encode packet payload
  packet.writeByte(CommandType.COM_CHANGE_USER);
  BufferUtils.writeNullTerminatedString(packet, cmd.username(), StandardCharsets.UTF_8);
  String password = cmd.password();
  if (password.isEmpty()) {
    packet.writeByte(0);
  } else {
    packet.writeByte(password.length());
    packet.writeCharSequence(password, StandardCharsets.UTF_8);
  }
  BufferUtils.writeNullTerminatedString(packet, cmd.database(), StandardCharsets.UTF_8);
  MySQLCollation collation = cmd.collation();
  int collationId = collation.collationId();
  packet.writeShortLE(collationId);

  if ((encoder.clientCapabilitiesFlag & CLIENT_PLUGIN_AUTH) != 0) {
    BufferUtils.writeNullTerminatedString(packet, "mysql_native_password", StandardCharsets.UTF_8);
  }
  if ((encoder.clientCapabilitiesFlag & CLIENT_CONNECT_ATTRS) != 0) {
    Map<String, String> clientConnectionAttributes = cmd.connectionAttributes();
    if (clientConnectionAttributes != null) {
      encodeConnectionAttributes(clientConnectionAttributes, packet);
    }
  }

  // set payload length
  int lenOfPayload = packet.writerIndex() - packetStartIdx - 4;
  packet.setMediumLE(packetStartIdx, lenOfPayload);

  sendPacket(packet, lenOfPayload);
}
 
Example 6
Source File: CommandEncoder.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void writeArgument(ByteBuf out, byte[] arg) {
    out.writeByte(BYTES_PREFIX);
    out.writeCharSequence(Long.toString(arg.length), CharsetUtil.US_ASCII);
    out.writeBytes(CRLF);
    out.writeBytes(arg);
    out.writeBytes(CRLF);
}
 
Example 7
Source File: FluxReceiveTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1016() throws Exception {
	EmbeddedChannel channel = new EmbeddedChannel();

	Connection connection = Connection.from(channel);
	ConnectionObserver observer = (conn, newState) -> {
		if (newState == ConnectionObserver.State.DISCONNECTING) {
			if (conn.channel().isActive() && !conn.isPersistent()) {
				conn.dispose();
			}
		}
	};
	ChannelOperations<?, ?> ops = new ChannelOperations<>(connection, observer);
	ops.bind();

	ByteBuf buffer = channel.alloc().buffer();
	buffer.writeCharSequence("testIssue1016", Charset.defaultCharset());
	ops.inbound.onInboundNext(buffer);

	CountDownLatch latch = new CountDownLatch(1);
	// There is a subscriber, but there is no request for an item
	ops.receive().subscribe(new TestSubscriber(latch));

	ops.onInboundError(new OutOfMemoryError());

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	assertThat(buffer.refCnt()).isEqualTo(0);
}
 
Example 8
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testDropMessage() throws Exception {
	ByteBuf data = ByteBufAllocator.DEFAULT.buffer();
	data.writeCharSequence("test", Charset.defaultCharset());
	doTestDropData(
			(req, res) -> res.header("Content-Length", "0")
			                 .sendObject(data),
			(req, out) -> out);
	assertThat(ReferenceCountUtil.refCnt(data)).isEqualTo(0);
}
 
Example 9
Source File: CompositeMetadataTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
void decodeEntryTooShortForContentLength() {
  ByteBuf fakeEntry = Unpooled.buffer();
  fakeEntry.writeByte(1);
  fakeEntry.writeCharSequence("w", CharsetUtil.US_ASCII);
  NumberUtils.encodeUnsignedMedium(fakeEntry, 456);
  fakeEntry.writeChar('w');
  CompositeMetadata compositeMetadata = new CompositeMetadata(fakeEntry, false);

  assertThatIllegalStateException()
      .isThrownBy(() -> compositeMetadata.iterator().next())
      .withMessage("metadata is malformed");
}
 
Example 10
Source File: CloseWebSocketFrame.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static ByteBuf newBinaryData(int statusCode, String reasonText) {
    if (reasonText == null) {
        reasonText = StringUtil.EMPTY_STRING;
    }

    ByteBuf binaryData = Unpooled.buffer(2 + reasonText.length());
    binaryData.writeShort(statusCode);
    if (!reasonText.isEmpty()) {
        binaryData.writeCharSequence(reasonText, CharsetUtil.UTF_8);
    }

    binaryData.readerIndex(0);
    return binaryData;
}
 
Example 11
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static void binaryEncodeNAME(String value, ByteBuf buff) {
  String s = String.valueOf(value);
  buff.writeCharSequence(s, StandardCharsets.UTF_8);
}
 
Example 12
Source File: HttpObjectEncoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Deprecated
protected static void encodeAscii(String s, ByteBuf buf) {
    buf.writeCharSequence(s, CharsetUtil.US_ASCII);
}
 
Example 13
Source File: Util.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static void writeCString(ByteBuf dst, String s, Charset charset) {
  dst.writeCharSequence(s, charset);
  dst.writeByte(0);
}
 
Example 14
Source File: ConnectionInfoTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void proxyProtocolOn() throws InterruptedException {
	String remoteAddress = "202.112.144.236";
	ArrayBlockingQueue<String> resultQueue = new ArrayBlockingQueue<>(1);

	Consumer<HttpServerRequest> requestConsumer = serverRequest -> {
		String remoteAddrFromRequest = serverRequest.remoteAddress().getHostString();
		resultQueue.add(remoteAddrFromRequest);
	};

	this.connection =
			HttpServer.create()
			          .port(0)
			          .proxyProtocol(ProxyProtocolSupportType.ON)
			          .handle((req, res) -> {
			              try {
			                  requestConsumer.accept(req);
			                  return res.status(200)
			                            .sendString(Mono.just("OK"));
			              }
			              catch (Throwable e) {
			                  return res.status(500)
			                            .sendString(Mono.just(e.getMessage()));
			              }
			          })
			          .wiretap(true)
			          .bindNow();

	Connection clientConn =
			TcpClient.create()
			         .port(this.connection.port())
			         .connectNow();

	ByteBuf proxyProtocolMsg = clientConn.channel()
	                                     .alloc()
	                                     .buffer();
	proxyProtocolMsg.writeCharSequence("PROXY TCP4 " + remoteAddress + " 10.210.12.10 5678 80\r\n",
			Charset.defaultCharset());
	proxyProtocolMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n",
			Charset.defaultCharset());
	clientConn.channel()
	          .writeAndFlush(proxyProtocolMsg)
	          .addListener(f -> {
	              if (!f.isSuccess()) {
	                  fail("Writing proxyProtocolMsg was not successful");
	              }
	          });

	assertThat(resultQueue.poll(5, TimeUnit.SECONDS)).isEqualTo(remoteAddress);

	//send a http request again to confirm that removeAddress is not changed.
	ByteBuf httpMsg = clientConn.channel()
	                            .alloc()
	                            .buffer();
	httpMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n",
			Charset.defaultCharset());
	clientConn.channel()
	          .writeAndFlush(httpMsg)
	          .addListener(f -> {
	              if (!f.isSuccess()) {
	                  fail("Writing proxyProtocolMsg was not successful");
	              }
	          });

	assertThat(resultQueue.poll(5, TimeUnit.SECONDS)).isEqualTo(remoteAddress);
}
 
Example 15
Source File: NettyKt.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int writeUtf8(ByteBuf buf, CharSequence data) {
  return buf.writeCharSequence(data, StandardCharsets.UTF_8);
}
 
Example 16
Source File: ClientPacketEncoder.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
protected void encodeCommandPacket(ClientCommandPacket packet, ByteBuf buf, MysqlCharacterSet characterSet) {
	buf.writeByte(packet.getCommand().getCommandCode());
	if (packet instanceof ClientQueryPacket) {
		buf.writeCharSequence(((ClientQueryPacket) packet).getQuery(), characterSet.getCharset());
	}
}
 
Example 17
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static void binaryEncodeTEXT(String value, ByteBuf buff) {
  String s = String.valueOf(value);
  buff.writeCharSequence(s, StandardCharsets.UTF_8);
}
 
Example 18
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static void binaryEncodeTsQuery(String value, ByteBuf buff) {
  buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8);
}
 
Example 19
Source File: NettyHttpServer.java    From krpc with Apache License 2.0 4 votes vote down vote up
private void writeDynamicContent(ChannelHandlerContext ctx, ChannelPromise promise, DefaultWebRes data) {

        DefaultFullHttpResponse res = null;

        if (data.getContent() != null && !data.getContent().isEmpty()) {

            int size = ByteBufUtil.utf8MaxBytes(data.getContent());
            ByteBuf bb = ctx.alloc().buffer(size);  //  ByteBuf type: io.netty.buffer.PooledUnsafeDirectByteBuf

            bb.writeCharSequence(data.getContent(), Charset.forName(data.getCharSet()));
            int len = bb.readableBytes();
            if (data.isHeadMethod()) {
                res = new DefaultFullHttpResponse(data.getVersion(), HttpResponseStatus.valueOf(data.getHttpCode()));
                ReferenceCountUtil.release(bb);
            } else {
                res = new DefaultFullHttpResponse(data.getVersion(), HttpResponseStatus.valueOf(data.getHttpCode()), bb);
            }
            res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, len);
        } else {
            res = new DefaultFullHttpResponse(data.getVersion(), HttpResponseStatus.valueOf(data.getHttpCode()));
            res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);  // 302 不返回长度会导致客户端卡住
        }
        res.headers().set(HttpHeaderNames.SERVER, WebConstants.Server);

        if (data.isKeepAlive()) {
            res.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
        }

        if (data.getHeaders() != null) {
            for (String key : data.getHeaders().names()) {
                res.headers().set(key, data.getHeaders().get(key));
            }
        }

        if (data.getCookies() != null) {
            for (Cookie c : data.getCookies()) {
                String s = ServerCookieEncoder.STRICT.encode(c);
                res.headers().add(HttpHeaderNames.SET_COOKIE, s);
            }
        }

        ChannelFuture future = ctx.writeAndFlush(res, promise);
        if (!data.isKeepAlive()) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
 
Example 20
Source File: BufferUtils.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static void writeNullTerminatedString(ByteBuf buffer, CharSequence charSequence, Charset charset) {
  buffer.writeCharSequence(charSequence, charset);
  buffer.writeByte(0);
}