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

The following examples show how to use io.netty.buffer.ByteBuf#setInt() . 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: CommandDecoderTest.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownFields() throws IOException {
    ByteBuf buffer = Unpooled.buffer(100);
    Hello command = new WireCommands.Hello(10, 1);     
    CommandEncoder.writeMessage(command, buffer);
    buffer.writeLong(1); //Bonus data
    buffer.writeLong(2);
    buffer.writeLong(3);
    buffer.setInt(4, 8 + 24);
    assertEquals(16 + 24, buffer.readableBytes());

    command = (Hello) CommandDecoder.parseCommand(buffer);
    assertEquals(0, buffer.readableBytes());
    assertEquals(WireCommandType.HELLO, command.getType());    
    assertEquals(10, command.highVersion); 
    assertEquals(1, command.lowVersion);          
}
 
Example 2
Source File: ObjectEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    int startIdx = out.writerIndex();

    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    ObjectOutputStream oout = null;
    try {
        bout.write(LENGTH_PLACEHOLDER);
        oout = new CompactObjectOutputStream(bout);
        oout.writeObject(msg);
        oout.flush();
    } finally {
        if (oout != null) {
            oout.close();
        } else {
            bout.close();
        }
    }

    int endIdx = out.writerIndex();

    out.setInt(startIdx, endIdx - startIdx - 4);
}
 
Example 3
Source File: PGArray.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public int writeAsBinary(ByteBuf buffer, @Nonnull List<Object> value) {
    int dimensions = getDimensions(value);

    List<Integer> dimensionsList = new ArrayList<>();
    buildDimensions(value, dimensionsList, dimensions, 1);

    int bytesWritten = 4 + 4 + 4;
    final int lenIndex = buffer.writerIndex();
    buffer.writeInt(0);
    buffer.writeInt(dimensions);
    buffer.writeInt(1); // flags bit 0: 0=no-nulls, 1=has-nulls
    buffer.writeInt(typElem());

    for (Integer dim : dimensionsList) {
        buffer.writeInt(dim); // upper bound
        buffer.writeInt(dim); // lower bound
        bytesWritten += 8;
    }
    int len = bytesWritten + writeArrayAsBinary(buffer, value, dimensionsList, 1);
    buffer.setInt(lenIndex, len);
    return INT32_BYTE_SIZE + len; // add also the size of the length itself
}
 
Example 4
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
private static <T> void binaryEncodeArray(T[] values, DataType type, ByteBuf buff){
  int startIndex = buff.writerIndex();
  buff.writeInt(1);             // ndim
  buff.writeInt(0);             // dataoffset
  buff.writeInt(type.id);       // elemtype
  buff.writeInt(values.length); // dimension
  buff.writeInt(1);             // lower bnds
  boolean hasNulls = false;
  for (T value : values) {
    if (value == null) {
      hasNulls = true;
      buff.writeInt(-1);
    } else {
      int idx = buff.writerIndex();
      buff.writeInt(0);
      encodeBinary(type, value, buff);
      buff.setInt(idx, buff.writerIndex() - idx - 4);
    }
  }
  if (hasNulls) {
    buff.setInt(startIndex + 4, 1);
  }
}
 
Example 5
Source File: Lz4FrameEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private ChannelFuture finishEncode(final ChannelHandlerContext ctx, ChannelPromise promise) {
    if (finished) {
        promise.setSuccess();
        return promise;
    }
    finished = true;

    final ByteBuf footer = ctx.alloc().heapBuffer(
            compressor.maxCompressedLength(buffer.readableBytes()) + HEADER_LENGTH);
    flushBufferedData(footer);

    final int idx = footer.writerIndex();
    footer.setLong(idx, MAGIC_NUMBER);
    footer.setByte(idx + TOKEN_OFFSET, (byte) (BLOCK_TYPE_NON_COMPRESSED | compressionLevel));
    footer.setInt(idx + COMPRESSED_LENGTH_OFFSET, 0);
    footer.setInt(idx + DECOMPRESSED_LENGTH_OFFSET, 0);
    footer.setInt(idx + CHECKSUM_OFFSET, 0);

    footer.writerIndex(idx + HEADER_LENGTH);

    return ctx.writeAndFlush(footer, promise);
}
 
