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

The following examples show how to use io.netty.buffer.ByteBuf#writeBytes() . 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: GrpcRequestHandlerTest.java    From xio with Apache License 2.0 6 votes vote down vote up
private ByteBuf bufferFor(
    com.google.protobuf.GeneratedMessageV3 protoObject, boolean compressed) {
  byte[] dataBytes = protoObject.toByteArray();
  int length = dataBytes.length;
  byte[] lengthByteBuffer = ByteBuffer.allocate(4).putInt(length).array();
  int compressedFlag = compressed ? 1 : 0;
  byte[] compressedByteBuffer = ByteBuffer.allocate(1).put((byte) compressedFlag).array();

  ByteBuf grpcRequestBuffer = UnpooledByteBufAllocator.DEFAULT.buffer(length + 5, length + 5);

  grpcRequestBuffer.writeBytes(compressedByteBuffer);
  grpcRequestBuffer.writeBytes(lengthByteBuffer);
  grpcRequestBuffer.writeBytes(dataBytes);

  return grpcRequestBuffer;
}
 
Example 2
Source File: NettyEncoder.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
        throws Exception {
    try {
        ByteBuffer header = remotingCommand.encodeHeader();
        out.writeBytes(header);
        byte[] body = remotingCommand.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    } catch (Exception e) {
        log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        if (remotingCommand != null) {
            log.error(remotingCommand.toString());
        }
        RemotingUtil.closeChannel(ctx.channel());
    }
}
 
Example 3
Source File: AbstractEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@DataPoints("largeData")
public static ByteBuf[] largeData() {
    ByteBuf heap = Unpooled.wrappedBuffer(BYTES_LARGE);
    ByteBuf direct = Unpooled.directBuffer(BYTES_LARGE.length);
    direct.writeBytes(BYTES_LARGE);
    return new ByteBuf[] {heap, direct};
}
 
Example 4
Source File: EvpnNlriParser.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public static void serializeNlri(final List<EvpnDestination> destinationList, final ByteBuf output) {
    ByteBuf nlriOutput = null;
    for (final EvpnDestination dest : destinationList) {
        final ByteBuf nlriCommon = Unpooled.buffer();
        serializeRouteDistinquisher(dest.getRouteDistinguisher(), nlriCommon);
        nlriOutput = SimpleEvpnNlriRegistry.getInstance().serializeEvpn(dest.getEvpnChoice(), nlriCommon);
    }
    output.writeBytes(nlriOutput);
}
 
Example 5
Source File: MoreByteBufUtils.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Ensures the {@code buf} will work with the specified {@code nativeStuff}. After this function
 * is called, you should decrement the reference count on the {@code buf} with
 * {@link ByteBuf#release()}.
 *
 * @param alloc the {@link ByteBufAllocator} to use
 * @param nativeStuff the native we are working with
 * @param buf the buffer we are working with
 * @return a buffer compatible with the native
 */
public static ByteBuf ensureCompatible(ByteBufAllocator alloc, Native nativeStuff, ByteBuf buf) {
  if (!nativeStuff.isNative() || buf.hasMemoryAddress()) {
    // Will always work in either case. JNI code demands a memory address, and if we have a Java
    // fallback, it uses byte arrays in all cases.
    return buf.retain();
  }

  // It's not, so we must make a direct copy.
  ByteBuf newBuf = alloc.directBuffer(buf.readableBytes());
  newBuf.writeBytes(buf);
  return newBuf;
}
 
Example 6
Source File: JoyQueueMapTools.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static void write(final Object object, final ByteBuf out) {
    if (object instanceof Byte) {
        out.writeByte(BYTE_TYPE);
        out.writeByte(((Byte) object).byteValue());
    } else if (object instanceof Short) {
        out.writeByte(SHORT_TYPE);
        out.writeShort(((Short) object).shortValue());
    } else if (object instanceof Integer) {
        out.writeByte(INT_TYPE);
        out.writeInt(((Integer) object).intValue());
    } else if (object instanceof Long) {
        out.writeByte(LONG_TYPE);
        out.writeLong(((Long) object).longValue());
    } else if (object instanceof Double) {
        out.writeByte(DOUBLE_TYPE);
        out.writeDouble((Double) object);
    } else if (object instanceof String) {
        String str = (String) object;
        byte[] bytes = str.getBytes(UTF8);
        int size = bytes.length;
        if (size <= Byte.MAX_VALUE) {
            out.writeByte(STRING_BYTE_TYPE);
            out.writeByte((byte) size);
        } else if (size <= Short.MAX_VALUE) {
            out.writeByte(STRING_SHORT_TYPE);
            out.writeShort((short) size);
        } else if (size <= Integer.MAX_VALUE) {
            out.writeByte(STRING_INT_TYPE);
            out.writeInt(size);
        }
        out.writeBytes(bytes);
    } else {
        throw new RuntimeException("type is illegal:" + object);
    }
}
 
Example 7
Source File: MyServerHandler.java    From krpc with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

	ByteBuf buf = (ByteBuf) msg;
	byte[] bytes = new byte[buf.readableBytes()];
	buf.readBytes(bytes);

	String content = new String(bytes);
	System.out.println("服务端接受到:" + content);

	byte[] res = "world".getBytes();
	ByteBuf time = ctx.alloc().buffer(res.length);
	time.writeBytes(res);
	ctx.writeAndFlush(time);
}
 
