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

The following examples show how to use io.netty.buffer.ByteBuf#writeChar() . 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: Http2ClientUpgradeCodec.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the current settings for the handler to the Base64-encoded representation used in
 * the HTTP2-Settings upgrade header.
 */
private CharSequence getSettingsHeaderValue(ChannelHandlerContext ctx) {
    ByteBuf buf = null;
    ByteBuf encodedBuf = null;
    try {
        // Get the local settings for the handler.
        Http2Settings settings = connectionHandler.decoder().localSettings();

        // Serialize the payload of the SETTINGS frame.
        int payloadLength = SETTING_ENTRY_LENGTH * settings.size();
        buf = ctx.alloc().buffer(payloadLength);
        for (CharObjectMap.PrimitiveEntry<Long> entry : settings.entries()) {
            buf.writeChar(entry.key());
            buf.writeInt(entry.value().intValue());
        }

        // Base64 encode the payload and then convert to a string for the header.
        encodedBuf = Base64.encode(buf, URL_SAFE);
        return encodedBuf.toString(UTF_8);
    } finally {
        release(buf);
        release(encodedBuf);
    }
}
 
Example 2
Source File: DefaultHttp2FrameWriter.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture writeSettings(ChannelHandlerContext ctx, Http2Settings settings,
        ChannelPromise promise) {
    try {
        checkNotNull(settings, "settings");
        int payloadLength = SETTING_ENTRY_LENGTH * settings.size();
        ByteBuf buf = ctx.alloc().buffer(FRAME_HEADER_LENGTH + settings.size() * SETTING_ENTRY_LENGTH);
        writeFrameHeaderInternal(buf, payloadLength, SETTINGS, new Http2Flags(), 0);
        for (Http2Settings.PrimitiveEntry<Long> entry : settings.entries()) {
            buf.writeChar(entry.key());
            buf.writeInt(entry.value().intValue());
        }
        return ctx.write(buf, promise);
    } catch (Throwable t) {
        return promise.setFailure(t);
    }
}
 
Example 3
Source File: PacketProfile.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, profileType.ordinal());
	if (profileType == ProfileType.PROFILE_MESSAGE) {
		PacketBuffer.writeString(buffer, profileMessage);
	} else if (profileType == ProfileType.ONLINE_STATUS) {
		PacketBuffer.writeVarIntToBuffer(buffer, onlineStatus.ordinal());
	} else if (profileType == ProfileType.DISPLAY_COLOR) {
		buffer.writeChar(displayColor.getCode());
	} else {
		buffer.writeBoolean(show);
	}
}
 
Example 4
Source File: PacketProfile.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public void write(ByteBuf buffer) throws IOException {
	PacketBuffer.writeVarIntToBuffer(buffer, profileType.ordinal());
	if (profileType == ProfileType.PROFILE_MESSAGE) {
		PacketBuffer.writeString(buffer, profileMessage);
	} else if (profileType == ProfileType.ONLINE_STATUS) {
		PacketBuffer.writeVarIntToBuffer(buffer, onlineStatus.ordinal());
	} else if (profileType == ProfileType.DISPLAY_COLOR) {
		buffer.writeChar(displayColor.getCode());
	} else {
		buffer.writeBoolean(show);
	}
}
 
Example 5
Source File: Packet.java    From Clither-Server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static String readUTF16(ByteBuf in) {
       in = in.order(ByteOrder.BIG_ENDIAN);
       ByteBuf buffer = in.alloc().buffer();
       char chr;
       while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
           buffer.writeChar(chr);
       }

       return buffer.toString(Charsets.UTF_16LE);
   }
 
Example 6
Source File: FWEntity.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeSpawnData(ByteBuf buffer) {
	//Write the ID of the entity to client
	String id = wrapped.getID();
	char[] chars = id.toCharArray();
	buffer.writeInt(chars.length);

	for (char c : chars)
		buffer.writeChar(c);
}
 
Example 7
Source File: FWEntity.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeSpawnData(ByteBuf buffer) {
	//Write the ID of the entity to client
	String id = wrapped.getID();
	char[] chars = id.toCharArray();
	buffer.writeInt(chars.length);

	for (char c : chars)
		buffer.writeChar(c);
}
 
Example 8
Source File: FWEntity.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeSpawnData(ByteBuf buffer) {
	//Write the ID of the entity to client
	String id = wrapped.getID();
	char[] chars = id.toCharArray();
	buffer.writeInt(chars.length);

	for (char c : chars)
		buffer.writeChar(c);
}
 
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: Packet.java    From Ogar2-Server with GNU General Public License v3.0 5 votes vote down vote up
public static String readUTF16(ByteBuf in) {
    in = in.order(ByteOrder.BIG_ENDIAN);
    ByteBuf buffer = in.alloc().buffer();
    char chr;
    while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
        buffer.writeChar(chr);
    }

    return buffer.toString(Charsets.UTF_16LE);
}
 
Example 11
Source File: WritePacket.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This is only for LS <-> GS Communication, do not use it for clients!
 * @param buff
 * @param value
 */
public void writeS(ByteBuf buff, String value) {
	if(value == null)
		throw new RuntimeException("Value is null!");
	
	try {
		for (int i = 0; i < value.length(); i++) {
			buff.writeChar(value.charAt(i));
		}
		buff.writeChar('\000');
	}
	catch (Exception e) {
		log.warn("Failed writing string!", e);
	}
}
 
Example 12
Source File: LegacyClientHandler.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
private static ByteBuf encode(String response) {
    ByteBuf buf = Unpooled.buffer();
    buf.writeByte(0xFF);

    char[] chars = response.toCharArray();
    buf.writeShort(chars.length);

    for (char c : chars) {
        buf.writeChar(c);
    }

    return buf;
}
 