Example 6
Source File: CommandEncoder.java    From pravega with Apache License 2.0 5 votes vote down vote up
@SneakyThrows(IOException.class)
@VisibleForTesting
static int writeMessage(WireCommand msg, ByteBuf out) {
    int startIdx = out.writerIndex();
    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    bout.writeInt(msg.getType().getCode());
    bout.write(LENGTH_PLACEHOLDER);
    msg.writeFields(bout);
    bout.flush();
    bout.close();
    int endIdx = out.writerIndex();
    int fieldsSize = endIdx - startIdx - TYPE_PLUS_LENGTH_SIZE;
    out.setInt(startIdx + TYPE_SIZE, fieldsSize);
    return endIdx - startIdx;
}
 
Example 7
Source File: FastestSerializer.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
public static void writeResponse(ByteBuf byteBuf, Response response) throws IOException {
	int beginWriterIndex = byteBuf.writerIndex();
	byteBuf.writeInt(0);

	responseSerializer.write(byteBuf, response);

	int finishWriterIndex = byteBuf.writerIndex();
	int length = finishWriterIndex - beginWriterIndex - 4;

	byteBuf.setInt(beginWriterIndex, length);
}
 
Example 8
Source File: KryoSerializer.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
public void writeResponse(ByteBuf byteBuf, Response response) throws IOException {
	final int beginWriterIndex = byteBuf.writerIndex();

	byteBuf.writeInt(0);
	// byteBuf.writerIndex(beginWriterIndex + TurboConstants.HEADER_FIELD_LENGTH);
	byteBuf.writeInt(response.getRequestId());

	final int statusWriterIndex = byteBuf.writerIndex();

	try {
		byteBuf.writeByte(response.getStatusCode());
		tracerSerializer.write(byteBuf, response.getTracer());
		kryoContext().writeClassAndObject(byteBuf, response.getResult());
	} catch (Exception e) {
		if (logger.isWarnEnabled()) {
			logger.warn("kryo writeResponse error", e);
		}

		byteBuf.writerIndex(statusWriterIndex);
		byteBuf.writeByte(ResponseStatus.BAD_RESPONSE);
		tracerSerializer.write(byteBuf, response.getTracer());
		kryoContext().writeClassAndObject(byteBuf, e.getMessage());
	}

	int finishWriterIndex = byteBuf.writerIndex();
	int length = finishWriterIndex - beginWriterIndex - TurboConstants.HEADER_FIELD_LENGTH;

	byteBuf.setInt(beginWriterIndex, length);

	RecycleUtils.release(response);
}
 
Example 9
Source File: ObjectEncoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    int startIdx = out.writerIndex();

    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    bout.write(LENGTH_PLACEHOLDER);
    ObjectOutputStream oout = new CompactObjectOutputStream(bout);
    oout.writeObject(msg);
    oout.flush();
    oout.close();

    int endIdx = out.writerIndex();

    out.setInt(startIdx, endIdx - startIdx - 4);
}
 
Example 10
Source File: ClientMessages.java    From crate with Apache License 2.0 5 votes vote down vote up
static void sendBindMessage(ByteBuf buffer,
                            String portalName,
                            String statementName,
                            List<Object> params) {
    buffer.writeByte('B');
    byte[] portalBytes = portalName.getBytes(StandardCharsets.UTF_8);
    byte[] statementBytes = statementName.getBytes(StandardCharsets.UTF_8);

    int beforeLengthWriterIndex = buffer.writerIndex();
    buffer.writeInt(0);
    writeCString(buffer, portalBytes);
    writeCString(buffer, statementBytes);
    buffer.writeShort(0); // formatCode use 0 to default to text for all
    buffer.writeShort(params.size());

    int paramsLength = 0;
    for (Object param : params) {
        BytesRef value = BytesRefs.toBytesRef(param);
        buffer.writeInt(value.length);
        // the strings here are _not_ zero-padded because we specify the length upfront
        buffer.writeBytes(value.bytes, value.offset, value.length);
        paramsLength += 4 + value.length;
    }
    buffer.writeShort(0); // numResultFormatCodes - 0 to default to text for all

    buffer.setInt(beforeLengthWriterIndex,
        4 +
        portalBytes.length + 1 +
        statementBytes.length + 1 +
        2 + // numFormatCodes
        2 + // numParams
        paramsLength +
        2); // numResultColumnFormatCodes
}
 
