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:sailfish.remoting.ProtocolTest.java

License:Apache License

@Test
public void testRequestProtocol() throws SailfishException {
    RequestProtocol send = RequestProtocol.newInstance();
    send.body(new byte[] { 1, 2, 3, 4 });
    send.compressType(CompressType.NON_COMPRESS);
    send.heartbeat(false);/* w ww.j  a v a 2s.c  om*/
    send.langType(LangType.JAVA);
    send.oneway(false);
    send.opcode((short) 1);
    send.packetId(1);
    send.serializeType(SerializeType.NON_SERIALIZE);

    ByteBuf output = ByteBufAllocator.DEFAULT.buffer(128);
    send.serialize(output);

    Assert.assertTrue(output.readShort() == RemotingConstants.SAILFISH_MAGIC);
    RequestProtocol receive = RequestProtocol.newInstance();
    Assert.assertTrue(send == receive);

    receive.deserialize(output, output.readInt());
    Assert.assertArrayEquals(send.body(), receive.body());
    Assert.assertTrue(receive.compressType() == CompressType.NON_COMPRESS);
    Assert.assertFalse(receive.heartbeat());
    Assert.assertTrue(receive.langType() == LangType.JAVA);
    Assert.assertFalse(receive.oneway());
    Assert.assertTrue(1 == receive.opcode());
    Assert.assertTrue(1 == receive.packetId());
    Assert.assertTrue(receive.serializeType() == SerializeType.NON_SERIALIZE);

    output.clear();
    send.body(new byte[] { -1, -1, -1, -1 });
    send.heartbeat(true);
    send.oneway(true);
    send.langType(LangType.CPP);
    send.serializeType(SerializeType.PROTOBUF_SERIALIZE);
    send.compressType(CompressType.LZ4_COMPRESS);
    send.opcode((short) 100);
    send.packetId(1000);
    send.serialize(output);

    Assert.assertTrue(output.readShort() == RemotingConstants.SAILFISH_MAGIC);
    receive = RequestProtocol.newInstance();
    Assert.assertTrue(send == receive);

    receive.deserialize(output, output.readInt());
    Assert.assertArrayEquals(send.body(), receive.body());
    Assert.assertTrue(receive.compressType() == CompressType.LZ4_COMPRESS);
    Assert.assertTrue(receive.heartbeat());
    Assert.assertTrue(receive.langType() == LangType.CPP);
    Assert.assertTrue(receive.oneway());
    Assert.assertTrue(100 == receive.opcode());
    Assert.assertTrue(1000 == receive.packetId());
    Assert.assertTrue(receive.serializeType() == SerializeType.PROTOBUF_SERIALIZE);
}

From source file:sailfish.remoting.ProtocolTest.java

License:Apache License

@Test
public void testResponseProtocol() throws SailfishException {
    ResponseProtocol send = ResponseProtocol.newInstance();
    send.body(new byte[] { 1, 2, 3, 4 });
    send.compressType(CompressType.GZIP_COMPRESS);
    send.heartbeat(false);// w  ww .j  av a2 s. c  om
    send.packetId(1);
    send.result((byte) 0);
    send.serializeType(SerializeType.JDK_SERIALIZE);

    ByteBuf output = ByteBufAllocator.DEFAULT.buffer(128);
    send.serialize(output);

    ResponseProtocol receive = ResponseProtocol.newInstance();
    Assert.assertTrue(send == receive);
    Assert.assertTrue(output.readShort() == RemotingConstants.SAILFISH_MAGIC);
    receive.deserialize(output, output.readInt());
    Assert.assertArrayEquals(send.body(), receive.body());
    Assert.assertTrue(send.compressType() == CompressType.GZIP_COMPRESS);
    Assert.assertTrue(send.serializeType() == SerializeType.JDK_SERIALIZE);
    Assert.assertFalse(receive.heartbeat());
    Assert.assertTrue(1 == receive.packetId());
    Assert.assertTrue(0 == receive.result());

    output.clear();
    send.heartbeat(true);
    send.serialize(output);

    Assert.assertTrue(output.readShort() == RemotingConstants.SAILFISH_MAGIC);
    receive = ResponseProtocol.newInstance();
    Assert.assertTrue(send == receive);
    receive.deserialize(output, output.readInt());
    Assert.assertTrue(receive.heartbeat());
}

From source file:se.sics.caracaldb.operations.SerializationTest.java