Example 8
Source File: BinaryMemcacheDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * This test makes sure that large content is emitted in chunks.
 */
@Test
public void shouldDecodeRequestWithChunkedContent() {
    int smallBatchSize = 2;
    channel = new EmbeddedChannel(new BinaryMemcacheRequestDecoder(smallBatchSize));

    ByteBuf incoming = Unpooled.buffer();
    incoming.writeBytes(SET_REQUEST_WITH_CONTENT);
    channel.writeInbound(incoming);

    BinaryMemcacheRequest request = channel.readInbound();

    assertThat(request, notNullValue());
    assertThat(request.key(), notNullValue());
    assertThat(request.extras(), nullValue());

    assertThat(request.keyLength(), is((short) 3));
    assertThat(request.extrasLength(), is((byte) 0));
    assertThat(request.totalBodyLength(), is(11));

    request.release();

    int expectedContentChunks = 4;
    for (int i = 1; i <= expectedContentChunks; i++) {
        MemcacheContent content = channel.readInbound();
        if (i < expectedContentChunks) {
            assertThat(content, instanceOf(MemcacheContent.class));
        } else {
            assertThat(content, instanceOf(LastMemcacheContent.class));
        }
        assertThat(content.content().readableBytes(), is(2));
        content.release();
    }
    assertThat(channel.readInbound(), nullValue());
}
 
Example 9
Source File: FetchTopicMessageResponseCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(FetchTopicMessageResponse payload, ByteBuf buffer) throws Exception {
    buffer.writeShort(payload.getData().size());
    for (Map.Entry<String, FetchTopicMessageAckData> entry : payload.getData().entrySet()) {
        FetchTopicMessageAckData fetchTopicMessageAckData = entry.getValue();
        Serializer.write(entry.getKey(), buffer, Serializer.SHORT_SIZE);
        buffer.writeShort(fetchTopicMessageAckData.getBuffers().size());
        for (ByteBuffer rByteBuffer : fetchTopicMessageAckData.getBuffers()) {
            buffer.writeBytes(rByteBuffer);
        }
        buffer.writeInt(fetchTopicMessageAckData.getCode().getCode());
    }
}
 
Example 10
Source File: FakeChannelCrypter.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void encrypt(ByteBuf out, List<ByteBuf> plain) throws GeneralSecurityException {
  checkState(!destroyCalled);
  for (ByteBuf buf : plain) {
    out.writeBytes(buf);
    for (int i = 0; i < TAG_BYTES; ++i) {
      out.writeByte(TAG_BYTE);
    }
  }
}
 
Example 11
Source File: NettyEncryptionTranslator.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
protected void cipher(ByteBuf in, ByteBuf out) throws ShortBufferException {
	int i = in.readableBytes();
	byte[] abyte = this.func_150502_a(in);
	int j = this.cipher.getOutputSize(i);

	if (this.field_150506_c.length < j) {
		this.field_150506_c = new byte[j];
	}

	out.writeBytes(this.field_150506_c, 0, this.cipher.update(abyte, 0, i, this.field_150506_c));
}
 
