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

The following examples show how to use io.netty.buffer.ByteBuf#writeShort() . 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: LispNonceLcafAddress.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(ByteBuf byteBuf, LispNonceLcafAddress address)
                                            throws LispWriterException {
    int lcafIndex = byteBuf.writerIndex();
    LispLcafAddress.serializeCommon(byteBuf, address);

    // reserved field
    byteBuf.writeByte(UNUSED_ZERO);

    // nonce field
    int nonceFirst = address.getNonce() >> NONCE_SHIFT_BIT;
    byteBuf.writeShort((short) nonceFirst);
    int nonceSecond = address.getNonce() - (nonceFirst << NONCE_SHIFT_BIT);
    byteBuf.writeInt(nonceSecond);

    // address
    AfiAddressWriter writer = new AfiAddressWriter();
    writer.writeTo(byteBuf, address.getAddress());

    LispLcafAddress.updateLength(lcafIndex, byteBuf);
}
 
Example 2
Source File: ZclDataUtil.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static void writeByteString(ByteBuf output, Object value, int lengthBytes) throws IOException {
   if (value == NONE && lengthBytes == 1) { output.writeByte(0xFF); return; }
   if (value == NONE && lengthBytes == 2) { output.writeShort(0xFFFF); return; }

   byte[] array = (byte[])value;
   int length = array.length;
   if (lengthBytes == 2 && length > 0xFE) {
      log.warn("zigbee byte string too long, truncating");
      length = 0xFE;
   }

   if (lengthBytes == 1 && length > 0xFFFE) {
      log.warn("zigbee byte string too long, truncating");
      length = 0xFFFE;
   }

   if (lengthBytes == 1) {
      output.writeByte(length);
   } else {
      output.writeShort(length);
   }

   output.writeBytes(array, 0, length);
}
 
Example 3
Source File: GeneralFrame.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
public ByteBuf write(ByteBufAllocator out) {
    long payloadSize = getPayloadSize();
    long totalSize = payloadSize + 1 + 2 + 4;
    ByteBuf buf = out.buffer((int) totalSize);

    buf.writeByte(type);
    buf.writeShort(channel);
    buf.writeInt((int) payloadSize);

    writePayload(buf);

    buf.writeByte(FRAME_END);

    return buf;
}
 
Example 4
Source File: ModbusRequestEncoder.java    From modbus with Apache License 2.0 5 votes vote down vote up
public ByteBuf encodeWriteMultipleCoils(WriteMultipleCoilsRequest request, ByteBuf buffer) {
    buffer.writeByte(request.getFunctionCode().getCode());
    buffer.writeShort(request.getAddress());
    buffer.writeShort(request.getQuantity());

    int byteCount = (request.getQuantity() + 7) / 8;
    buffer.writeByte(byteCount);

    buffer.writeBytes(request.getValues(), byteCount);

    return buffer;
}
 
Example 5
Source File: RangeTlvParser.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public static void serializeSrRange(final SrRange srRange, final ByteBuf aggregator) {
    final BitArray flags = new BitArray(FLAGS_SIZE);
    flags.set(INNER_AREA, srRange.isInterArea());
    flags.toByteBuf(aggregator);
    aggregator.writeZero(RESERVED);
    aggregator.writeShort(srRange.getRangeSize().toJava());
    serializeSubTlvs(aggregator, srRange.getSubTlvs());
}
 
Example 6
Source File: CodecUtils.java    From tchannel-java with MIT License 5 votes vote down vote up
public static int writeArg(
    @NotNull ByteBufAllocator allocator,
    @NotNull ByteBuf arg,
    int writableBytes,
    @NotNull List<ByteBuf> bufs,
    @NotNull List<ByteBuf> allocatedBufs
) {
    if (writableBytes <= TFrame.FRAME_SIZE_LENGTH) {
        throw new UnsupportedOperationException("writableBytes must be larger than " + TFrame.FRAME_SIZE_LENGTH);
    }

    int readableBytes = arg.readableBytes();
    ByteBuf sizeBuf = allocator.buffer(TFrame.FRAME_SIZE_LENGTH);
    allocatedBufs.add(sizeBuf);
    bufs.add(sizeBuf);

    // Write the size of the `arg`
    int headerSize = TFrame.FRAME_SIZE_LENGTH;
    int chunkLength = Math.min(readableBytes + headerSize, writableBytes);
    sizeBuf.writeShort(chunkLength - headerSize);
    if (readableBytes == 0) {
        return TFrame.FRAME_SIZE_LENGTH;
    } else {
        bufs.add(arg.readSlice(chunkLength - headerSize).retain());
        return chunkLength;
    }
}
 
