Example usage for io.netty.buffer ByteBuf discardReadBytes

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

Introduction

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

Prototype

public abstract ByteBuf discardReadBytes();

Source Link

Document

Discards the bytes between the 0th index and readerIndex .

Usage

From source file:com.github.subalakr.yasjl.Bench.java

License:Apache License

public void run() throws Exception {
    for (int i = 0; i < iterations; i++) {
        ByteBuf inBuf = Unpooled.buffer();
        JsonPointer[] jsonPointers = { new JsonPointer("/metrics/resultCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();//from  ww w  . j a  v  a 2s  . com
            }
        }), new JsonPointer("/metrics/warningCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/metrics/errorCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/results/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                rowsEmitted.getAndIncrement();
                buf.release();
            }
        }), new JsonPointer("/errors/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/warnings/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), };
        parser.initialize(inBuf, jsonPointers);
        inBuf.writeBytes(inJson.getBytes());
        long start = System.currentTimeMillis();
        parser.parse();
        long currentRun = System.currentTimeMillis() - start;
        totalDuration += currentRun;
        totalBytesRead += inJsonSz;
        inBuf.discardReadBytes();
        inBuf.release();
    }
}

From source file:com.mapr.franz.netty.FranzClientHandler.java

License:Apache License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) {
    ByteBuf out = ctx.nextOutboundByteBuffer();
    out.discardReadBytes();
    out.writeBytes(in);/* w  w  w  .  j a  v  a 2s. com*/
    ctx.flush();
}

From source file:com.mastfrog.scamper.MessageTypeRegistry.java

License:Open Source License

/**
 * Decode a message type from the <i>current position</i> of the
 * passed ByteBuf./*ww  w .jav a  2 s  .  co m*/
 * @param buf
 * @return 
 */
public MessageType forByteBuf(ByteBuf buf) {
    if (buf.readableBytes() >= 2) {
        byte one = buf.readByte();
        byte two = buf.readByte();
        for (MessageType mt : types) {
            if (mt.match(one, two)) {
                buf.discardReadBytes();
                return mt;
            }
        }
        return MessageType.createUnknown(one, two);
    }
    buf.resetReaderIndex();
    return MessageType.createUnknown((byte) 0, (byte) 0);
}

From source file:com.witjit.game.server.communication.handler.ClientDispatchHandler.java