License:Open Source License

@Test
public void messageTest() throws UnknownHostException {
    InetAddress ip = InetAddress.getLocalHost();
    Address source = new Address(ip, 1234, "abcd".getBytes());
    Address dest = new Address(ip, 5678, "efgh".getBytes());

    Key k = Key.fromHex("1F 2F 3F 4F");
    byte[] data = "Some Data".getBytes();

    ByteBuf buf = Unpooled.buffer();

    OperationSerializer opS = CoreSerializer.OP.instance;

    // PUT/*  ww w .  j av  a 2  s  . c  o m*/
    // REQ
    PutRequest pr = new PutRequest(UUID.randomUUID(), k, data);
    CaracalMsg msg = new CaracalMsg(source, dest, pr);
    opS.toBinary(msg, buf);
    //TODO finish
    buf.clear();

    buf.release();
}

From source file:se.sics.caracaldb.paxos.SerializationTest.java

License:Open Source License

@Test
public void messageTest() throws UnknownHostException {
    InetAddress ip = InetAddress.getLocalHost();
    Address source = new Address(ip, 1234, "abcd".getBytes());
    Address dest = new Address(ip, 5678, "efgh".getBytes());

    ByteBuf buf = Unpooled.buffer();

    PaxosSerializer paxosS = CoreSerializer.PAXOS.instance;

    // PREPARE// w  ww  .j  av a  2s.c om
    Prepare prepare = new Prepare(source, dest, 1);
    paxosS.toBinary(prepare, buf);
    Prepare prepare2 = (Prepare) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(prepare.src, prepare2.src);
    Assert.assertEquals(prepare.dst, prepare2.dst);
    Assert.assertEquals(prepare.ballot, prepare2.ballot);
    buf.clear();

    // PROMISE
    Instance i = Instance.noop(10, 1);
    View v = new View(ImmutableSortedSet.of(source, dest), 1);
    Promise promise = new Promise(source, dest, 1, ImmutableSet.of(i), v);
    paxosS.toBinary(promise, buf);
    Promise promise2 = (Promise) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(promise.src, promise2.src);
    Assert.assertEquals(promise.dst, promise2.dst);
    Assert.assertEquals(promise.ballot, promise2.ballot);
    Assert.assertEquals(promise.maxInstances.size(), promise2.maxInstances.size());
    Assert.assertEquals(promise.view, promise2.view);
    buf.clear();

    // NO_PROMISE
    NoPromise noPromise = new NoPromise(source, dest, 1);
    paxosS.toBinary(noPromise, buf);
    NoPromise noPromise2 = (NoPromise) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(noPromise.src, noPromise2.src);
    Assert.assertEquals(noPromise.dst, noPromise2.dst);
    Assert.assertEquals(noPromise.ballot, noPromise2.ballot);
    buf.clear();

    // ACCEPT
    Accept accept = new Accept(source, dest, 1, i);
    paxosS.toBinary(accept, buf);
    Accept accept2 = (Accept) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(accept.src, accept2.src);
    Assert.assertEquals(accept.dst, accept2.dst);
    Assert.assertEquals(accept.ballot, accept2.ballot);
    Assert.assertEquals(accept.i, accept2.i);
    buf.clear();

    // ACCEPTED
    Accepted accepted = new Accepted(source, dest, 1, i, v);
    paxosS.toBinary(accepted, buf);
    Accepted accepted2 = (Accepted) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(accepted.src, accepted2.src);
    Assert.assertEquals(accepted.dst, accepted2.dst);
    Assert.assertEquals(accepted.ballot, accepted2.ballot);
    Assert.assertEquals(accepted.i, accepted2.i);
    Assert.assertEquals(accepted.view, accepted2.view);
    buf.clear();

    // REJECTED
    Rejected rejected = new Rejected(source, dest, 1, i);
    paxosS.toBinary(rejected, buf);
    Rejected rejected2 = (Rejected) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(rejected.src, rejected2.src);
    Assert.assertEquals(rejected.dst, rejected2.dst);
    Assert.assertEquals(rejected.ballot, rejected2.ballot);
    Assert.assertEquals(rejected.i, rejected2.i);
    buf.clear();

    // INSTALL
    Reconfigure reconf = new Reconfigure(new UUID(0, 1), v, 3, 0, KeyRange.EMPTY);
    ImmutableSortedMap<Long, Value> bla = ImmutableSortedMap.of(1l, (Value) Noop.val, 2l, (Value) Noop.val); // how hard can it be to detec covariance correctly -.-
    Install install = new Install(source, dest, 1, reconf, 10, bla);
    paxosS.toBinary(install, buf);
    Install install2 = (Install) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(install.src, install2.src);
    Assert.assertEquals(install.dst, install2.dst);
    Assert.assertEquals(install.ballot, install2.ballot);
    Assert.assertEquals(install.highestDecided, install2.highestDecided);
    Assert.assertEquals(install.event, install2.event);
    Assert.assertEquals(install.log.size(), install2.log.size());
    buf.clear();

    // FORWARD
    Forward forward = new Forward(source, dest, source, Noop.val);
    paxosS.toBinary(forward, buf);
    Forward forward2 = (Forward) paxosS.fromBinary(buf, Optional.absent());
    Assert.assertEquals(forward.src, forward2.src);
    Assert.assertEquals(forward.dst, forward2.dst);
    Assert.assertEquals(forward.orig, forward2.orig);
    Assert.assertEquals(forward.p, forward2.p);
    buf.clear();

    buf.release();
}

