Example usage for io.netty.buffer ByteBuf capacity

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

Introduction

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

Prototype

public abstract int capacity();

Source Link

Document

Returns the number of bytes (octets) this buffer can contain.

Usage

From source file:TestTCPServer.java

License:Open Source License

public static void main(String... args) throws Throwable {
    IOService service = new IOService();
    TCPAcceptor acceptor = new TCPAcceptor(service);
    acceptor.setOption(ChannelOption.SO_BACKLOG, 3);
    acceptor.setChildOption(ChannelOption.TCP_NODELAY, true);
    acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true);

    acceptor.bind(4321);//from   w  ww. j  a  v  a 2 s . c  o m
    TCPSocket con = acceptor.accept();
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000);
    byte[] bytea = new byte[buffer.capacity()];
    long bytes;

    System.out.println("Connected " + con.remoteEndpoint());
    bytes = con.receive(buffer);
    while (bytes != -1 && buffer.getByte(0) != 4) {
        buffer.readBytes(bytea, 0, (int) bytes);
        System.out.print(new String(bytea, 0, (int) bytes));
        buffer.readerIndex(0).writerIndex(0);
        con.send(buffer, (int) bytes);
        buffer.readerIndex(0).writerIndex(0);
        bytes = con.receive(buffer);
    }

    System.out.println("Connection closed");
    con.close();

    acceptor.close();
    service.cancel();
}

From source file:alluxio.worker.grpc.AbstractWriteHandlerTest.java

License:Apache License

/**
 * @param buffer buffer to get checksum//from ww  w. ja v  a  2s  .  c om
 * @return the checksum
 */
public static long getChecksum(ByteBuf buffer) {
    long ret = 0;
    for (int i = 0; i < buffer.capacity(); i++) {
        ret += BufferUtils.byteToInt(buffer.getByte(i));
    }
    return ret;
}

From source file:com.addthis.basis.chars.ReadOnlyAsciiBuf.java

License:Apache License

@Override
public String toString() {
    // TODO: if our ByteBuf has a backing array, then we can use the deprecated, ascii-only
    // String constructor : new String(byte[], int, int, int)

    // Can't find a good way around String's stupid always-copy constructor, but by
    // not using content().toString(UTF8), we can at least prevent one extra allocation.
    ///*from w w  w  .  j a v a 2 s  .c om*/
    // ((CharBuffer alloc, CharBuffer toString, new String) -> (char[] alloc, new String))
    //
    // If desperate, _might_ be able to hack it with a dummy CharacterEncoder if there is
    // no security manager. Otherwise have to class path boot etc to get into the lang
    // package. I suppose annoyances like these are why I made this package.
    ByteBuf slice = content().slice();
    char[] values = new char[slice.capacity()];
    if (slice.readableBytes() > 0) {
        for (int i = 0; i < slice.capacity(); i++) {
            values[i] = (char) slice.getByte(i);
        }
    } else {
        return "";
    }
    return new String(values);
}

From source file:com.addthis.meshy.SourceHandler.java

License:Apache License

@Override
public final boolean send(byte[] data, final SendWatcher watcher) {
    synchronized (channels) {
        if (channels.isEmpty()) {
            return false;
        }//from  w w w. j a  va  2  s  . co  m

        int sendType = MeshyConstants.KEY_EXISTING;
        if (sent.compareAndSet(false, true) || DISABLE_CREATION_FRAMES) {
            sendType = targetHandler;
        }

        final ByteBufAllocator alloc = channels.iterator().next().alloc();
        final ByteBuf buffer = allocateSendBuffer(alloc, sendType, session, data);
        final int reportBytes = data.length;
        final int peerCount = channels.size();

        log.trace("{} send {} to {}", this, buffer.capacity(), peerCount);
        List<ChannelFuture> futures = new ArrayList<>(peerCount);
        for (Channel c : channels) {
            futures.add(c.writeAndFlush(buffer.duplicate().retain()));
        }
        AggregateChannelFuture aggregateFuture = new AggregateChannelFuture(futures);
        aggregateFuture.addListener(ignored -> {
            master.sentBytes(reportBytes * peerCount);
            if (watcher != null) {
                watcher.sendFinished(reportBytes);
            }
        });
        buffer.release();
        return true;
    }
}

From source file:com.addthis.meshy.SourceHandler.java

License:Apache License

protected boolean sendToSingleTarget(Channel channel, byte[] data) {
    int sendType = MeshyConstants.KEY_EXISTING;
    final ByteBufAllocator alloc = channel.alloc();
    final ByteBuf buffer = allocateSendBuffer(alloc, sendType, session, data);

    final int reportBytes = data.length;
    log.trace("{} send {} to {}", this, buffer.capacity(), channel);
    channel.writeAndFlush(buffer.duplicate().retain()).addListener(ignored -> {
        master.sentBytes(reportBytes);/*from  ww w.  ja  va2s. co m*/
    });
    buffer.release();
    return true;
}

From source file:com.chiorichan.util.ObjectUtil.java