Example 13
Source File: AbstractProtocolEncoder.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
@Override
    public void encode(ChannelHandlerContext ctx, T packet, ByteBuf out) throws Exception {
        int packetLength = fixedLength;

        //(2 byte Unsigned) mak total length
        int writerTotalLengthIndex = out.writerIndex();
        out.writerIndex(writerTotalLengthIndex + CHAR_LENGTH);

        //(1 byte Unsigned) packet type
        out.writeByte(packet.getPacketType());

        //(1 byte) packet ack flag
        out.writeByte(packet.getAck());

        //(8 byte) protocol head
        out.writeBytes(versionBytes);

        //Fields
        Map<AsciiString, ByteBuf> fieldMap = packet.getFieldMap();
        int fieldSize = fieldMap == null ? 0 : fieldMap.size();
        //(1 byte Unsigned) Fields size
        out.writeByte(fieldSize);
        if (fieldSize > 0) {
            packetLength += fieldSize * 3;
            for (Map.Entry<AsciiString, ByteBuf> entry : fieldMap.entrySet()) {
                AsciiString key = entry.getKey();
                ByteBuf value = entry.getValue();

                //(key.length byte Unsigned) Fields size
                packetLength += key.length();
                out.writeByte(key.length());
                ByteBufUtil.writeAscii(out,key);

                //(value.length byte Unsigned) Fields size
                packetLength += value.readableBytes();
                out.writeChar(value.readableBytes());
                out.writeBytes(value);
            }
        }

        //Body
        ByteBuf body = packet.getBody();
        if (body.readableBytes() > 0) {
            packetLength += body.readableBytes();
            out.writeBytes(body);
        }

        //Fill total length
        out.setChar(writerTotalLengthIndex, packetLength);

        //retain
//        out.retain();
    }
 
Example 14
Source File: Packet.java    From Clither-Server with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static void writeUTF16(ByteBuf out, String s) {
       out.order(ByteOrder.BIG_ENDIAN).writeBytes(s.getBytes(Charsets.UTF_16LE));
       out.writeChar(0);
   }
 
Example 15
Source File: CompositeMetadataTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
void decodeThreeEntries() {
  // metadata 1: well known
  WellKnownMimeType mimeType1 = WellKnownMimeType.APPLICATION_PDF;
  ByteBuf metadata1 = Unpooled.buffer();
  metadata1.writeCharSequence("abcdefghijkl", CharsetUtil.UTF_8);

  // metadata 2: custom
  String mimeType2 = "application/custom";
  ByteBuf metadata2 = Unpooled.buffer();
  metadata2.writeChar('E');
  metadata2.writeChar('∑');
  metadata2.writeChar('é');
  metadata2.writeBoolean(true);
  metadata2.writeChar('W');

  // metadata 3: reserved but unknown
  byte reserved = 120;
  assertThat(WellKnownMimeType.fromIdentifier(reserved))
      .as("ensure UNKNOWN RESERVED used in test")
      .isSameAs(WellKnownMimeType.UNKNOWN_RESERVED_MIME_TYPE);
  ByteBuf metadata3 = Unpooled.buffer();
  metadata3.writeByte(88);

  CompositeByteBuf compositeMetadataBuffer = ByteBufAllocator.DEFAULT.compositeBuffer();
  CompositeMetadataFlyweight.encodeAndAddMetadata(
      compositeMetadataBuffer, ByteBufAllocator.DEFAULT, mimeType1, metadata1);
  CompositeMetadataFlyweight.encodeAndAddMetadata(
      compositeMetadataBuffer, ByteBufAllocator.DEFAULT, mimeType2, metadata2);
  CompositeMetadataFlyweight.encodeAndAddMetadata(
      compositeMetadataBuffer, ByteBufAllocator.DEFAULT, reserved, metadata3);

  Iterator<Entry> iterator = new CompositeMetadata(compositeMetadataBuffer, true).iterator();

  assertThat(iterator.next())
      .as("entry1")
      .isNotNull()
      .satisfies(
          e ->
              assertThat(e.getMimeType()).as("entry1 mime type").isEqualTo(mimeType1.getString()))
      .satisfies(
          e ->
              assertThat(((WellKnownMimeTypeEntry) e).getType())
                  .as("entry1 mime id")
                  .isEqualTo(WellKnownMimeType.APPLICATION_PDF))
      .satisfies(
          e ->
              assertThat(e.getContent().toString(CharsetUtil.UTF_8))
                  .as("entry1 decoded")
                  .isEqualTo("abcdefghijkl"));

  assertThat(iterator.next())
      .as("entry2")
      .isNotNull()
      .satisfies(e -> assertThat(e.getMimeType()).as("entry2 mime type").isEqualTo(mimeType2))
      .satisfies(
          e -> assertThat(e.getContent()).as("entry2 decoded").isEqualByComparingTo(metadata2));

  assertThat(iterator.next())
      .as("entry3")
      .isNotNull()
      .satisfies(e -> assertThat(e.getMimeType()).as("entry3 mime type").isNull())
      .satisfies(
          e ->
              assertThat(((ReservedMimeTypeEntry) e).getType())
                  .as("entry3 mime id")
                  .isEqualTo(reserved))
      .satisfies(
          e -> assertThat(e.getContent()).as("entry3 decoded").isEqualByComparingTo(metadata3));

  assertThat(iterator.hasNext()).as("has no more than 3 entries").isFalse();
}
 
Example 16
Source File: Packet.java    From Ogar2-Server with GNU General Public License v3.0 4 votes vote down vote up
public static void writeUTF16(ByteBuf out, String s) {
    out.order(ByteOrder.BIG_ENDIAN).writeBytes(s.getBytes(Charsets.UTF_16LE));
    out.writeChar(0);
}