Example usage for io.netty.buffer ByteBuf writerIndex

List of usage examples for io.netty.buffer ByteBuf writerIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf writerIndex.

Prototype

public abstract int writerIndex();

Source Link

Document

Returns the writerIndex of this buffer.

Usage

From source file:com.quavo.osrs.network.protocol.codec.update.encrypt.XOREncryptionEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, XOREncryptionResponse msg, ByteBuf out) throws Exception {
    if (msg.getKey() != 0) {
        for (int i = 0; i < out.writerIndex(); i++) {
            out.setByte(i, out.getByte(i) ^ msg.getKey());
        }//from  ww  w  .  j a  v a 2s .  co m
    }

    ctx.pipeline().remove(this);
}

From source file:com.spotify.ffwd.riemann.RiemannSerialization.java

License:Apache License

public ByteBuf encodeAll0(Collection<Object> messages) throws IOException {
    final Proto.Msg.Builder builder = Proto.Msg.newBuilder();

    for (final Object d : messages) {
        if (d instanceof Metric) {
            builder.addEvents(encodeMetric0((Metric) d));
        } else if (d instanceof Event) {
            builder.addEvents(encodeEvent0((Event) d));
        }/*w  ww.  j  av a2s . co m*/
    }

    final Proto.Msg m = builder.build();

    final ByteBuf work = Unpooled.buffer();

    try (final ByteBufOutputStream output = new ByteBufOutputStream(work)) {
        m.writeTo(output);

        final ByteBuf result = Unpooled.buffer();

        result.writeInt(work.writerIndex());
        result.writeBytes(work);

        return result;
    } finally {
        work.release();
    }
}

From source file:com.spotify.folsom.client.binary.RequestTestTemplate.java

License:Apache License

protected void assertEOM(final ByteBuf b) {
    assertEquals(b.readerIndex(), b.writerIndex());
}

From source file:com.spotify.netty.handler.codec.zmtp.ZMTPUtils.java

License:Apache License

/**
 * Create a string from binary data, keeping printable ascii and hex encoding everything else.
 *
 * @param data The data/*from   w w w  . j a  v a 2 s  . c  om*/
 * @return A string representation of the data
 */
public static String toString(final ByteBuf data) {
    if (data == null) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    for (int i = data.readerIndex(); i < data.writerIndex(); i++) {
        final byte b = data.getByte(i);
        if (b > 31 && b < 127) {
            if (b == '%') {
                sb.append('%');
            }
            sb.append((char) b);
        } else {
            sb.append('%');
            sb.append(String.format("%02X", b));
        }
    }
    return sb.toString();
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPFramingDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws ZMTPParsingException {
    while (in.isReadable()) {
        if (!headerParsed) {
            final int mark = in.readerIndex();
            headerParsed = header.read(in);
            if (!headerParsed) {
                // Wait for more data
                in.readerIndex(mark);//from  w w  w  .j  av a 2s. c  o m
                return;
            }
            decoder.header(ctx, header.length(), header.more(), out);
            remaining = header.length();
        }

        final int writerMark = in.writerIndex();
        final int n = (int) min(remaining, in.readableBytes());
        final int readerMark = in.readerIndex();
        in.writerIndex(readerMark + n);
        decoder.content(ctx, in, out);
        in.writerIndex(writerMark);
        final int read = in.readerIndex() - readerMark;
        remaining -= read;
        if (remaining > 0) {
            // Wait for more data
            return;
        }
        if (!header.more()) {
            decoder.finish(ctx, out);
        }
        headerParsed = false;
    }
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPMessage.java

License:Apache License

/**
 * Create a human readable string representation of binary data, keeping printable ascii and hex
 * encoding everything else./*from  www  .j  av  a  2 s  .  c  o m*/
 *
 * @param data The data
 * @return A human readable string representation of the data.
 */
private static String toString(final ByteBuf data) {
    if (data == null) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    for (int i = data.readerIndex(); i < data.writerIndex(); i++) {
        final byte b = data.getByte(i);
        if (b > 31 && b < 127) {
            if (b == '%') {
                sb.append('%');
            }
            sb.append((char) b);
        } else {
            sb.append('%');
            sb.append(String.format("%02X", b));
        }
    }
    return sb.toString();
}

From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Returns the number of bytes between the readerIndex of the haystack and
 * the first needle found in the haystack.  -1 is returned if no needle is
 * found in the haystack.//from  w  ww  . ja  v  a 2  s. c  om
 */
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
    for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++) {
        int haystackIndex = i;
        int needleIndex;
        for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex++) {
            if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
                break;
            } else {
                haystackIndex++;
                if (haystackIndex == haystack.writerIndex() && needleIndex != needle.capacity() - 1) {
                    return -1;
                }
            }
        }

        if (needleIndex == needle.capacity()) {
            // Found the needle from the haystack!
            return i - haystack.readerIndex();
        }
    }
    return -1;
}

From source file:com.tesora.dve.db.mysql.libmy.BufferedExecute.java

License:Open Source License

