Example usage for io.netty.buffer ByteBuf clear

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

Introduction

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

Prototype

public abstract ByteBuf clear();

Source Link

Document

Sets the readerIndex and writerIndex of this buffer to 0 .

Usage

From source file:org.asynchttpclient.request.body.generators.ByteArrayBodyGeneratorTest.java

License:Open Source License

@Test(groups = "standalone")
public void testSingleRead() throws IOException {
    final int srcArraySize = chunkSize - 1;
    final byte[] srcArray = new byte[srcArraySize];
    random.nextBytes(srcArray);//w  w  w.  j  a v  a  2 s  . c  o  m

    final ByteArrayBodyGenerator babGen = new ByteArrayBodyGenerator(srcArray);
    final Body body = babGen.createBody();

    final ByteBuf chunkBuffer = Unpooled.buffer(chunkSize);

    // should take 1 read to get through the srcArray
    body.transferTo(chunkBuffer);
    assertEquals(chunkBuffer.readableBytes(), srcArraySize, "bytes read");
    chunkBuffer.clear();

    assertEquals(body.transferTo(chunkBuffer), BodyState.STOP, "body at EOF");
}

From source file:org.asynchttpclient.request.body.generators.ByteArrayBodyGeneratorTest.java

License:Open Source License

@Test(groups = "standalone")
public void testMultipleReads() throws IOException {
    final int srcArraySize = (3 * chunkSize) + 42;
    final byte[] srcArray = new byte[srcArraySize];
    random.nextBytes(srcArray);/*from   ww w .ja v  a2 s  .c  o  m*/

    final ByteArrayBodyGenerator babGen = new ByteArrayBodyGenerator(srcArray);
    final Body body = babGen.createBody();

    final ByteBuf chunkBuffer = Unpooled.buffer(chunkSize);

    int reads = 0;
    int bytesRead = 0;
    while (body.transferTo(chunkBuffer) != BodyState.STOP) {
        reads += 1;
        bytesRead += chunkBuffer.readableBytes();
        chunkBuffer.clear();
    }
    assertEquals(reads, 4, "reads to drain generator");
    assertEquals(bytesRead, srcArraySize, "bytes read");
}

From source file:org.dcache.xrootd.core.XrootdHandshakeHandler.java

License:Open Source License

@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() >= CLIENT_HANDSHAKE_LEN) {
        byte[] handshake = new byte[20];
        in.readBytes(handshake);/*from   w w  w . j  a va  2s  . com*/

        if (!Arrays.equals(handshake, HANDSHAKE_REQUEST)) {
            in.clear();
            LOGGER.warn("{} Received invalid handshake.", ctx.channel());
            ctx.close();
            return;
        }

        ctx.writeAndFlush(Unpooled.wrappedBuffer(response));
        ctx.channel().pipeline().remove(this);
    }
}

From source file:org.eclipse.moquette.parser.netty.SubAckDecoderTest.java

License:Open Source License

private void initHeaderQos(ByteBuf buff, int messageID, AbstractMessage.QOSType... qoss)
        throws IllegalAccessException {
    buff.clear().writeByte(AbstractMessage.SUBACK << 4)
            .writeBytes(Utils.encodeRemainingLength(2 + qoss.length));

    buff.writeShort(messageID);/*w  w w. j a  v a 2s  . c  om*/
    for (AbstractMessage.QOSType qos : qoss) {
        buff.writeByte(qos.ordinal());
    }
}

From source file:org.eclipse.moquette.parser.netty.SubscribeDecoderTest.java

License:Open Source License

private void initMultiTopic(ByteBuf buff, int messageID, SubscribeMessage.Couple... topics)
        throws IllegalAccessException {
    ByteBuf topicBuffer = Unpooled.buffer(4);
    topicBuffer.writeShort(messageID);/*from  w  w w  .  j av a 2s .c  o m*/
    for (SubscribeMessage.Couple couple : topics) {
        topicBuffer.writeBytes(Utils.encodeString(couple.getTopicFilter()));
        topicBuffer.writeByte(couple.getQos());
    }

    buff.clear().writeByte(AbstractMessage.SUBSCRIBE << 4 | (byte) 0x02)
            .writeBytes(Utils.encodeRemainingLength(topicBuffer.readableBytes()));
    buff.writeBytes(topicBuffer);
}

From source file:org.eclipse.moquette.parser.netty.SubscribeDecoderTest.java

License:Open Source License

private void initPollutedTopic(ByteBuf buff, int messageID, SubscribeMessage.Couple topic)
        throws IllegalAccessException {
    ByteBuf topicBuffer = Unpooled.buffer(4);
    topicBuffer.writeShort(messageID);//  w  ww  . ja  v a 2 s.com
    topicBuffer.writeBytes(Utils.encodeString(topic.getTopicFilter()));
    topicBuffer.writeByte(0xF0 | topic.getQos());

    buff.clear().writeByte(AbstractMessage.SUBSCRIBE << 4 | (byte) 0x02)
            .writeBytes(Utils.encodeRemainingLength(topicBuffer.readableBytes()));
    buff.writeBytes(topicBuffer);
}