Example 7
Source File: TrafficRateEcHandler.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void serializeExtendedCommunity(final ExtendedCommunity extendedCommunity, final ByteBuf byteAggregator) {
    checkArgument(extendedCommunity instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang
        .bgp.flowspec.rev200120.TrafficRateExtendedCommunity,
            "The extended community %s is not TrafficRateExtendedCommunity type.", extendedCommunity);
    final TrafficRateExtendedCommunity trafficRate = ((org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
            .yang.bgp.flowspec.rev200120.TrafficRateExtendedCommunity) extendedCommunity)
            .getTrafficRateExtendedCommunity();
    byteAggregator.writeShort(trafficRate.getInformativeAs().getValue().intValue());
    byteAggregator.writeBytes(trafficRate.getLocalAdministrator().getValue());
}
 
Example 8
Source File: Packet.java    From MirServer-Netty with GNU General Public License v3.0 5 votes vote down vote up
public void writePacket(ByteBuf out) {
	out.writeInt(recog);
	out.writeShort(protocol == null ? 0 : protocol.id);
	out.writeShort(p1);
	out.writeShort(p2);
	out.writeShort(p3);
}
 
Example 9
Source File: EncodeHandler.java    From qmq with Apache License 2.0 5 votes vote down vote up
private static void encodeHeader(final RemotingHeader header, final ByteBuf out) {
    out.writeInt(header.getMagicCode());
    out.writeShort(header.getCode());
    out.writeShort(header.getVersion());
    out.writeInt(header.getOpaque());
    out.writeInt(header.getFlag());
    out.writeShort(header.getRequestCode());
}
 
Example 10
Source File: TestNetflowParser.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test(expected = OnRecordErrorException.class)
public void testInvalidVersion() throws Exception {
  UnpooledByteBufAllocator allocator = new UnpooledByteBufAllocator(false);
  NetflowParser netflowParser = makeNetflowParser();
  ByteBuf buf = allocator.buffer(4);
  buf.writeShort(0);
  buf.writeShort(0);
  netflowParser.parse(buf, null, null);
}
 
Example 11
Source File: ResultPacketCodec.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
public void encode(ResultPacket packet, ByteBuf buffer) {
	buffer.writeInt(packet.getId());
	buffer.writeByte(packet.getStatusCode());
	ByteBuf payload = packet.getPayload();
	if(payload != null) {
		buffer.writeShort(payload.readableBytes());
		buffer.writeBytes(payload, payload.readerIndex(), payload.readableBytes());
		packet.getPayload().release();
	} else if(packet.getStatusCode() == ConnectPacketConstants.statusSuccess) {
		buffer.writeShort(0);
	}
}
 
Example 12
Source File: MessagePacketCodec.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
public void encode(MessagePacket packet, ByteBuf buffer) {
	BufferUtils.writeString(buffer, packet.getSender());
	BufferUtils.writeString(buffer, packet.getChannel());
	ByteBuf payload = packet.getPayload();
	buffer.writeShort(payload.readableBytes());
	buffer.writeBytes(payload, payload.readerIndex(), payload.readableBytes());
	packet.getPayload().release();
}
 
Example 13
Source File: ContainerClear.java    From ehacks-pro with GNU General Public License v3.0 5 votes vote down vote up
public void setSlot(int slotId, int x, int y, int z) {
    int playerId = Wrapper.INSTANCE.player().getEntityId();
    ByteBuf buf = Unpooled.buffer(0);
    buf.writeByte(0);
    buf.writeInt(Wrapper.INSTANCE.player().dimension);
    buf.writeShort(20);
    buf.writeInt(x);
    buf.writeInt(y);
    buf.writeInt(z);
    buf.writeInt(playerId);
    buf.writeInt(slotId);
    buf.writeByte(0);
    C17PacketCustomPayload packet = new C17PacketCustomPayload("MFReloaded", buf);
    Wrapper.INSTANCE.player().sendQueue.addToSendQueue(packet);
}
 
