Java Code Examples for io.netty.buffer.ByteBuf.writerIndex()

The following are Jave code examples for showing how to use writerIndex() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: reactive-pg-client   File: StartupMessage.java   Source Code and License Vote up 6 votes
@Override
public void encode(ByteBuf out) {

  int pos = out.writerIndex();

  out.writeInt(0);
  // protocol version
  out.writeShort(3);
  out.writeShort(0);

  writeCString(out, BUFF_USER);
  Util.writeCStringUTF8(out, username);
  writeCString(out, BUFF_DATABASE);
  Util.writeCStringUTF8(out, database);
  writeCString(out, BUFF_APPLICATION_NAME);
  writeCString(out, BUFF_VERTX_PG_CLIENT);
  writeCString(out, BUFF_CLIENT_ENCODING);
  writeCString(out, BUFF_UTF8);
  writeCString(out, BUFF_DATE_STYLE);
  writeCString(out, BUFF_ISO);
  writeCString(out, BUFF_EXTRA_FLOAT_DIGITS);
  writeCString(out, BUFF_2);

  out.writeByte(0);
  out.setInt(pos, out.writerIndex() - pos);
}
 
Example 2
Project: fresco_floodlight   File: ThriftFrameEncoder.java   Source Code and License Vote up 6 votes
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
 