License:Mozilla Public License

public static String hexDump(ByteBuf buf, int highlightIndex) {
    if (buf == null)
        return "Buffer: null!";

    if (buf.capacity() < 1) {
        return "Buffer: 0B!";
    }/*from  w  w w . ja  v  a  2  s .c  o  m*/

    StringBuilder dump = new StringBuilder();

    final int startIndex = 0;
    final int endIndex = buf.capacity();
    final int length = endIndex - startIndex;
    final int fullRows = length >>> 4;
    final int remainder = length & 0xF;

    int highlightRow = -1;

    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    if (highlightIndex > 0) {
        highlightRow = highlightIndex >>> 4;
        highlightIndex = highlightIndex - (16 * highlightRow) - 1;

        dump.append(NEWLINE + "|        |" + Strings.repeat("   ", highlightIndex) + " $$"
                + Strings.repeat("   ", 15 - highlightIndex));
        dump.append(" |" + Strings.repeat(" ", highlightIndex) + "$" + Strings.repeat(" ", 15 - highlightIndex)
                + "|");
    }

    // Dump the rows which have 16 bytes.
    for (int row = 0; row < fullRows; row++) {
        int rowStartIndex = row << 4;

        // Per-row prefix.
        appendHexDumpRowPrefix(dump, row, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + 16;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(" |");

        // ASCII dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append('|');

        if (highlightIndex > 0 && highlightRow == row + 1)
            dump.append(" <--");
    }

    // Dump the last row which has less than 16 bytes.
    if (remainder != 0) {
        int rowStartIndex = fullRows << 4;
        appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + remainder;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");

        // Ascii dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow > fullRows + 1)
            dump.append(" <--");
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");

    return dump.toString();
}

From source file:com.chiorichan.util.ServerFunc.java

License:Mozilla Public License

public static String hexDump(ByteBuf buf, int highlightIndex) {
    if (buf == null)
        return "Buffer: null!";

    if (buf.capacity() < 1)
        return "Buffer: 0B!";

    StringBuilder dump = new StringBuilder();

    final int startIndex = 0;
    final int endIndex = buf.capacity();
    final int length = endIndex - startIndex;
    final int fullRows = length >>> 4;
    final int remainder = length & 0xF;

    int highlightRow = -1;

    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    if (highlightIndex > 0) {
        highlightRow = highlightIndex >>> 4;
        highlightIndex = highlightIndex - 16 * highlightRow - 1;

        dump.append(NEWLINE + "|        |" + Strings.repeat("   ", highlightIndex) + " $$"
                + Strings.repeat("   ", 15 - highlightIndex));
        dump.append(" |" + Strings.repeat(" ", highlightIndex) + "$" + Strings.repeat(" ", 15 - highlightIndex)
                + "|");
    }/*from  w  ww  . j  a v  a 2  s. c  o  m*/

    // Dump the rows which have 16 bytes.
    for (int row = 0; row < fullRows; row++) {
        int rowStartIndex = row << 4;

        // Per-row prefix.
        appendHexDumpRowPrefix(dump, row, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + 16;
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        dump.append(" |");

        // ASCII dump
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow == row + 1)
            dump.append(" <--");
    }

    // Dump the last row which has less than 16 bytes.
    if (remainder != 0) {
        int rowStartIndex = fullRows << 4;
        appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + remainder;
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");

        // Ascii dump
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow > fullRows + 1)
            dump.append(" <--");
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");

    return dump.toString();
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

private Integer extractLength(ByteBuf buffer) {
    int len = (int) parseLengthHeader(buffer);

    // scan utf8 symbols if needed
    if (buffer.capacity() > buffer.readerIndex() + len
            && !isCurrentDelimiter(buffer, buffer.readerIndex() + len)) {
        int index = charsScanner.findTailIndex(buffer, buffer.readerIndex(), buffer.capacity(), len);
        len = index - buffer.readerIndex();
    }/*from  w ww .  j a  va2s  .co  m*/
    return len;
}

From source file:com.corundumstudio.socketio.parser.UTF8CharsScannerTest.java

License:Apache License

@Test
public void testfindTailIndex() {
    String str = "132 4  \ufffd\ufffd  \\";
    UTF8CharsScanner p = new UTF8CharsScanner();
    ByteBuf b = Unpooled.wrappedBuffer(str.getBytes());
    int len = p.findTailIndex(b, b.readerIndex(), b.capacity(), str.length());
    Assert.assertEquals(b.capacity(), len);
}

From source file:com.flysoloing.learning.network.netty.udt.echo.message.MsgEchoClientHandler.java

License:Apache License

public MsgEchoClientHandler() {
    super(false);
    final ByteBuf byteBuf = Unpooled.buffer(MsgEchoClient.SIZE);
    for (int i = 0; i < byteBuf.capacity(); i++) {
        byteBuf.writeByte((byte) i);
    }/* ww w.  j a  va2 s .c  o m*/
    message = new UdtMessage(byteBuf);
}