From source file:se.sics.kompics.network.netty.serialization.SerializationTest.java

License:Open Source License

@Test
public void addressTest() {
    try {//from   ww  w . j a  v  a  2  s .  c  om
        Address addr = new Address(InetAddress.getByName("127.0.0.1"), 1234, new byte[] { 1, 2, 3, 4 });
        Address hostAddr = addr.hostAddress();
        ByteBuf buf = Unpooled.directBuffer();
        Serializers.toBinary(addr, buf);
        System.out.println("Address: " + ByteBufUtil.hexDump(buf));
        Address someRes = (Address) Serializers.fromBinary(buf, Optional.absent());
        assertEquals(addr, someRes);

        buf.clear();

        Serializers.toBinary(hostAddr, buf);
        System.out.println("HostAddress: " + ByteBufUtil.hexDump(buf));
        Address someHostRes = (Address) Serializers.fromBinary(buf, Optional.absent());
        assertEquals(hostAddr, someHostRes);

        buf.release();
    } catch (UnknownHostException ex) {
        Assert.fail(ex.getMessage());
    }
}

From source file:se.sics.kompics.network.netty.serialization.SerializationTest.java

License:Open Source License

@Test
public void disambTest() {
    for (Transport proto : Transport.values()) {
        try {//w ww  . j  av a2s. c o m
            Address src = new Address(InetAddress.getByName("127.0.0.1"), 1234, new byte[] { 1, 2, 3, 4 });
            Address dst = new Address(InetAddress.getByName("127.0.0.1"), 5678, new byte[] { 5, 6, 7, 8 });
            DisambiguateConnection.Req req = new DisambiguateConnection.Req(src, dst, proto, 1234, 5678);
            DisambiguateConnection.Resp resp = new DisambiguateConnection.Resp(src, dst, proto, 1234, 5678,
                    9876);
            ByteBuf buf = Unpooled.directBuffer();
            Serializers.toBinary(req, buf);
            System.out.println("DisambReq: " + ByteBufUtil.hexDump(buf));
            Object someRes = Serializers.fromBinary(buf, Optional.absent());
            Assert.assertNotNull(someRes);
            someRes = null;
            buf.clear();
            Serializers.toBinary(resp, buf);
            System.out.println("DisambResp: " + ByteBufUtil.hexDump(buf));
            someRes = Serializers.fromBinary(buf, Optional.absent());
            Assert.assertNotNull(someRes);
        } catch (UnknownHostException ex) {
            Assert.fail(ex.getMessage());
        }
    }
}

From source file:se.sics.kompics.network.netty.serialization.SerializationTest.java

License:Open Source License

