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

The following examples show how to use io.netty.buffer.ByteBuf#resetWriterIndex() .
Example 1
Project: jt808-netty   File: JT808Encoder.java    License: MIT License 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, DataPacket msg, ByteBuf out) throws Exception {
    log.debug(msg.toString());
    ByteBuf bb = msg.toByteBufMsg();
    bb.markWriterIndex();//标记一下,先到前面去写覆盖的,然后回到标记写校验码
    short bodyLen = (short) (bb.readableBytes() - 12);//包体长度=总长度-头部长度
    short bodyProps = createDefaultMsgBodyProperty(bodyLen);
    //覆盖占用的4字节
    bb.writerIndex(0);
    bb.writeShort(msg.getHeader().getMsgId());
    bb.writeShort(bodyProps);
    bb.resetWriterIndex();
    bb.writeByte(JT808Util.XorSumBytes(bb));
    log.debug(">>>>> ip:{},hex:{}\n", ctx.channel().remoteAddress(), ByteBufUtil.hexDump(bb));
    ByteBuf escape = escape(bb);
    out.writeBytes(escape);
    ReferenceCountUtil.safeRelease(escape);
}
 
Example 2
Project: qmq   File: IndexLog.java    License: Apache License 2.0 6 votes vote down vote up
private void partialCopy(ByteBuffer src, ByteBuf to) {
    while (to.isWritable(Long.BYTES)) {
        src.mark();
        to.markWriterIndex();
        if (!to.isWritable(Long.BYTES)) break;
        to.writeLong(src.getLong());

        if (!to.isWritable(Long.BYTES)) {
            src.reset();
            to.resetWriterIndex();
            break;
        }
        to.writeLong(src.getLong());

        // subject
        if (!writeString(src, to)) break;

        // msgId
        if (!writeString(src, to)) break;
    }
}
 
Example 3
Project: qmq   File: IndexLog.java    License: Apache License 2.0 6 votes vote down vote up
private boolean writeString(ByteBuffer src, ByteBuf to) {
    short len = src.getShort();
    if (!to.isWritable(Short.BYTES + len)) {
        src.reset();
        to.resetWriterIndex();
        return false;
    }
    if (len == 0) {
        to.writeShort(len);
        return true;
    }
    byte[] subject = new byte[len];
    src.get(subject);
    to.writeShort(len);
    to.writeBytes(subject);
    return true;
}
 
Example 4
Project: grpc-java   File: AltsChannelCrypter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void encrypt(ByteBuf outBuf, List<ByteBuf> plainBufs) throws GeneralSecurityException {
  byte[] tempArr = new byte[outBuf.writableBytes()];

  // Copy plaintext into tempArr.
  {
    ByteBuf tempBuf = Unpooled.wrappedBuffer(tempArr, 0, tempArr.length - TAG_LENGTH);
    tempBuf.resetWriterIndex();
    for (ByteBuf plainBuf : plainBufs) {
      tempBuf.writeBytes(plainBuf);
    }
  }

  // Encrypt into tempArr.
  {
    ByteBuffer out = ByteBuffer.wrap(tempArr);
    ByteBuffer plain = ByteBuffer.wrap(tempArr, 0, tempArr.length - TAG_LENGTH);

    byte[] counter = incrementOutCounter();
    aeadCrypter.encrypt(out, plain, counter);
  }
  outBuf.writeBytes(tempArr);
}
 
Example 5
Project: activemq-artemis   File: TypedPropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testByteBufStringValuePool() {
   final int capacity = 8;
   final int chars = Integer.toString(capacity).length();
   final TypedProperties.StringValue.ByteBufStringValuePool pool = new TypedProperties.StringValue.ByteBufStringValuePool(capacity, chars);
   final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
   final ByteBuf bb = Unpooled.buffer(bytes, bytes);
   for (int i = 0; i < capacity; i++) {
      final SimpleString s = new SimpleString(Integer.toString(i));
      bb.resetWriterIndex();
      SimpleString.writeSimpleString(bb, s);
      bb.resetReaderIndex();
      final TypedProperties.StringValue expectedPooled = pool.getOrCreate(bb);
      bb.resetReaderIndex();
      Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
      bb.resetReaderIndex();
   }
}
 