public void marshallMessage(ByteBuf stmtExecuteBuf) {
    //header and type are marshalled by parent class.

    int rowsToFlush = this.size();

    MyNullBitmap nullBitmap = new MyNullBitmap(rowsToFlush * columnsPerTuple,
            MyNullBitmap.BitmapType.EXECUTE_REQUEST);

    //            stmtExecuteBuf.writeByte(MSPComStmtExecuteRequestMessage.TYPE_IDENTIFIER);
    stmtExecuteBuf.writeInt(this.stmtID);
    stmtExecuteBuf.writeZero(1); // flags
    stmtExecuteBuf.writeInt(1); // iteration count
    int nullBitmapIndex = stmtExecuteBuf.writerIndex();
    stmtExecuteBuf.writeZero(nullBitmap.length());

    // write the parameter types, as appropriate
    if (this.needsNewParams) {
        stmtExecuteBuf.writeByte(1);//from  w w w .  j a  v  a2  s  .c  o  m

        for (int i = 0; i < rowsToFlush; ++i) {
            stmtExecuteBuf.writeBytes(metadataFragment.slice());
        }

    } else
        stmtExecuteBuf.writeZero(1);

    // Copy the parameter values, updating the null bitmap
    // null bitmap is 1-based
    int rowsWritten = 0;
    int execStmtColIndex = 1;
    for (Iterator<MyBinaryResultRow> i = this.queuedPackets.iterator(); i.hasNext();) {
        MyBinaryResultRow rowPacketData = i.next();

        //                ByteBuf rowSet = Unpooled.buffer(rowPacketData.binRow.sizeInBytes()).order(ByteOrder.LITTLE_ENDIAN);
        //                rowPacketData.binRow.marshallFullMessage(rowSet);

        //                while (rowSet.isReadable() && rowsToWrite-- > 0) {
        //            System.out.println(siteCtx + "/" + myi + ": adding row");
        //                    int payloadLen = rowSet.readMedium();
        //                    rowSet.skipBytes(1);
        //                    byte packetHeader = rowSet.readByte();
        //                    if (packetHeader != 0)
        //                        throw new PEException("Out-of-sync reading redist rowSet");
        int bitmapSize = MyNullBitmap.computeSize(columnsPerTuple, MyNullBitmap.BitmapType.RESULT_ROW);
        int rowFields = rowPacketData.size();
        for (int colIndex = 1; colIndex <= columnsPerTuple; colIndex++, execStmtColIndex++) {
            //we are looping through target columns, which may exceed the source column count.
            if ((colIndex <= rowFields) && rowPacketData.isNull(colIndex - 1 /* zero based indexing */))
                nullBitmap.setBit(execStmtColIndex);
        }
        //                    rowSet.skipBytes(bitmapSize);

        //                    stmtExecuteBuf.writeBytes(rowSet, payloadLen-bitmapSize-1);
        rowPacketData.marshallRawValues(stmtExecuteBuf);
        ++rowsWritten;

    }

    if (rowsWritten != rowsToFlush) {
        //         System.out.println("At failure " + stmtExecuteBuf + "/" + siteCtx);
        throw new PECodingException("Asked to write " + rowsToFlush + " rows, but only " + rowsWritten
                + " were (" + rowsToFlush + " were made available to flushBuffers)");
    }

    // Go back and set the null bitmap and the payload size
    stmtExecuteBuf.setBytes(nullBitmapIndex, nullBitmap.getBitmapArray());
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPAuthenticateV10MessageMessage.java

License:Open Source License

public static void write(ByteBuf out, String userName, String userPassword, String salt, Charset charset,
        int mysqlCharsetID, int capabilitiesFlag) {
    ByteBuf leBuf = out.order(ByteOrder.LITTLE_ENDIAN);

    int payloadSizeIndex = leBuf.writerIndex();
    leBuf.writeMedium(0);/*from  w w w.j  a  v a2s .  c  om*/
    leBuf.writeByte(1);
    int payloadStartIndex = leBuf.writerIndex();
    leBuf.writeInt(capabilitiesFlag);
    leBuf.writeInt(MAX_PACKET_SIZE);
    //      leBuf.writeByte(serverGreeting.getServerCharsetId());
    leBuf.writeByte(mysqlCharsetID);
    leBuf.writeZero(23);
    leBuf.writeBytes(userName.getBytes(charset));
    leBuf.writeZero(1);

    if ((capabilitiesFlag & ClientCapabilities.CLIENT_SECURE_CONNECTION) > 0) {

        byte[] securePassword = computeSecurePassword(userPassword, salt);
        leBuf.writeByte(securePassword.length);
        leBuf.writeBytes(securePassword);
    } else {
        leBuf.writeBytes(userPassword.getBytes(charset));
        leBuf.writeZero(1);
    }

    leBuf.setMedium(payloadSizeIndex, leBuf.writerIndex() - payloadStartIndex);
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPComStmtExecuteRequestMessage.java

License:Open Source License

@Override
protected void marshall(ParsedData state, ByteBuf destination) {
    ByteBuf leBuf = destination.order(ByteOrder.LITTLE_ENDIAN);
    leBuf.writeByte(TYPE_IDENTIFIER);//ww  w. j  a v a 2  s.c  o m
    leBuf.writeInt((int) state.statementID);
    leBuf.writeByte(state.flags);
    leBuf.writeInt((int) state.iterationCount);
    if (state.metadata == null)
        throw new IllegalStateException("Cannot build execute request, no prepare metadata provided.");

    int numParams = state.metadata.getNumParams();
    if (numParams > 0) {
        MyNullBitmap nullBitmap = new MyNullBitmap(numParams, MyNullBitmap.BitmapType.EXECUTE_REQUEST);
        int bitmapIndex = leBuf.writerIndex();
        leBuf.writeZero(nullBitmap.length());
        if (state.metadata.isNewParameterList()) {
            leBuf.writeByte(1);
            for (MyParameter param : state.metadata.getParameters()) {
                leBuf.writeByte(param.getType().getByteValue());
                leBuf.writeZero(1);
            }
        } else {
            leBuf.writeZero(1);
        }
        List<Object> params = state.values;
        for (int i = 0; i < params.size(); ++i) {
            if (params.get(i) != null)
                DBTypeBasedUtils.getJavaTypeFunc(params.get(i).getClass()).writeObject(leBuf, params.get(i));
            else
                nullBitmap.setBit(i + 1);
        }
        leBuf.setBytes(bitmapIndex, nullBitmap.getBitmapArray());
    }
}