Example 3
Project: reactive-pg-client   File: Parse.java   Source Code and License Vote up 6 votes
private static void encode(long statement, String query, int[] paramDataTypes, ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(PARSE);
  out.writeInt(0);
  if(statement == 0) {
    out.writeByte(0);
  } else {
    out.writeLong(statement);
  }
  Util.writeCStringUTF8(out, query);
  // no parameter data types (OIDs)
  if(paramDataTypes == null) {
    out.writeShort(0);
  } else {
    // Parameter data types (OIDs)
    out.writeShort(paramDataTypes.length);
    for (int paramDataType : paramDataTypes) {
      out.writeInt(paramDataType);
    }
  }
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 4
Project: proteus-java   File: ProteusMetadata.java   Source Code and License Vote up 6 votes
public static int encode(ByteBuf byteBuf, int namespaceId, int serviceId, int methodId, ByteBuf metadata) {
    int offset = 0;

    byteBuf.setShort(offset, 1);
    offset += VERSION_SIZE;

    byteBuf.setInt(offset, namespaceId);
    offset += NAMESPACE_ID_SIZE;

    byteBuf.setInt(offset, serviceId);
    offset += SERVICE_ID_SIZE;

    byteBuf.setInt(offset, methodId);
    offset += METHOD_ID_SIZE;

    int metadataLength = metadata.readableBytes();
    byteBuf.setInt(offset, metadataLength);
    offset += METADATA_LENGTH_SIZE;

    byteBuf.setBytes(offset, metadata);
    offset += metadataLength;

    byteBuf.writerIndex(offset);

    return offset;
}
 
Example 5
Project: sstable-adaptor   File: CBUtil.java   Source Code and License Vote up 5 votes
public static void writeString(String str, ByteBuf cb)
{
    int writerIndex = cb.writerIndex();
    cb.writeShort(0);
    int lengthBytes = ByteBufUtil.writeUtf8(cb, str);
    cb.setShort(writerIndex, lengthBytes);
}
 
Example 6
Project: reactive-pg-client   File: DataType.java   Source Code and License Vote up 5 votes
public void encodeText(T value, ByteBuf buff) {
  int index = buff.writerIndex();
  String s = String.valueOf(value);
  int len = buff.setCharSequence(index + 4, s, StandardCharsets.UTF_8);
  buff.writeInt(len);
  buff.writerIndex(index + 4 + len);
}
 
Example 7
Project: incubator-servicecomb-java-chassis   File: VertxUtils.java   Source Code and License Vote up 5 votes
public static byte[] getBytesFast(ByteBuf byteBuf) {
  if (byteBuf.hasArray()) {
    return byteBuf.array();
  }

  byte[] arr = new byte[byteBuf.writerIndex()];
  byteBuf.getBytes(0, arr);
  return arr;
}
 
Example 8
Project: reactive-pg-client   File: Execute.java   Source Code and License Vote up 5 votes
private static void encode(String portal, int rowCount, ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(EXECUTE);
  out.writeInt(0);
  if (portal != null) {
    out.writeCharSequence(portal, StandardCharsets.UTF_8);
  }
  out.writeByte(0);
  out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream<Row>
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 9
Project: reactive-pg-client   File: Close.java   Source Code and License Vote up 5 votes
@Override
public void encode(ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(CLOSE);
  out.writeInt(0);
  out.writeByte('S'); // 'S' to close a prepared statement or 'P' to close a portal
  Util.writeCStringUTF8(out, statement != null ? statement : "");
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 10
Project: Backmemed   File: NettyEncryptionTranslator.java   Source Code and License Vote up 5 votes
protected ByteBuf decipher(ChannelHandlerContext ctx, ByteBuf buffer) throws ShortBufferException
{
    int i = buffer.readableBytes();
    byte[] abyte = this.bufToBytes(buffer);
    ByteBuf bytebuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(i));
    bytebuf.writerIndex(this.cipher.update(abyte, 0, i, bytebuf.array(), bytebuf.arrayOffset()));
    return bytebuf;
}
 
Example 11
Project: reactive-pg-client   File: Query.java   Source Code and License Vote up 5 votes
@Override
public void encode(ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(QUERY);
  out.writeInt(0);
  Util.writeCStringUTF8(out, getQuery());
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 12
Project: BaseClient   File: NettyEncryptionTranslator.java   Source Code and License Vote up 5 votes
protected ByteBuf decipher(ChannelHandlerContext ctx, ByteBuf buffer) throws ShortBufferException
{
    int i = buffer.readableBytes();
    byte[] abyte = this.func_150502_a(buffer);
    ByteBuf bytebuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(i));
    bytebuf.writerIndex(this.cipher.update(abyte, 0, i, bytebuf.array(), bytebuf.arrayOffset()));
    return bytebuf;
}
 
Example 13
Project: FlexMC   File: EncryptionBufWrapper.java   Source Code and License Vote up 5 votes
public ByteBuf decrypt( ChannelHandlerContext paramChannelHandlerContext, ByteBuf input ) throws ShortBufferException {
    int readableBytes = input.readableBytes();
    this.lock.lock();
    try {
        byte[] array = toByteArray( input );
        ByteBuf output = paramChannelHandlerContext.alloc().heapBuffer( this.cipher.getOutputSize( readableBytes ) );
        output.writerIndex( this.cipher.update( array, 0, readableBytes, output.array(), output.arrayOffset() ) );
        return output;
    } finally {
        this.lock.unlock();
    }
}
 
Example 14
Project: reactive-pg-client   File: PasswordMessage.java   Source Code and License Vote up 5 votes
@Override
public void encode(ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(PASSWORD_MESSAGE);
  out.writeInt(0);
  Util.writeCStringUTF8(out, hash);
  out.setInt(pos + 1, out.writerIndex() - pos- 1);
}
 
Example 15
Project: L2J-Global   File: PacketEncoder.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, IOutgoingPacket packet, ByteBuf out)
{
	if (out.order() != _byteOrder)
	{
		out = out.order(_byteOrder);
	}
	
	try
	{
		if (packet.write(new PacketWriter(out)))
		{
			if (out.writerIndex() > _maxPacketSize)
			{
				throw new IllegalStateException("Packet (" + packet + ") size (" + out.writerIndex() + ") is bigger than the limit (" + _maxPacketSize + ")");
			}
		}
		else
		{
			// Avoid sending the packet
			out.clear();
		}
	}
	catch (Throwable e)
	{
		LOGGER.log(Level.WARNING, "Failed sending Packet(" + packet + ")", e);
		// Avoid sending the packet if some exception happened
		out.clear();
	}
}
 
Example 16
Project: kcp-netty   File: Kcp.java   Source Code and License Vote up 5 votes
private static int encodeSeg(ByteBuf buf, Segment seg) {
    int offset = buf.writerIndex();

    buf.writeIntLE(seg.conv);
    buf.writeByte(seg.cmd);
    buf.writeByte(seg.frg);
    buf.writeShortLE(seg.wnd);
    buf.writeIntLE((int) seg.ts);
    buf.writeIntLE((int) seg.sn);
    buf.writeIntLE((int) seg.una);
    buf.writeIntLE(seg.data.readableBytes());

    return buf.writerIndex() - offset;
}
 
Example 17
Project: L2J-Global   File: Crypt.java   Source Code and License Vote up 4 votes
private void onPacketReceive(ByteBuf buf)
{
	final byte[] data = new byte[buf.writerIndex()];
	buf.getBytes(0, data);
	EventDispatcher.getInstance().notifyEvent(new OnPacketReceived(_client, data));
}
 
Example 18
Project: curiostack   File: ProtobufRedisCodec.java   Source Code and License Vote up 4 votes
@Override
public void encodeKey(K key, ByteBuf target) {
  target.writeBytes(keyPrefix);
  encodeTo(key, target);
  target.writerIndex(key.getSerializedSize() + keyPrefix.length);
}
 
Example 19
Project: hekate   File: NetworkProtocolCodec.java   Source Code and License Vote up 4 votes
private static void doEncode(Object msg, ByteBufDataWriter out, Codec<Object> codec) throws CodecException {
    try {
        ByteBuf outBuf = out.buffer();

        // Header indexes.
        int headStartIdx = outBuf.writerIndex();

        // Header end index.
        int headEndIdx = headStartIdx + HEADER_LENGTH;

        // Placeholder for the header.
        outBuf.ensureWritable(HEADER_LENGTH).writerIndex(headEndIdx);

        boolean internalMsg;

        if (msg instanceof NetworkProtocol) {
            // Encode internal message.
            internalMsg = true;

            NetworkProtocol netMsg = (NetworkProtocol)msg;

            encodeInternal(out, codec, netMsg);
        } else {
            // Encode user-defined message.
            internalMsg = false;

            codec.encode(msg, out);
        }

        // Calculate real message length.
        int len = outBuf.writerIndex() - headStartIdx;

        // Magic length value:
        //   negative - for protocol messages
        //   positive - for user messages
        if (internalMsg) {
            len = -len;
        }

        // Update length header.
        outBuf.setInt(headStartIdx, len);
    } catch (CodecException e) {
        throw e;
    } catch (Throwable t) {
        throw new CodecException("Failed to encode message [message=" + msg + ", codec=" + codec + ']', t);
    }
}
 
Example 20
Project: incubator-plc4x   File: IsoTPProtocol.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, IsoOnTcpMessage in, List<Object> out) throws Exception {
    if(logger.isTraceEnabled()) {
        logger.trace("Got Data: {}", ByteBufUtil.hexDump(in.getUserData()));
    }
    logger.debug("ISO TP Message received");

    if (in == null) {
        return;
    }

    ByteBuf userData = in.getUserData();
    if (userData.writerIndex() < 1) {
        return;
    }
    
    int packetStart = userData.readerIndex();
    byte headerLength = userData.readByte();
    int headerEnd = packetStart + headerLength;
    TpduCode tpduCode = TpduCode.valueOf(userData.readByte());
    // Read fixed header part.
    Tpdu tpdu = null;
    List<Parameter> parameters = new LinkedList<>();
    switch (tpduCode) {
        case CONNECTION_REQUEST:
        case CONNECTION_CONFIRM:
            tpdu = decodeConnection(ctx, userData, tpduCode, parameters);
            break;
        case DATA:
            tpdu = decodeData(userData, parameters);
            break;
        case DISCONNECT_REQUEST:
        case DISCONNECT_CONFIRM:
            tpdu = decodeDisconnect(userData, tpduCode, parameters);
            break;
        case TPDU_ERROR:
            tpdu = decodeError(userData, parameters);
            break;
        default:
            logger.trace("Tpdu Code %s not implemented", tpduCode.name());
            break;
    }

    // Read variable header parameters
    while (userData.readerIndex() < headerEnd) {
        Parameter parameter = parseParameter(userData);
        if (parameter != null) {
            parameters.add(parameter);
        }
    }

    if (tpdu != null) {
        // If we got a ConnectionConfirmTpdu response we are currently
        // in the process of establishing a connection with the PLC, so
        // Save some of the information in the session and tell the next
        // layer to negotiate the connection parameters.
        if (tpdu instanceof ConnectionConfirmTpdu) {
            calledTsapParameter = tpdu.getParameter(CalledTsapParameter.class);
            tpduSizeParameter = tpdu.getParameter(TpduSizeParameter.class);
        }
        out.add(new IsoTPMessage(tpdu, userData));
    }
}