Example 6
Project: ethernet-ip   File: MultipleServicePacketService.java    License: Apache License 2.0 6 votes vote down vote up
private void encode(ByteBuf buffer) {
    int serviceCount = currentServices.size();

    buffer.writeShort(serviceCount);

    int[] offsets = new int[serviceCount];
    int offsetsStartIndex = buffer.writerIndex();
    buffer.writeZero(serviceCount * 2);

    for (int i = 0; i < serviceCount; i++) {
        offsets[i] = buffer.writerIndex() - offsetsStartIndex + 2;
        currentServices.get(i).encodeRequest(buffer);
    }

    buffer.markWriterIndex();
    buffer.writerIndex(offsetsStartIndex);
    for (int offset : offsets) {
        buffer.writeShort(offset);
    }
    buffer.resetWriterIndex();
}
 
Example 7
Project: activemq-artemis   File: SimpleStringTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testByteBufSimpleStringPool() {
   final int capacity = 8;
   final int chars = Integer.toString(capacity).length();
   final SimpleString.ByteBufSimpleStringPool pool = new SimpleString.ByteBufSimpleStringPool(capacity, chars);
   final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
   final ByteBuf bb = Unpooled.buffer(bytes, bytes);
   for (int i = 0; i < capacity; i++) {
      final SimpleString s = new SimpleString(Integer.toString(i));
      bb.resetWriterIndex();
      SimpleString.writeSimpleString(bb, s);
      bb.resetReaderIndex();
      final SimpleString expectedPooled = pool.getOrCreate(bb);
      bb.resetReaderIndex();
      Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
      bb.resetReaderIndex();
   }
}
 
Example 8
Project: Jupiter   File: LowCopyProtocolEncoder.java    License: Apache License 2.0 6 votes vote down vote up
private ByteBuf doEncodeResponse(JResponsePayload response) {
    byte sign = JProtocolHeader.toSign(response.serializerCode(), JProtocolHeader.RESPONSE);
    byte status = response.status();
    long invokeId = response.id();
    ByteBuf byteBuf = (ByteBuf) response.outputBuf().backingObject();
    int length = byteBuf.readableBytes();

    byteBuf.markWriterIndex();

    byteBuf.writerIndex(byteBuf.writerIndex() - length);

    byteBuf.writeShort(JProtocolHeader.MAGIC)
            .writeByte(sign)
            .writeByte(status)
            .writeLong(invokeId)
            .writeInt(length - JProtocolHeader.HEADER_SIZE);

    byteBuf.resetWriterIndex();

    return byteBuf;
}
 
Example 9
Project: ethernet-ip   File: UnconnectedDataItemResponse.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteBuf encode(UnconnectedDataItemResponse item, ByteBuf buffer) {
    buffer.writeShort(item.getTypeId());

    // Length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeShort(0);

    // Encode the encapsulated data...
    int dataStartIndex = buffer.writerIndex();
    buffer.writeBytes(item.getData());
    item.getData().release();

    // Go back and update the length.
    int bytesWritten = buffer.writerIndex() - dataStartIndex;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeShort(bytesWritten);
    buffer.resetWriterIndex();

    return buffer;
}
 
Example 10
Project: ethernet-ip   File: ConnectedDataItemRequest.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteBuf encode(ConnectedDataItemRequest item, ByteBuf buffer) {
    buffer.writeShort(item.getTypeId());

    // Length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeShort(0);

    // Encode the encapsulated data...
    int dataStartIndex = buffer.writerIndex();
    item.getEncoder().accept(buffer);

    // Go back and update the length.
    int bytesWritten = buffer.writerIndex() - dataStartIndex;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeShort(bytesWritten);
    buffer.resetWriterIndex();

    return buffer;
}
 
Example 11
Project: ethernet-ip   File: ConnectedDataItemResponse.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteBuf encode(ConnectedDataItemResponse item, ByteBuf buffer) {
    buffer.writeShort(item.getTypeId());

    // Length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeShort(0);

    // Encode the encapsulated data...
    int dataStartIndex = buffer.writerIndex();
    buffer.writeBytes(item.getData());
    item.getData().release();

    // Go back and update the length.
    int bytesWritten = buffer.writerIndex() - dataStartIndex;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeShort(bytesWritten);
    buffer.resetWriterIndex();

    return buffer;
}
 