@Test
public void avroTest() throws AvroSerializer.KeyExistsException, AvroSerializer.InvalidKeyException {
    Serializers.register(new AvroSerializer(), "avroS");
    AvroSerializer.register(15, SomeAvro.class);
    Serializers.register(ParentSomeAvro.class, "avroS");
    AvroSerializer.register(16, SomeGeneratedAvro.class);
    SomeAvro some = new SomeAvro();
    ByteBuf buf = Unpooled.directBuffer();
    Serializers.toBinary(some, buf);/*w ww .j  av a  2  s.  c  o  m*/
    System.out.println(
            "AVRO - SomeAvro: " + ByteBufUtil.hexDump(buf) + " : " + ByteBufUtil.hexDump(buf).length());
    SomeAvro someRes = (SomeAvro) Serializers.fromBinary(buf, Optional.absent());
    assertEquals(some.getField(), someRes.getField());
    //
    buf.clear();
    //
    ParentSomeAvro someP = new ParentSomeAvro(some);
    Serializers.toBinary(someP, buf);
    System.out.println(
            "AVRO - ParentSomeAvro: " + ByteBufUtil.hexDump(buf) + " : " + ByteBufUtil.hexDump(buf).length());
    ParentSomeAvro somePRes = (ParentSomeAvro) Serializers.fromBinary(buf, Optional.absent());
    assertEquals(someP.getMySer().getField(), somePRes.getMySer().getField());
    //
    buf.clear();
    //
    SomeGeneratedAvro sga = SomeGeneratedAvro.newBuilder().setSomeNumber(1234).build();
    Serializers.toBinary(sga, buf);
    System.out.println("AVRO - SomeGeneratedAvro: " + ByteBufUtil.hexDump(buf) + " : "
            + ByteBufUtil.hexDump(buf).length());
    SomeGeneratedAvro sgaR = (SomeGeneratedAvro) Serializers.fromBinary(buf, Optional.absent());
    assertEquals(sga.getSomeNumber(), sgaR.getSomeNumber());
    //
    buf.release();
}

From source file:sh.lab.jcorrelat.MessageDecoder.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {
    in.readBytes(this.buffer, 0, in.readableBytes());
    in.clear();

    LOG.trace("Received line: {}", this.buffer);

    final Message message = this.mapper.readValue(this.buffer, Message.class);

    LOG.trace("Received message: {}", message);

    out.add(message);//from w  w w . ja va2s.co m

    in.retain();
}

From source file:starbounddata.packets.Packet.java

License:Open Source License

/**
 * Recommended: For connections StarNub usage.
 * <p>/*  ww w  .j  a v  a  2s .com*/
 * Uses: This method will write to a {@link io.netty.buffer.ByteBuf} using this packets fields
 * <p>
 *
 * @return ByteBuf representing the ByteBuf to write to socket
 */
protected ByteBuf packetToMessageEncoder() {
    ByteBuf msgOut = PooledByteBufAllocator.DEFAULT.directBuffer();
    this.write(msgOut);
    int payloadLengthOut = msgOut.readableBytes();
    byte[] dataOut;
    if (payloadLengthOut > 100) {
        dataOut = Zlib.compress(msgOut.readBytes(payloadLengthOut).array());
        payloadLengthOut = -dataOut.length;
    } else {
        dataOut = msgOut.readBytes(payloadLengthOut).array();
    }
    msgOut.clear();
    msgOut.writeByte(PACKET_ID);
    writeSVLQPacketEncoder(msgOut, payloadLengthOut);
    msgOut.writeBytes(dataOut);
    return msgOut;
}

From source file:z.offheap.buffer.BufferTest3.java

License:Open Source License

@Test
public void sanitycheck() {
    System.out.println("start to sanity check...");

    ByteBuffer buffer = Buffer.create(5 * 8);

    ByteBuf nettyBuf = PooledByteBufAllocator.DEFAULT.directBuffer(5 * 8);

    buffer.clear().write((byte) 1).skipWriteTo(4).networkOrder().writeShortN((short) 2).writeIntN(12345)
            .write((byte) 123).writeCharN('[').writeFloatN(3.14159f).writeDoubleN(1.9999d).writeLongN(-2L)
            .write((byte) -1).writeCharN(']').writeIntN(Integer.MIN_VALUE);
    //4+2+4+1+2+4+8+8+1+2
    //8+8+8+8+4 -> 5*Long

    nettyBuf.clear().writeByte(1).writeByte(0).writeByte(0).writeByte(0).writeShort(2).writeInt(12345)
            .writeByte(123).writeChar('[').writeFloat(3.14159f).writeDouble(1.9999d).writeLong(-2L)
            .writeByte(-1).writeChar(']').writeInt(Integer.MIN_VALUE);

    long r1 = buffer.networkOrder().readLongN();
    long r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));//www  .  java 2  s.  c  o m

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    r1 = buffer.networkOrder().readLongN();
    r2 = nettyBuf.readLong();
    assertThat(r1, is(r2));

    buffer.close();
}