Example 14
Source File: DFClusterManager.java    From dfactor with MIT License 5 votes vote down vote up
protected int sendToNodeInternal(String srcActor, String dstNode, String dstActor, int sessionId, int cmd){
	DFNode node = null;
	_lockNodeRead.lock();
	try{
		node = _mapNode.get(dstNode);
	}finally{
		_lockNodeRead.unlock();
	}
	if(node != null){
		//
		DMCluster.UserMsgHead.Builder bd = DMCluster.UserMsgHead.newBuilder();
		bd.setSrcNode(_selfNodeName).setSrcType(_selfNodeType)
		.setSessionId(sessionId)
		.setSrcActor(srcActor).setDstActor(dstActor);
		byte[] bufHead = bd.build().toByteArray();
		int headLen = bufHead.length;
		int dataLen = 0;
		
		//cmd(2) + headLen(2) + head(N) + userCmd(4) + userDataType(1) +  userData(N)
		int msgLen = 2 + headLen + 4 + 1 + dataLen;
		ByteBuf buf = PooledByteBufAllocator.DEFAULT.ioBuffer(msgLen);
		buf.writeShort(cmd);
		buf.writeShort(headLen);
		buf.writeBytes(bufHead);
		buf.writeInt(0);
		buf.writeByte(0);
		node.channel.write(buf);
		//
		return 0;
	}
	return 1;
}
 
Example 15
Source File: Commands.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private static ByteBufPair serializeCommandSendWithSize(BaseCommand.Builder cmdBuilder, ChecksumType checksumType,
        MessageMetadata msgMetadata, ByteBuf payload) {
    // / Wire format
    // [TOTAL_SIZE] [CMD_SIZE][CMD] [MAGIC_NUMBER][CHECKSUM] [METADATA_SIZE][METADATA] [PAYLOAD]

    BaseCommand cmd = cmdBuilder.build();
    int cmdSize = cmd.getSerializedSize();
    int msgMetadataSize = msgMetadata.getSerializedSize();
    int payloadSize = payload.readableBytes();
    int magicAndChecksumLength = ChecksumType.Crc32c.equals(checksumType) ? (2 + 4 /* magic + checksumLength*/) : 0;
    boolean includeChecksum = magicAndChecksumLength > 0;
    // cmdLength + cmdSize + magicLength +
    // checksumSize + msgMetadataLength +
    // msgMetadataSize
    int headerContentSize = 4 + cmdSize + magicAndChecksumLength + 4 + msgMetadataSize;
    int totalSize = headerContentSize + payloadSize;
    int headersSize = 4 + headerContentSize; // totalSize + headerLength
    int checksumReaderIndex = -1;

    ByteBuf headers = PulsarByteBufAllocator.DEFAULT.buffer(headersSize, headersSize);
    headers.writeInt(totalSize); // External frame

    try {
        // Write cmd
        headers.writeInt(cmdSize);

        ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(headers);
        cmd.writeTo(outStream);
        cmd.recycle();
        cmdBuilder.recycle();

        //Create checksum placeholder
        if (includeChecksum) {
            headers.writeShort(magicCrc32c);
            checksumReaderIndex = headers.writerIndex();
            headers.writerIndex(headers.writerIndex() + checksumSize); //skip 4 bytes of checksum
        }

        // Write metadata
        headers.writeInt(msgMetadataSize);
        msgMetadata.writeTo(outStream);
        outStream.recycle();
    } catch (IOException e) {
        // This is in-memory serialization, should not fail
        throw new RuntimeException(e);
    }

    ByteBufPair command = ByteBufPair.get(headers, payload);

    // write checksum at created checksum-placeholder
    if (includeChecksum) {
        headers.markReaderIndex();
        headers.readerIndex(checksumReaderIndex + checksumSize);
        int metadataChecksum = computeChecksum(headers);
        int computedChecksum = resumeChecksum(metadataChecksum, payload);
        // set computed checksum
        headers.setInt(checksumReaderIndex, computedChecksum);
        headers.resetReaderIndex();
    }
    return command;
}
 
Example 16
Source File: AddOffsetsToTxnCodec.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public void encode(AddOffsetsToTxnResponse payload, ByteBuf buffer) throws Exception {
    buffer.writeInt(payload.getThrottleTimeMs());
    buffer.writeShort(payload.getCode());
}
 
Example 17
Source File: TlvUtil.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
public static void formatTlvShort16(final int type, final int value, final ByteBuf out) {
    formatTlvHeader(type, Short.BYTES, out);
    out.writeShort(value);
}
 
Example 18
Source File: DtxEndOk.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeMethod(ByteBuf buf) {
    buf.writeShort(xaResult);
}
 
Example 19
Source File: TlvUtil.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
public static void formatTlv(final int type,final ByteBuf body, final ByteBuf out) {
    out.writeShort(type);
    out.writeShort(body.writerIndex());
    out.writeBytes(body);
    out.writeZero(getPadding(HEADER_SIZE + body.writerIndex(), PADDED_TO));
}
 
Example 20
Source File: QueuePurge.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeMethod(ByteBuf buf) {
    buf.writeShort(0);
    queue.write(buf);
    buf.writeBoolean(noWait);
}