Example 12
Project: Distributed-KV   File: ByteBufUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 批量恢复索引位置
 * @param buffers
 */
public static void resetIndex(ByteBuf... buffers) {
	for(ByteBuf buffer : buffers) {
		// 恢复bytebuf信息
		buffer.resetReaderIndex();
		buffer.resetWriterIndex();
	}
}
 
Example 13
Project: qmq   File: MessageIndexSyncWorker.java    License: Apache License 2.0 5 votes vote down vote up
private Control copyString(ByteBuffer from, ByteBuf to) {
    short len = from.getShort();
    if (len <= 0) {
        to.resetWriterIndex();
        return Control.INVALID;
    }
    byte[] str = new byte[len];
    from.get(str);
    if (!to.isWritable(Short.BYTES + len)) {
        to.resetWriterIndex();
        return Control.NOSPACE;
    }
    PayloadHolderUtils.writeString(str, to);
    return Control.OK;
}
 
Example 14
Project: grpc-java   File: AltsChannelCrypter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void decrypt(
    ByteBuf outBuf, ByteBuf ciphertextAndTagDirect) throws GeneralSecurityException {
  byte[] tempArr = new byte[ciphertextAndTagDirect.readableBytes()];

  // Copy ciphertext and tag into tempArr.
  {
    ByteBuf tempBuf = Unpooled.wrappedBuffer(tempArr);
    tempBuf.resetWriterIndex();
    tempBuf.writeBytes(ciphertextAndTagDirect);
  }

  decryptInternal(outBuf, tempArr);
}
 
Example 15
Project: ballerina-message-broker   File: Metadata.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] getPropertiesAsBytes() {
    long size = properties.getSize() + headers.getSize();
    byte[] bytes = new byte[(int) size];
    ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
    buffer.resetWriterIndex();
    properties.write(buffer);
    headers.write(buffer);
    return bytes;
}
 
Example 16
Project: ballerina-message-broker   File: BindingDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void persist(String exchangeName, Binding binding) throws BrokerException {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(RDBMSConstants.PS_INSERT_BINDING);
        statement.setString(1, exchangeName);
        statement.setString(2, binding.getQueue().getName());
        statement.setString(3, binding.getBindingPattern());
        FieldTable arguments = binding.getArguments();
        byte[] bytes = new byte[(int) arguments.getSize()];
        ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
        byteBuf.resetWriterIndex();
        arguments.write(byteBuf);
        statement.setBytes(4, bytes);

        statement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        String message = "Error occurred while storing binding " + binding;
        rollback(connection, message);
        throw new BrokerException(message, e);
    } finally {
        close(connection, statement);
    }
}
 
Example 17
Project: rsocket-java   File: CompositeMetadataCodec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encode a custom mime type and a metadata value length into a newly allocated {@link ByteBuf}.
 *
 * <p>This larger representation encodes the mime type representation's length on a single byte,
 * then the representation itself, then the unsigned metadata value length on 3 additional bytes.
 *
 * @param allocator the {@link ByteBufAllocator} to use to create the buffer.
 * @param customMime a custom mime type to encode.
 * @param metadataLength the metadata length to append to the buffer as an unsigned 24 bits
 *     integer.
 * @return the encoded mime and metadata length information
 */
static ByteBuf encodeMetadataHeader(
    ByteBufAllocator allocator, String customMime, int metadataLength) {
  ByteBuf metadataHeader = allocator.buffer(4 + customMime.length());
  // reserve 1 byte for the customMime length
  // /!\ careful not to read that first byte, which is random at this point
  int writerIndexInitial = metadataHeader.writerIndex();
  metadataHeader.writerIndex(writerIndexInitial + 1);

  // write the custom mime in UTF8 but validate it is all ASCII-compatible
  // (which produces the right result since ASCII chars are still encoded on 1 byte in UTF8)
  int customMimeLength = ByteBufUtil.writeUtf8(metadataHeader, customMime);
  if (!ByteBufUtil.isText(
      metadataHeader, metadataHeader.readerIndex() + 1, customMimeLength, CharsetUtil.US_ASCII)) {
    metadataHeader.release();
    throw new IllegalArgumentException("custom mime type must be US_ASCII characters only");
  }
  if (customMimeLength < 1 || customMimeLength > 128) {
    metadataHeader.release();
    throw new IllegalArgumentException(
        "custom mime type must have a strictly positive length that fits on 7 unsigned bits, ie 1-128");
  }
  metadataHeader.markWriterIndex();

  // go back to beginning and write the length
  // encoded length is one less than actual length, since 0 is never a valid length, which gives
  // wider representation range
  metadataHeader.writerIndex(writerIndexInitial);
  metadataHeader.writeByte(customMimeLength - 1);

  // go back to post-mime type and write the metadata content length
  metadataHeader.resetWriterIndex();
  NumberUtils.encodeUnsignedMedium(metadataHeader, metadataLength);

  return metadataHeader;
}
 