/**
 *
 * @param ctx//from ww  w .  ja v  a  2  s. c o  m
 * @param msg
 * @throws Exception
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        //TODO: handle error message.
        return;
    }

    ByteBuf mb = (ByteBuf) msg;

    byte target = mb.readByte();
    short id = mb.readShort();
    mb.discardReadBytes();

    ClientChannelData channelData = ChannelData.get(ctx.channel());
    ClientSessionPoint sessionPoint = channelData.getBindSessionPoint();
    sessionPoint.transit(target, MessageID.make(id), msg);
}

From source file:com.zextras.modules.chat.server.xmpp.netty.XmlSubTagTokenizer.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects)
        throws Exception {
    int idx = byteBuf.bytesBefore(sTokenEnd);
    if (idx == -1) {
        return;//from  w  ww  .  j  a  v  a2  s.  co m
    }

    String token = byteBuf.toString(0, idx + 1, mCharset);
    byteBuf.readerIndex(byteBuf.readerIndex() + idx + 1);
    byteBuf.discardReadBytes();
    objects.add(token);
}

From source file:impl.underdark.transport.bluetooth.BtLink.java

License:Open Source License

private void inputLoop() {
    // Input I/O thread.

    sendHelloFrame();//from  w  w  w.j  a  v  a  2  s.  c o  m

    int bufferSize = 4096;
    ByteBuf inputData = Unpooled.buffer(bufferSize);
    inputData.order(ByteOrder.BIG_ENDIAN);

    try {
        int len;
        while (true) {
            inputData.ensureWritable(bufferSize, true);
            len = inputStream.read(inputData.array(), inputData.writerIndex(), bufferSize);
            if (len <= 0)
                break;

            inputData.writerIndex(inputData.writerIndex() + len);

            if (!formFrames(inputData))
                break;

            inputData.discardReadBytes();
            inputData.capacity(inputData.writerIndex() + bufferSize);
        } // while
    } catch (InterruptedIOException ex) {
        Logger.warn("bt input timeout: {}", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    } catch (Exception ex) {
        Logger.warn("bt input read failed.", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    }

    Logger.debug("bt input read end.");
    notifyDisconnect();

}

From source file:impl.underdark.transport.nsd.NsdLink.java

License:Open Source License

private void inputLoop() {
    // Input thread.
    final int bufferSize = 4096;
    ByteBuf inputData = Unpooled.buffer(bufferSize);
    inputData.order(ByteOrder.BIG_ENDIAN);

    try {//  ww w. ja v  a2s  .  c  o m
        int len;
        while (true) {
            inputData.ensureWritable(bufferSize, true);
            len = inputStream.read(inputData.array(), inputData.writerIndex(), bufferSize);
            if (len <= 0)
                break;

            inputData.writerIndex(inputData.writerIndex() + len);

            if (!formFrames(inputData))
                break;

            inputData.discardReadBytes();
            inputData.capacity(inputData.writerIndex() + bufferSize);
        } // while
    } catch (InterruptedIOException ex) {
        Logger.warn("nsd input timeout: {}", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    } catch (Exception ex) {
        Logger.warn("nsd input read failed: {}", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    }

    Logger.debug("nsd input read end");
    notifyDisconnect();
}

From source file:info.zhoumin.dat.AbstractDoubleArrayTrie.java

License:Apache License

private boolean branchInTail(int sepNode, int c, ByteBuf suffix, V data) {
    /* adjust separate point in old path */
    int oldTail = getTailIndex(sepNode);
    ByteBuf oldSuffix = tail.getSuffix(oldTail);
    if (oldSuffix == null)
        return false;

    byte oldByte, newByte;
    int s = sepNode;
    suffix.resetReaderIndex();// w w  w .  j  a  va2s .  c  o m
    oldSuffix.resetReaderIndex();
    do {
        newByte = suffix.readByte();
        oldByte = oldSuffix.readByte();
        if (newByte != oldByte)
            break;
        int t = insertBranch(s, newByte + 1);
        if (TRIE_INDEX_ERROR == t) {
            // /* failed, undo previous insertions and return error */
            // da_prune_upto (trie->da, sep_node, s);
            // trie_da_set_tail_index (trie->da, sep_node, old_tail);
            // throw new RuntimeException("error happened!");
            return false;
        }
        s = t;
    } while (suffix.isReadable() && oldSuffix.isReadable());

    int oldDA = insertBranch(s, oldByte + 1);
    if (TRIE_INDEX_ERROR == oldDA) {
        // /* failed, undo previous insertions and return error */
        // da_prune_upto (trie->da, sep_node, s);
        // trie_da_set_tail_index (trie->da, sep_node, old_tail);
        // throw new RuntimeException("error happened!");
        return false;
    }

    tail.setSuffix(oldTail, oldSuffix.discardReadBytes().copy());
    setTailIndex(oldDA, oldTail);

    /* insert the new branch at the new separate point */
    return branchInBranch(s, newByte + 1, suffix.discardReadBytes().copy(), data);
}

From source file:io.lettuce.core.protocol.CommandHandler.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException {

    if (pristine && stack.isEmpty() && buffer.isReadable()) {

        if (debugEnabled) {
            logger.debug("{} Received response without a command context (empty stack)", logPrefix());
        }//from   w  ww  .j a v a2 s. co  m

        if (consumeResponse(buffer)) {
            pristine = false;
        }

        return;
    }

    while (canDecode(buffer)) {

        RedisCommand<?, ?, ?> command = stack.peek();
        if (debugEnabled) {
            logger.debug("{} Stack contains: {} commands", logPrefix(), stack.size());
        }

        pristine = false;

        try {
            if (!decode(ctx, buffer, command)) {
                return;
            }
        } catch (Exception e) {

            ctx.close();
            throw e;
        }

        if (isProtectedMode(command)) {
            onProtectedMode(command.getOutput().getError());
        } else {

            if (canComplete(command)) {
                stack.poll();

                try {
                    complete(command);
                } catch (Exception e) {
                    logger.warn("{} Unexpected exception during request: {}", logPrefix, e.toString(), e);
                }
            }
        }

        afterDecode(ctx, command);
    }

    if (buffer.refCnt() != 0) {
        buffer.discardReadBytes();
    }
}

From source file:io.lettuce.core.pubsub.PubSubCommandHandler.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*w  w w . jav a 2s .co m*/
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException {

    if (!getStack().isEmpty()) {
        super.decode(ctx, buffer);
    }

    ReplayOutput<K, V> replay;
    while ((replay = queue.poll()) != null) {

        replay.replay(output);
        endpoint.notifyMessage(output);
        output = new PubSubOutput<>(codec);
    }

    while (super.getStack().isEmpty() && buffer.isReadable()) {

        if (!super.decode(buffer, output)) {
            return;
        }

        endpoint.notifyMessage(output);
        output = new PubSubOutput<>(codec);
    }

    buffer.discardReadBytes();

}