Example 11
Source File: OneNetMsgEncoder.java    From one-net with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, BasePackage msg, ByteBuf out) throws Exception {
    int startIdx = out.writerIndex();
    out.writeBytes(LENGTH_PLACEHOLDER);
    out.writeBytes(msg.toBytes());
    int endIdx = out.writerIndex();
    out.setInt(startIdx, endIdx - startIdx - 4);
}
 
Example 12
Source File: MixMessageEncoder.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, MixMessage msg, ByteBuf out) throws Exception {
    int startIdx = out.writerIndex();
    out.writeBytes(LENGTH_PLACEHOLDER);

    MixEventName event = msg.getEvent();
    byte b = event.getID();
    out.writeByte(b);

    Object feature = msg.getFeature();
    encodeObject(feature, out);

    float weight = msg.getWeight();
    out.writeFloat(weight);

    float covariance = msg.getCovariance();
    out.writeFloat(covariance);

    short clock = msg.getClock();
    out.writeShort(clock);

    int deltaUpdates = msg.getDeltaUpdates();
    out.writeInt(deltaUpdates);

    boolean cancelRequest = msg.isCancelRequest();
    out.writeBoolean(cancelRequest);

    String groupId = msg.getGroupID();
    writeString(groupId, out);

    int endIdx = out.writerIndex();
    out.setInt(startIdx, endIdx - startIdx - 4);
}
 
Example 13
Source File: Base64.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void encode3to4LittleEndian(
        int inBuff, int numSigBytes, ByteBuf dest, int destOffset, byte[] alphabet) {
    // Packing bytes into an int to reduce bound and reference count checking.
    switch (numSigBytes) {
        case 3:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ]       |
                                    alphabet[inBuff >>> 12 & 0x3f] << 8  |
                                    alphabet[inBuff >>>  6 & 0x3f] << 16 |
                                    alphabet[inBuff        & 0x3f] << 24);
            break;
        case 2:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ]       |
                                    alphabet[inBuff >>> 12 & 0x3f] << 8  |
                                    alphabet[inBuff >>> 6  & 0x3f] << 16 |
                                    EQUALS_SIGN << 24);
            break;
        case 1:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ]      |
                                    alphabet[inBuff >>> 12 & 0x3f] << 8 |
                                    EQUALS_SIGN << 16                   |
                                    EQUALS_SIGN << 24);
            break;
        default:
            // NOOP
            break;
    }
}
 
Example 14
Source File: Base64.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void encode3to4BigEndian(
        int inBuff, int numSigBytes, ByteBuf dest, int destOffset, byte[] alphabet) {
    // Packing bytes into an int to reduce bound and reference count checking.
    switch (numSigBytes) {
        case 3:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ] << 24 |
                                    alphabet[inBuff >>> 12 & 0x3f] << 16 |
                                    alphabet[inBuff >>>  6 & 0x3f] << 8  |
                                    alphabet[inBuff        & 0x3f]);
            break;
        case 2:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ] << 24 |
                                    alphabet[inBuff >>> 12 & 0x3f] << 16 |
                                    alphabet[inBuff >>> 6  & 0x3f] << 8  |
                                    EQUALS_SIGN);
            break;
        case 1:
            dest.setInt(destOffset, alphabet[inBuff >>> 18       ] << 24 |
                                    alphabet[inBuff >>> 12 & 0x3f] << 16 |
                                    EQUALS_SIGN << 8                     |
                                    EQUALS_SIGN);
            break;
        default:
            // NOOP
            break;
    }
}
 
Example 15
Source File: ProducerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Strips checksum from {@link OpSendMsg} command if present else ignore it.
 *
 * @param op
 */