Example 18
Project: ethernet-ip   File: CipIdentityItem.java    License: Apache License 2.0 5 votes vote down vote up
public static ByteBuf encode(CipIdentityItem item, ByteBuf buffer) {
    buffer.writeShort(TYPE_ID);

    // Length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeShort(0);

    // Encode the item...
    int itemStartIndex = buffer.writerIndex();
    buffer.writeShort(item.getProtocolVersion());
    SockAddr.encode(item.getSocketAddress(), buffer);
    buffer.writeShort(item.getVendorId());
    buffer.writeShort(item.getDeviceType());
    buffer.writeShort(item.getProductCode());
    buffer.writeByte(item.getRevisionMajor());
    buffer.writeByte(item.getRevisionMinor());
    buffer.writeShort(item.getStatus());
    buffer.writeInt((int) item.getSerialNumber());
    writeString(item.getProductName(), buffer);
    buffer.writeByte(item.getState());

    // Go back and update the length.
    int bytesWritten = buffer.writerIndex() - itemStartIndex;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeShort(bytesWritten);
    buffer.resetWriterIndex();

    return buffer;
}
 
Example 19
Project: ethernet-ip   File: ForwardCloseRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encode the connection path.
 * <p>
 * {@link PaddedEPath#encode(EPath, ByteBuf)} can't be used here because the {@link ForwardCloseRequest} has an
 * extra reserved byte after the connection path size for some reason.
 *
 * @param path   the {@link PaddedEPath} to encode.
 * @param buffer the {@link ByteBuf} to encode into.
 */
private static void encodeConnectionPath(PaddedEPath path, ByteBuf buffer) {
    // length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeByte(0);

    // reserved
    buffer.writeZero(1);

    // encode the path segments...
    int dataStartIndex = buffer.writerIndex();

    for (EPathSegment segment : path.getSegments()) {
        if (segment instanceof LogicalSegment) {
            LogicalSegment.encode((LogicalSegment) segment, path.isPadded(), buffer);
        } else if (segment instanceof PortSegment) {
            PortSegment.encode((PortSegment) segment, path.isPadded(), buffer);
        } else if (segment instanceof DataSegment) {
            DataSegment.encode((DataSegment) segment, path.isPadded(), buffer);
        } else {
            throw new RuntimeException("no encoder for " + segment.getClass().getSimpleName());
        }
    }

    // go back and update the length
    int bytesWritten = buffer.writerIndex() - dataStartIndex;
    int wordsWritten = bytesWritten / 2;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeByte(wordsWritten);
    buffer.resetWriterIndex();
}
 
Example 20
Project: ethernet-ip   File: EnipPacket.java    License: Apache License 2.0 5 votes vote down vote up
public static ByteBuf encode(EnipPacket packet, ByteBuf buffer) {
    buffer.writeShort(packet.getCommandCode().getCode());

    // Length placeholder...
    int lengthStartIndex = buffer.writerIndex();
    buffer.writeShort(0);

    buffer.writeInt((int) packet.getSessionHandle());
    buffer.writeInt(packet.getStatus().getStatus());
    buffer.writeLong(packet.getSenderContext());
    buffer.writeInt(0);

    int dataStartIndex = buffer.writerIndex();

    if (packet.getCommand() != null) {
        encodeCommand(packet.getCommand(), buffer);
    }

    // Go back and update the length.
    int bytesWritten = buffer.writerIndex() - dataStartIndex;
    buffer.markWriterIndex();
    buffer.writerIndex(lengthStartIndex);
    buffer.writeShort(bytesWritten);
    buffer.resetWriterIndex();

    return buffer;
}