From source file:org.fusesource.hawtdispatch.netty.HawtSocketChannel.java

License:Apache License

@Override
protected void doFlushByteBuffer(ByteBuf buf) throws Exception {
    if (!buf.isReadable()) {
        // Reset reader/writerIndex to 0 if the buffer is empty.
        buf.clear();
        return;//  w w  w .j av a 2s.com
    }

    for (int i = config().getWriteSpinCount() - 1; i >= 0; i--) {
        int localFlushedAmount = doWriteBytes(buf, i == 0);
        if (localFlushedAmount > 0) {
            break;
        }
        if (!buf.isReadable()) {
            // Reset reader/writerIndex to 0 if the buffer is empty.
            buf.clear();
            break;
        }
    }
}

From source file:org.hawkular.metrics.clients.ptrans.DemuxHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, @SuppressWarnings("rawtypes") List out)
        throws Exception {

    if (msg.readableBytes() < 5) {
        msg.clear();
        ctx.close();//from   w w  w . j a va2s . c om
        return;
    }
    ChannelPipeline pipeline = ctx.pipeline();

    String data = msg.toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled()) {
        logger.debug("Incoming: [" + data + "]");
    }

    boolean done = false;

    if (data.contains("type=metric")) {
        pipeline.addLast(new SyslogEventDecoder());
        pipeline.addLast("forwarder", new RestForwardingHandler(configuration));
        pipeline.remove(this);
        done = true;
    } else if (!data.contains("=")) {
        String[] items = data.split(" |\\n");
        if (items.length % 3 == 0) {
            pipeline.addLast("encoder", new GraphiteEventDecoder());
            pipeline.addLast("forwarder", forwardingHandler);
            pipeline.remove(this);
            done = true;
        }
    }
    if (!done) {
        logger.warn("Unknown input [" + data + "], ignoring");
        msg.clear();
        ctx.close();
    }
}

From source file:org.hawkular.metrics.clients.ptrans.ganglia.UdpGangliaDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket in, List<Object> out) throws Exception {
    ByteBuf msg = in.content();
    if (msg.readableBytes() < 5) {
        msg.clear();
        ctx.close();/* www .jav a2  s. c o  m*/
        return;
    }

    short magic = msg.getUnsignedByte(3);
    if (msg.getByte(0) == 0 && msg.getByte(1) == 0 && msg.getByte(2) == 0 && magic == 134) {

        // We have an UnsafeSuperDuperBuffer, so we need to "manually" pull the bytes from it.
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);

        XdrBufferDecodingStream stream = new XdrBufferDecodingStream(bytes);
        stream.beginDecoding();
        stream.xdrDecodeInt(); // Packet id , should be 134 as in above magic => type of value
        String host = stream.xdrDecodeString();
        String metricName = stream.xdrDecodeString();
        stream.xdrDecodeInt();
        String format = stream.xdrDecodeString(); // e.g. .0f for a number
        String value;
        if (format.endsWith("f")) {
            value = String.valueOf(stream.xdrDecodeFloat());
        } else {
            value = stream.xdrDecodeString();
        }
        stream.endDecoding();

        try {
            String path = host + "." + metricName;
            Double val = Double.parseDouble(value);

            SingleMetric metric = new SingleMetric(path, System.currentTimeMillis(), val);
            out.add(metric);
        } catch (Exception e) {
            e.printStackTrace();
            msg.clear();
            ctx.close();

        }
    }

}

From source file:org.hawkular.metrics.clients.ptrans.statsd.StatsdDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    ByteBuf buf = msg.content();

    if (buf.readableBytes() < 3) {
        // Not enough data - nothing to do.
        buf.clear();
        ctx.close();/*from  w  w w .ja  v a2 s  .  c o  m*/
        return;
    }

    String packet = buf.toString(CharsetUtil.UTF_8).trim();
    if (!packet.contains(":")) {
        buf.clear();
        ctx.close();
        return;
    }

    String name = packet.substring(0, packet.indexOf(":"));
    String remainder = packet.substring(packet.indexOf(":") + 1);
    String valString;
    String type;
    if (remainder.contains("|")) {
        valString = remainder.substring(0, remainder.indexOf("|"));
        type = remainder.substring(remainder.indexOf("|") + 1);
    } else {
        valString = remainder;
        type = "";
    }
    Double value = Double.valueOf(valString);
    SingleMetric singleMetric = new SingleMetric(name, System.currentTimeMillis(), value,
            MetricType.from(type));
    out.add(singleMetric);
}