Example 12
Source File: PacketCapeSettings.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void write(ByteBuf buffer) throws IOException {
	PacketBuffer.writeVarIntToBuffer(buffer, action.ordinal());
	if (action == Action.UPLOAD_CUSTOM) {
		buffer.writeBytes(image);
	}
	if (action == Action.UPLOAD_DEFAULT)
		PacketBuffer.writeVarIntToBuffer(buffer, cape.ordinal());
	if (action == Action.SETTINGS)
		buffer.writeBoolean(enabled);
}
 
Example 13
Source File: NettyBsonDocumentWriter.java    From mongowp with Apache License 2.0 4 votes vote down vote up
void writeCString(ByteBuf buf, String str) {
  buf.writeBytes(str.getBytes(Charsets.UTF_8));
  buf.writeByte(0x00);
}
 
Example 14
Source File: Command.java    From hanboDB with Apache License 2.0 4 votes vote down vote up
private static void writeArgument(ByteBuf os, ByteBuf argument) throws IOException {
    os.writeBytes(BYTES_PREFIX);
    os.writeBytes(numToBytes(argument.readableBytes(), true));
    os.writeBytes(argument);
    os.writeBytes(CRLF);
}
 
Example 15
Source File: BedrockUtils.java    From Protocol with Apache License 2.0 4 votes vote down vote up
public static void writeByteArray(ByteBuf buffer, byte[] bytes) {
    Preconditions.checkNotNull(buffer, "buffer");
    Preconditions.checkNotNull(bytes, "bytes");
    VarInts.writeUnsignedInt(buffer, bytes.length);
    buffer.writeBytes(bytes);
}
 
Example 16
Source File: ByteOutputContext.java    From nemo with Apache License 2.0 4 votes vote down vote up
@Override
public void write(final byte[] bytes, final int offset, final int length) throws IOException {
  final ByteBuf byteBuf = channel.alloc().ioBuffer(length, length);
  byteBuf.writeBytes(bytes, offset, length);
  writeByteBuf(byteBuf);
}
 
Example 17
Source File: PreparedExecuteMessage.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
@Override
protected Publisher<ByteBuf> fragments(ByteBufAllocator allocator, ConnectionContext context) {
    int size = values.length;
    ByteBuf buf;

    if (size == 0) {
        buf = allocator.buffer(NO_PARAM_SIZE, NO_PARAM_SIZE);
    } else {
        buf = allocator.buffer();
    }

    try {
        buf.writeByte(EXECUTE_FLAG)
            .writeIntLE(statementId)
            .writeByte(immediate ? NO_CURSOR : READ_ONLY)
            .writeIntLE(TIMES);

        if (size == 0) {
            return Mono.just(buf);
        }

        List<Parameter> nonNull = new ArrayList<>(size);
        byte[] nullMap = fillNullBitmap(size, nonNull);

        // Fill null-bitmap.
        buf.writeBytes(nullMap);

        if (nonNull.isEmpty()) {
            // No need rebound.
            buf.writeBoolean(false);
            return Mono.just(buf);
        }

        buf.writeBoolean(true);
        writeTypes(buf, size);

        Flux<ByteBuf> parameters = OperatorUtils.discardOnCancel(Flux.fromArray(values))
            .doOnDiscard(Parameter.class, DISPOSE)
            .concatMap(Parameter::publishBinary);

        return Flux.just(buf).concatWith(parameters);
    } catch (Throwable e) {
        buf.release();
        cancelParameters();
        return Mono.error(e);
    }
}
 
Example 18
Source File: AttributesObjectParser.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
static void serializeFlag(final List<FlagContainer> flagList, final ByteBuf bufferAux) {
    for (final FlagContainer flagContainer : flagList) {
        bufferAux.writeBytes(flagContainer.getFlags());
    }
}
 
Example 19
Source File: ByteArrayType.java    From ViaVersion with MIT License 4 votes vote down vote up
@Override
public void write(ByteBuf buffer, byte[] object) throws Exception {
    Type.VAR_INT.writePrimitive(buffer, object.length);
    buffer.writeBytes(object);
}
 
Example 20
Source File: StringSerializer.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void writeShortUTF16BEString(ByteBuf buf, String string) {
	buf.writeShort(string.length());
	buf.writeBytes(string.getBytes(StandardCharsets.UTF_16BE));
}