private void stripChecksum(OpSendMsg op) {
    int totalMsgBufSize = op.cmd.readableBytes();
    ByteBufPair msg = op.cmd;
    if (msg != null) {
        ByteBuf headerFrame = msg.getFirst();
        headerFrame.markReaderIndex();
        try {
            headerFrame.skipBytes(4); // skip [total-size]
            int cmdSize = (int) headerFrame.readUnsignedInt();

            // verify if checksum present
            headerFrame.skipBytes(cmdSize);

            if (!hasChecksum(headerFrame)) {
                return;
            }

            int headerSize = 4 + 4 + cmdSize; // [total-size] [cmd-length] [cmd-size]
            int checksumSize = 4 + 2; // [magic-number] [checksum-size]
            int checksumMark = (headerSize + checksumSize); // [header-size] [checksum-size]
            int metaPayloadSize = (totalMsgBufSize - checksumMark); // metadataPayload = totalSize - checksumMark
            int newTotalFrameSizeLength = 4 + cmdSize + metaPayloadSize; // new total-size without checksum
            headerFrame.resetReaderIndex();
            int headerFrameSize = headerFrame.readableBytes();

            headerFrame.setInt(0, newTotalFrameSizeLength); // rewrite new [total-size]
            ByteBuf metadata = headerFrame.slice(checksumMark, headerFrameSize - checksumMark); // sliced only
                                                                                                // metadata
            headerFrame.writerIndex(headerSize); // set headerFrame write-index to overwrite metadata over checksum
            metadata.readBytes(headerFrame, metadata.readableBytes());
            headerFrame.capacity(headerFrameSize - checksumSize); // reduce capacity by removed checksum bytes
        } finally {
            headerFrame.resetReaderIndex();
        }
    } else {
        log.warn("[{}] Failed while casting {} into ByteBufPair", producerName,
                (op.cmd == null ? null : op.cmd.getClass().getName()));
    }
}
 
Example 16
Source File: TestCodeC.java    From netty-custom-protocol with MIT License 5 votes vote down vote up
public ByteBuf encode(NettyMessage msg) throws Exception {
	ByteBuf sendBuf = Unpooled.buffer();
	sendBuf.writeInt((msg.getHeader().getCrcCode()));
	sendBuf.writeInt((msg.getHeader().getLength()));
	sendBuf.writeLong((msg.getHeader().getSessionID()));
	sendBuf.writeByte((msg.getHeader().getType()));
	sendBuf.writeByte((msg.getHeader().getPriority()));
	sendBuf.writeInt((msg.getHeader().getAttachment().size()));
	String key = null;
	byte[] keyArray = null;
	Object value = null;

	for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
		key = param.getKey();
		keyArray = key.getBytes("UTF-8");
		sendBuf.writeInt(keyArray.length);
		sendBuf.writeBytes(keyArray);
		value = param.getValue();
		marshallingEncoder.encode(value, sendBuf);
	}
	key = null;
	keyArray = null;
	value = null;
	if (msg.getBody() != null) {
		marshallingEncoder.encode(msg.getBody(), sendBuf);
	} else
		sendBuf.writeInt(0);
	sendBuf.setInt(4, sendBuf.readableBytes());
	return sendBuf;
}
 
Example 17
Source File: InitiateSslHandler.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ByteBuf byteBuf = Unpooled.buffer();
    byteBuf.writeInt(0);
    byteBuf.writeInt(code);
//    out.writeInt(0x12345679);
    byteBuf.setInt(0, byteBuf.writerIndex());
    ctx.writeAndFlush(byteBuf);
    super.channelActive(ctx);
  }
 
Example 18
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
static void encodeText(DataType id, Object value, ByteBuf buff) {
  int index = buff.writerIndex();
  buff.writeInt(0);
  textEncode(id, value, buff);
  buff.setInt(index, buff.writerIndex() - index - 4);
}
 
Example 19
Source File: KafkaEncoder.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeLength(Object obj, ByteBuf buffer) {
    buffer.setInt(0, buffer.writerIndex() - 4);
}
 
Example 20
Source File: CursorParamTest.java    From lmdbjava with Apache License 2.0 4 votes vote down vote up
@Override
public void set(final ByteBuf buff, final int val) {
  buff.setInt(0, val);
}